From 04bc2145a1990f419f637b7c17996feb2ce8f6b2 Mon Sep 17 00:00:00 2001 From: Christian Koop Date: Sat, 30 Oct 2021 14:09:08 +0200 Subject: [PATCH 01/18] ClientVersion: Adds 1.17.1 protocol version --- .../main/java/com/songoda/core/compatibility/ClientVersion.java | 1 + 1 file changed, 1 insertion(+) diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/ClientVersion.java b/Compatibility/src/main/java/com/songoda/core/compatibility/ClientVersion.java index 92b0daed..45377410 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/ClientVersion.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/ClientVersion.java @@ -101,6 +101,7 @@ public class ClientVersion { case 754: return ServerVersion.V1_16; case 755: + case 756: return ServerVersion.V1_17; } return version > 498 ? ServerVersion.getServerVersion() : ServerVersion.UNKNOWN; From a23224dbe2afdee76d1b94327f9c60480585b0a2 Mon Sep 17 00:00:00 2001 From: Christian Koop Date: Sat, 30 Oct 2021 14:09:45 +0200 Subject: [PATCH 02/18] ClientVersion: Fixes default version trying to return the server version --- .../com/songoda/core/compatibility/ClientVersion.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/ClientVersion.java b/Compatibility/src/main/java/com/songoda/core/compatibility/ClientVersion.java index 45377410..eabf1d69 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/ClientVersion.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/ClientVersion.java @@ -59,8 +59,8 @@ public class ClientVersion { } private static ServerVersion protocolToVersion(int version) { - // https://github.com/ViaVersion/ViaVersion/blob/master/common/src/main/java/us/myles/ViaVersion/api/protocol/ProtocolVersion.java - // https://github.com/ProtocolSupport/ProtocolSupport/blob/master/src/protocolsupport/api/ProtocolVersion.java + // https://wiki.vg/Protocol_version_numbers#Versions_after_the_Netty_rewrite + // https://github.com/ViaVersion/ViaVersion/blob/master/api/src/main/java/com/viaversion/viaversion/api/protocol/version/ProtocolVersion.java switch (version) { case 4: case 5: @@ -103,8 +103,10 @@ public class ClientVersion { case 755: case 756: return ServerVersion.V1_17; + + default: + return version > 756 ? ServerVersion.getServerVersion() : ServerVersion.UNKNOWN; } - return version > 498 ? ServerVersion.getServerVersion() : ServerVersion.UNKNOWN; } /** From 92f42e62614d708e50fa021ffe0bd09603ab9e29 Mon Sep 17 00:00:00 2001 From: Christian Koop Date: Sun, 26 Sep 2021 14:55:32 +0200 Subject: [PATCH 03/18] Update EditorConfig [DEV-2] --- .editorconfig | 736 +++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 670 insertions(+), 66 deletions(-) diff --git a/.editorconfig b/.editorconfig index 9737e6fa..c42c1d9a 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,3 +1,7 @@ +# This EditorConfig aims to achieve compact code while allowing a file's content to be understood easily + +root = true + [*] charset = utf-8 end_of_line = lf @@ -15,8 +19,127 @@ ij_smart_tabs = false ij_visual_guides = none ij_wrap_on_typing = false + +## +# Common file formats +## +[*.properties] +ij_properties_align_group_field_declarations = false +ij_properties_keep_blank_lines = false +ij_properties_key_value_delimiter = equals +ij_properties_spaces_around_key_value_delimiter = false + +[{*.yaml,*.yml}] +indent_size = 2 +ij_yaml_align_values_properties = do_not_align +ij_yaml_autoinsert_sequence_marker = true +ij_yaml_block_mapping_on_new_line = false +ij_yaml_indent_sequence_value = true +ij_yaml_keep_indents_on_empty_lines = false +ij_yaml_keep_line_breaks = true +ij_yaml_sequence_on_new_line = false +ij_yaml_space_before_colon = false +ij_yaml_spaces_within_braces = true +ij_yaml_spaces_within_brackets = true + +[{*.json,*.graphqlconfig,*.har,*.jsb2,*.jsb3,*.webmanifest,.babelrc,.eslintrc,.prettierrc,.stylelintrc,bowerrc,jest.config}] +indent_size = 2 +ij_json_keep_blank_lines_in_code = 0 +ij_json_keep_indents_on_empty_lines = false +ij_json_keep_line_breaks = true +ij_json_space_after_colon = true +ij_json_space_after_comma = true +ij_json_space_before_colon = true +ij_json_space_before_comma = false +ij_json_spaces_within_braces = false +ij_json_spaces_within_brackets = false +ij_json_wrap_long_lines = false + +[{*.xml,*.ant,*.fxml,*.jhm,*.jnlp,*.jrxml,*.mpd,*.pom,*.rng,*.tld,*.wsdl,*.xsd,*.xsl,*.xslt,*.xul}] +ij_xml_align_attributes = true +ij_xml_align_text = false +ij_xml_attribute_wrap = normal +ij_xml_block_comment_at_first_column = true +ij_xml_keep_blank_lines = 2 +ij_xml_keep_indents_on_empty_lines = false +ij_xml_keep_line_breaks = true +ij_xml_keep_line_breaks_in_text = true +ij_xml_keep_whitespaces = false +ij_xml_keep_whitespaces_around_cdata = preserve +ij_xml_keep_whitespaces_inside_cdata = false +ij_xml_line_comment_at_first_column = true +ij_xml_space_after_tag_name = false +ij_xml_space_around_equals_in_attribute = false +ij_xml_space_inside_empty_tag = false +ij_xml_text_wrap = normal + + +## +# MarkDown +# TODO: Not happy with this yet +## +[{*.markdown,*.md}] +indent_size = 2 +tab_width = 2 +ij_continuation_indent_size = 4 + + +## +# HTML + CSS +## +[{*.html,*.htm,*.ng,*.sht,*.shtm,*.shtml}] +indent_size = 2 +tab_width = 2 +ij_continuation_indent_size = 4 +ij_html_add_new_line_before_tags = body, div, p, form, h1, h2, h3 +ij_html_align_attributes = true +ij_html_align_text = false +ij_html_attribute_wrap = normal +ij_html_block_comment_at_first_column = true +ij_html_do_not_align_children_of_min_lines = 0 +ij_html_do_not_break_if_inline_tags = title, h1, h2, h3, h4, h5, h6, p, li +ij_html_do_not_indent_children_of_tags = html, body, thead, tbody, tfoot +ij_html_enforce_quotes = true +ij_html_inline_tags = a, abbr, acronym, b, basefont, bdo, big, br, cite, cite, code, dfn, em, font, i, img, input, kbd, label, q, s, samp, select, small, span, strike, strong, sub, sup, textarea, tt, u, var +ij_html_keep_blank_lines = 2 +ij_html_keep_indents_on_empty_lines = false +ij_html_keep_line_breaks = true +ij_html_keep_line_breaks_in_text = true +ij_html_keep_whitespaces = false +ij_html_keep_whitespaces_inside = span, pre, textarea +ij_html_line_comment_at_first_column = true +ij_html_new_line_after_last_attribute = never +ij_html_new_line_before_first_attribute = never +ij_html_quote_style = double +ij_html_remove_new_line_before_tags = br +ij_html_space_after_tag_name = false +ij_html_space_around_equality_in_attribute = false +ij_html_space_inside_empty_tag = false +ij_html_text_wrap = normal + +[*.css] +ij_css_align_closing_brace_with_properties = false +ij_css_blank_lines_around_nested_selector = 1 +ij_css_blank_lines_between_blocks = 1 +ij_css_brace_placement = end_of_line +ij_css_enforce_quotes_on_format = true +ij_css_hex_color_long_format = false +ij_css_hex_color_lower_case = true +ij_css_hex_color_short_format = true +ij_css_hex_color_upper_case = false +ij_css_keep_blank_lines_in_code = 2 +ij_css_keep_indents_on_empty_lines = false +ij_css_keep_single_line_blocks = false +ij_css_properties_order = font, font-family, font-size, font-weight, font-style, font-variant, font-size-adjust, font-stretch, line-height, position, z-index, top, right, bottom, left, display, visibility, float, clear, overflow, overflow-x, overflow-y, clip, zoom, align-content, align-items, align-self, flex, flex-flow, flex-basis, flex-direction, flex-grow, flex-shrink, flex-wrap, justify-content, order, box-sizing, width, min-width, max-width, height, min-height, max-height, margin, margin-top, margin-right, margin-bottom, margin-left, padding, padding-top, padding-right, padding-bottom, padding-left, table-layout, empty-cells, caption-side, border-spacing, border-collapse, list-style, list-style-position, list-style-type, list-style-image, content, quotes, counter-reset, counter-increment, resize, cursor, user-select, nav-index, nav-up, nav-right, nav-down, nav-left, transition, transition-delay, transition-timing-function, transition-duration, transition-property, transform, transform-origin, animation, animation-name, animation-duration, animation-play-state, animation-timing-function, animation-delay, animation-iteration-count, animation-direction, text-align, text-align-last, vertical-align, white-space, text-decoration, text-emphasis, text-emphasis-color, text-emphasis-style, text-emphasis-position, text-indent, text-justify, letter-spacing, word-spacing, text-outline, text-transform, text-wrap, text-overflow, text-overflow-ellipsis, text-overflow-mode, word-wrap, word-break, tab-size, hyphens, pointer-events, opacity, color, border, border-width, border-style, border-color, border-top, border-top-width, border-top-style, border-top-color, border-right, border-right-width, border-right-style, border-right-color, border-bottom, border-bottom-width, border-bottom-style, border-bottom-color, border-left, border-left-width, border-left-style, border-left-color, border-radius, border-top-left-radius, border-top-right-radius, border-bottom-right-radius, border-bottom-left-radius, border-image, border-image-source, border-image-slice, border-image-width, border-image-outset, border-image-repeat, outline, outline-width, outline-style, outline-color, outline-offset, background, background-color, background-image, background-repeat, background-attachment, background-position, background-position-x, background-position-y, background-clip, background-origin, background-size, box-decoration-break, box-shadow, text-shadow +ij_css_space_after_colon = true +ij_css_space_before_opening_brace = true +ij_css_use_double_quotes = true +ij_css_value_alignment = on_value + +## +# Java + Gradle +## [*.java] -ij_smart_tabs = true ij_java_align_consecutive_assignments = false ij_java_align_consecutive_variable_declarations = false ij_java_align_group_field_declarations = false @@ -71,7 +194,7 @@ ij_java_case_statement_on_separate_line = true ij_java_catch_on_new_line = false ij_java_class_annotation_wrap = split_into_lines ij_java_class_brace_style = end_of_line -ij_java_class_count_to_use_import_on_demand = 15 +ij_java_class_count_to_use_import_on_demand = 999 ij_java_class_names_in_javadoc = 1 ij_java_do_not_indent_top_level_class_members = false ij_java_do_not_wrap_after_single_annotation = false @@ -79,10 +202,10 @@ ij_java_do_while_brace_force = never ij_java_doc_add_blank_line_after_description = true ij_java_doc_add_blank_line_after_param_comments = true ij_java_doc_add_blank_line_after_return = true -ij_java_doc_add_p_tag_on_empty_lines = true +ij_java_doc_add_p_tag_on_empty_lines = false ij_java_doc_align_exception_comments = true ij_java_doc_align_param_comments = true -ij_java_doc_do_not_wrap_if_one_line = true +ij_java_doc_do_not_wrap_if_one_line = false ij_java_doc_enable_formatting = true ij_java_doc_enable_leading_asterisks = true ij_java_doc_indent_on_continuation = true @@ -111,10 +234,10 @@ ij_java_imports_layout = *, |, javax.**, java.**, |, $* ij_java_indent_case_from_switch = true ij_java_insert_inner_class_imports = false ij_java_insert_override_annotation = true -ij_java_keep_blank_lines_before_right_brace = 0 -ij_java_keep_blank_lines_between_package_declaration_and_header = 0 -ij_java_keep_blank_lines_in_code = 1 -ij_java_keep_blank_lines_in_declarations = 1 +ij_java_keep_blank_lines_before_right_brace = 2 +ij_java_keep_blank_lines_between_package_declaration_and_header = 2 +ij_java_keep_blank_lines_in_code = 2 +ij_java_keep_blank_lines_in_declarations = 2 ij_java_keep_builder_methods_indents = false ij_java_keep_control_statement_in_one_line = true ij_java_keep_first_column_comment = true @@ -122,9 +245,9 @@ ij_java_keep_indents_on_empty_lines = false ij_java_keep_line_breaks = true ij_java_keep_multiple_expressions_in_one_line = false ij_java_keep_simple_blocks_in_one_line = false -ij_java_keep_simple_classes_in_one_line = true -ij_java_keep_simple_lambdas_in_one_line = true -ij_java_keep_simple_methods_in_one_line = true +ij_java_keep_simple_classes_in_one_line = false +ij_java_keep_simple_lambdas_in_one_line = false +ij_java_keep_simple_methods_in_one_line = false ij_java_label_indent_absolute = false ij_java_label_indent_size = 0 ij_java_lambda_brace_style = end_of_line @@ -138,9 +261,9 @@ ij_java_method_parameters_new_line_after_left_paren = false ij_java_method_parameters_right_paren_on_new_line = false ij_java_method_parameters_wrap = off ij_java_modifier_list_wrap = false -ij_java_names_count_to_use_import_on_demand = 9 +ij_java_names_count_to_use_import_on_demand = 999 ij_java_new_line_after_lparen_in_record_header = false -ij_java_packages_to_use_import_on_demand = _java.awt.*, _javax.swing.* +ij_java_packages_to_use_import_on_demand = java.awt.*, javax.swing.* ij_java_parameter_annotation_wrap = off ij_java_parentheses_expression_new_line_after_left_paren = false ij_java_parentheses_expression_right_paren_on_new_line = false @@ -199,7 +322,7 @@ ij_java_space_before_while_keyword = true ij_java_space_before_while_left_brace = true ij_java_space_before_while_parentheses = true ij_java_space_inside_one_line_enum_braces = false -ij_java_space_within_empty_array_initializer_braces = true +ij_java_space_within_empty_array_initializer_braces = false ij_java_space_within_empty_method_call_parentheses = false ij_java_space_within_empty_method_parentheses = false ij_java_spaces_around_additive_operators = true @@ -217,7 +340,7 @@ ij_java_spaces_around_unary_operator = false ij_java_spaces_within_angle_brackets = false ij_java_spaces_within_annotation_parentheses = false ij_java_spaces_within_array_initializer_braces = false -ij_java_spaces_within_braces = true +ij_java_spaces_within_braces = false ij_java_spaces_within_brackets = false ij_java_spaces_within_cast_parentheses = false ij_java_spaces_within_catch_parentheses = false @@ -250,12 +373,539 @@ ij_java_wrap_comments = false ij_java_wrap_first_method_in_call_chain = false ij_java_wrap_long_lines = false -[*.properties] -ij_properties_align_group_field_declarations = false -ij_properties_keep_blank_lines = false -ij_properties_key_value_delimiter = equals -ij_properties_spaces_around_key_value_delimiter = false +[{*.gradle,*.gant,*.groovy,*.gy}] +ij_groovy_align_group_field_declarations = false +ij_groovy_align_multiline_array_initializer_expression = false +ij_groovy_align_multiline_assignment = false +ij_groovy_align_multiline_binary_operation = false +ij_groovy_align_multiline_chained_methods = false +ij_groovy_align_multiline_extends_list = false +ij_groovy_align_multiline_for = true +ij_groovy_align_multiline_list_or_map = true +ij_groovy_align_multiline_method_parentheses = false +ij_groovy_align_multiline_parameters = true +ij_groovy_align_multiline_parameters_in_calls = false +ij_groovy_align_multiline_resources = true +ij_groovy_align_multiline_ternary_operation = false +ij_groovy_align_multiline_throws_list = false +ij_groovy_align_named_args_in_map = true +ij_groovy_align_throws_keyword = false +ij_groovy_array_initializer_new_line_after_left_brace = false +ij_groovy_array_initializer_right_brace_on_new_line = false +ij_groovy_array_initializer_wrap = off +ij_groovy_assert_statement_wrap = off +ij_groovy_assignment_wrap = off +ij_groovy_binary_operation_wrap = off +ij_groovy_blank_lines_after_class_header = 0 +ij_groovy_blank_lines_after_imports = 1 +ij_groovy_blank_lines_after_package = 1 +ij_groovy_blank_lines_around_class = 1 +ij_groovy_blank_lines_around_field = 0 +ij_groovy_blank_lines_around_field_in_interface = 0 +ij_groovy_blank_lines_around_method = 1 +ij_groovy_blank_lines_around_method_in_interface = 1 +ij_groovy_blank_lines_before_imports = 1 +ij_groovy_blank_lines_before_method_body = 0 +ij_groovy_blank_lines_before_package = 0 +ij_groovy_block_brace_style = end_of_line +ij_groovy_block_comment_at_first_column = true +ij_groovy_call_parameters_new_line_after_left_paren = false +ij_groovy_call_parameters_right_paren_on_new_line = false +ij_groovy_call_parameters_wrap = off +ij_groovy_catch_on_new_line = false +ij_groovy_class_annotation_wrap = split_into_lines +ij_groovy_class_brace_style = end_of_line +ij_groovy_class_count_to_use_import_on_demand = 5 +ij_groovy_do_while_brace_force = never +ij_groovy_else_on_new_line = false +ij_groovy_enum_constants_wrap = off +ij_groovy_extends_keyword_wrap = off +ij_groovy_extends_list_wrap = off +ij_groovy_field_annotation_wrap = split_into_lines +ij_groovy_finally_on_new_line = false +ij_groovy_for_brace_force = never +ij_groovy_for_statement_new_line_after_left_paren = false +ij_groovy_for_statement_right_paren_on_new_line = false +ij_groovy_for_statement_wrap = off +ij_groovy_if_brace_force = never +ij_groovy_import_annotation_wrap = 2 +ij_groovy_imports_layout = *, |, javax.**, java.**, |, $* +ij_groovy_indent_case_from_switch = true +ij_groovy_indent_label_blocks = true +ij_groovy_insert_inner_class_imports = false +ij_groovy_keep_blank_lines_before_right_brace = 2 +ij_groovy_keep_blank_lines_in_code = 2 +ij_groovy_keep_blank_lines_in_declarations = 2 +ij_groovy_keep_control_statement_in_one_line = true +ij_groovy_keep_first_column_comment = true +ij_groovy_keep_indents_on_empty_lines = false +ij_groovy_keep_line_breaks = true +ij_groovy_keep_multiple_expressions_in_one_line = false +ij_groovy_keep_simple_blocks_in_one_line = false +ij_groovy_keep_simple_classes_in_one_line = true +ij_groovy_keep_simple_lambdas_in_one_line = true +ij_groovy_keep_simple_methods_in_one_line = true +ij_groovy_label_indent_absolute = false +ij_groovy_label_indent_size = 0 +ij_groovy_lambda_brace_style = end_of_line +ij_groovy_layout_static_imports_separately = true +ij_groovy_line_comment_add_space = false +ij_groovy_line_comment_at_first_column = true +ij_groovy_method_annotation_wrap = split_into_lines +ij_groovy_method_brace_style = end_of_line +ij_groovy_method_call_chain_wrap = off +ij_groovy_method_parameters_new_line_after_left_paren = false +ij_groovy_method_parameters_right_paren_on_new_line = false +ij_groovy_method_parameters_wrap = off +ij_groovy_modifier_list_wrap = false +ij_groovy_names_count_to_use_import_on_demand = 3 +ij_groovy_parameter_annotation_wrap = off +ij_groovy_parentheses_expression_new_line_after_left_paren = false +ij_groovy_parentheses_expression_right_paren_on_new_line = false +ij_groovy_prefer_parameters_wrap = false +ij_groovy_resource_list_new_line_after_left_paren = false +ij_groovy_resource_list_right_paren_on_new_line = false +ij_groovy_resource_list_wrap = off +ij_groovy_space_after_assert_separator = true +ij_groovy_space_after_colon = true +ij_groovy_space_after_comma = true +ij_groovy_space_after_comma_in_type_arguments = true +ij_groovy_space_after_for_semicolon = true +ij_groovy_space_after_quest = true +ij_groovy_space_after_type_cast = true +ij_groovy_space_before_annotation_parameter_list = false +ij_groovy_space_before_array_initializer_left_brace = false +ij_groovy_space_before_assert_separator = false +ij_groovy_space_before_catch_keyword = true +ij_groovy_space_before_catch_left_brace = true +ij_groovy_space_before_catch_parentheses = true +ij_groovy_space_before_class_left_brace = true +ij_groovy_space_before_closure_left_brace = true +ij_groovy_space_before_colon = true +ij_groovy_space_before_comma = false +ij_groovy_space_before_do_left_brace = true +ij_groovy_space_before_else_keyword = true +ij_groovy_space_before_else_left_brace = true +ij_groovy_space_before_finally_keyword = true +ij_groovy_space_before_finally_left_brace = true +ij_groovy_space_before_for_left_brace = true +ij_groovy_space_before_for_parentheses = true +ij_groovy_space_before_for_semicolon = false +ij_groovy_space_before_if_left_brace = true +ij_groovy_space_before_if_parentheses = true +ij_groovy_space_before_method_call_parentheses = false +ij_groovy_space_before_method_left_brace = true +ij_groovy_space_before_method_parentheses = false +ij_groovy_space_before_quest = true +ij_groovy_space_before_switch_left_brace = true +ij_groovy_space_before_switch_parentheses = true +ij_groovy_space_before_synchronized_left_brace = true +ij_groovy_space_before_synchronized_parentheses = true +ij_groovy_space_before_try_left_brace = true +ij_groovy_space_before_try_parentheses = true +ij_groovy_space_before_while_keyword = true +ij_groovy_space_before_while_left_brace = true +ij_groovy_space_before_while_parentheses = true +ij_groovy_space_in_named_argument = true +ij_groovy_space_in_named_argument_before_colon = false +ij_groovy_space_within_empty_array_initializer_braces = false +ij_groovy_space_within_empty_method_call_parentheses = false +ij_groovy_spaces_around_additive_operators = true +ij_groovy_spaces_around_assignment_operators = true +ij_groovy_spaces_around_bitwise_operators = true +ij_groovy_spaces_around_equality_operators = true +ij_groovy_spaces_around_lambda_arrow = true +ij_groovy_spaces_around_logical_operators = true +ij_groovy_spaces_around_multiplicative_operators = true +ij_groovy_spaces_around_regex_operators = true +ij_groovy_spaces_around_relational_operators = true +ij_groovy_spaces_around_shift_operators = true +ij_groovy_spaces_within_annotation_parentheses = false +ij_groovy_spaces_within_array_initializer_braces = false +ij_groovy_spaces_within_braces = true +ij_groovy_spaces_within_brackets = false +ij_groovy_spaces_within_cast_parentheses = false +ij_groovy_spaces_within_catch_parentheses = false +ij_groovy_spaces_within_for_parentheses = false +ij_groovy_spaces_within_gstring_injection_braces = false +ij_groovy_spaces_within_if_parentheses = false +ij_groovy_spaces_within_list_or_map = false +ij_groovy_spaces_within_method_call_parentheses = false +ij_groovy_spaces_within_method_parentheses = false +ij_groovy_spaces_within_parentheses = false +ij_groovy_spaces_within_switch_parentheses = false +ij_groovy_spaces_within_synchronized_parentheses = false +ij_groovy_spaces_within_try_parentheses = false +ij_groovy_spaces_within_tuple_expression = false +ij_groovy_spaces_within_while_parentheses = false +ij_groovy_special_else_if_treatment = true +ij_groovy_ternary_operation_wrap = off +ij_groovy_throws_keyword_wrap = off +ij_groovy_throws_list_wrap = off +ij_groovy_use_flying_geese_braces = false +ij_groovy_use_fq_class_names = false +ij_groovy_use_fq_class_names_in_javadoc = true +ij_groovy_use_relative_indents = false +ij_groovy_use_single_class_imports = true +ij_groovy_variable_annotation_wrap = off +ij_groovy_while_brace_force = never +ij_groovy_while_on_new_line = false +ij_groovy_wrap_chain_calls_after_dot = false +ij_groovy_wrap_long_lines = false + +## +# TypeScript / JavaScript +## +[{*.ts,*.ats}] +indent_size = 2 +tab_width = 2 +ij_continuation_indent_size = 4 +ij_typescript_align_imports = false +ij_typescript_align_multiline_array_initializer_expression = false +ij_typescript_align_multiline_binary_operation = false +ij_typescript_align_multiline_chained_methods = false +ij_typescript_align_multiline_extends_list = false +ij_typescript_align_multiline_for = true +ij_typescript_align_multiline_parameters = true +ij_typescript_align_multiline_parameters_in_calls = false +ij_typescript_align_multiline_ternary_operation = false +ij_typescript_align_object_properties = 0 +ij_typescript_align_union_types = false +ij_typescript_align_var_statements = 0 +ij_typescript_array_initializer_new_line_after_left_brace = false +ij_typescript_array_initializer_right_brace_on_new_line = false +ij_typescript_array_initializer_wrap = off +ij_typescript_assignment_wrap = off +ij_typescript_binary_operation_sign_on_next_line = false +ij_typescript_binary_operation_wrap = off +ij_typescript_blacklist_imports = rxjs/Rx, node_modules/**, **/node_modules/**, @angular/material, @angular/material/typings/** +ij_typescript_blank_lines_after_imports = 1 +ij_typescript_blank_lines_around_class = 1 +ij_typescript_blank_lines_around_field = 0 +ij_typescript_blank_lines_around_field_in_interface = 0 +ij_typescript_blank_lines_around_function = 1 +ij_typescript_blank_lines_around_method = 1 +ij_typescript_blank_lines_around_method_in_interface = 1 +ij_typescript_block_brace_style = end_of_line +ij_typescript_call_parameters_new_line_after_left_paren = false +ij_typescript_call_parameters_right_paren_on_new_line = false +ij_typescript_call_parameters_wrap = off +ij_typescript_catch_on_new_line = false +ij_typescript_chained_call_dot_on_new_line = true +ij_typescript_class_brace_style = end_of_line +ij_typescript_comma_on_new_line = false +ij_typescript_do_while_brace_force = never +ij_typescript_else_on_new_line = false +ij_typescript_enforce_trailing_comma = remove +ij_typescript_extends_keyword_wrap = off +ij_typescript_extends_list_wrap = off +ij_typescript_field_prefix = _ +ij_typescript_file_name_style = relaxed +ij_typescript_finally_on_new_line = false +ij_typescript_for_brace_force = never +ij_typescript_for_statement_new_line_after_left_paren = false +ij_typescript_for_statement_right_paren_on_new_line = false +ij_typescript_for_statement_wrap = off +ij_typescript_force_quote_style = true +ij_typescript_force_semicolon_style = true +ij_typescript_function_expression_brace_style = end_of_line +ij_typescript_if_brace_force = never +ij_typescript_import_merge_members = global +ij_typescript_import_prefer_absolute_path = global +ij_typescript_import_sort_members = true +ij_typescript_import_sort_module_name = true +ij_typescript_import_use_node_resolution = true +ij_typescript_imports_wrap = on_every_item +ij_typescript_indent_case_from_switch = true +ij_typescript_indent_chained_calls = true +ij_typescript_indent_package_children = 0 +ij_typescript_jsdoc_include_types = false +ij_typescript_jsx_attribute_value = braces +ij_typescript_keep_blank_lines_in_code = 2 +ij_typescript_keep_first_column_comment = true +ij_typescript_keep_indents_on_empty_lines = false +ij_typescript_keep_line_breaks = true +ij_typescript_keep_simple_blocks_in_one_line = false +ij_typescript_keep_simple_methods_in_one_line = false +ij_typescript_line_comment_add_space = true +ij_typescript_line_comment_at_first_column = false +ij_typescript_method_brace_style = end_of_line +ij_typescript_method_call_chain_wrap = off +ij_typescript_method_parameters_new_line_after_left_paren = false +ij_typescript_method_parameters_right_paren_on_new_line = false +ij_typescript_method_parameters_wrap = off +ij_typescript_object_literal_wrap = on_every_item +ij_typescript_parentheses_expression_new_line_after_left_paren = false +ij_typescript_parentheses_expression_right_paren_on_new_line = false +ij_typescript_place_assignment_sign_on_next_line = false +ij_typescript_prefer_as_type_cast = false +ij_typescript_prefer_explicit_types_function_expression_returns = false +ij_typescript_prefer_explicit_types_function_returns = false +ij_typescript_prefer_explicit_types_vars_fields = false +ij_typescript_prefer_parameters_wrap = false +ij_typescript_reformat_c_style_comments = false +ij_typescript_space_after_colon = true +ij_typescript_space_after_comma = true +ij_typescript_space_after_dots_in_rest_parameter = false +ij_typescript_space_after_generator_mult = true +ij_typescript_space_after_property_colon = true +ij_typescript_space_after_quest = true +ij_typescript_space_after_type_colon = true +ij_typescript_space_after_unary_not = false +ij_typescript_space_before_async_arrow_lparen = true +ij_typescript_space_before_catch_keyword = true +ij_typescript_space_before_catch_left_brace = true +ij_typescript_space_before_catch_parentheses = true +ij_typescript_space_before_class_lbrace = true +ij_typescript_space_before_class_left_brace = true +ij_typescript_space_before_colon = true +ij_typescript_space_before_comma = false +ij_typescript_space_before_do_left_brace = true +ij_typescript_space_before_else_keyword = true +ij_typescript_space_before_else_left_brace = true +ij_typescript_space_before_finally_keyword = true +ij_typescript_space_before_finally_left_brace = true +ij_typescript_space_before_for_left_brace = true +ij_typescript_space_before_for_parentheses = true +ij_typescript_space_before_for_semicolon = false +ij_typescript_space_before_function_left_parenth = true +ij_typescript_space_before_generator_mult = false +ij_typescript_space_before_if_left_brace = true +ij_typescript_space_before_if_parentheses = true +ij_typescript_space_before_method_call_parentheses = false +ij_typescript_space_before_method_left_brace = true +ij_typescript_space_before_method_parentheses = false +ij_typescript_space_before_property_colon = false +ij_typescript_space_before_quest = true +ij_typescript_space_before_switch_left_brace = true +ij_typescript_space_before_switch_parentheses = true +ij_typescript_space_before_try_left_brace = true +ij_typescript_space_before_type_colon = false +ij_typescript_space_before_unary_not = false +ij_typescript_space_before_while_keyword = true +ij_typescript_space_before_while_left_brace = true +ij_typescript_space_before_while_parentheses = true +ij_typescript_spaces_around_additive_operators = true +ij_typescript_spaces_around_arrow_function_operator = true +ij_typescript_spaces_around_assignment_operators = true +ij_typescript_spaces_around_bitwise_operators = true +ij_typescript_spaces_around_equality_operators = true +ij_typescript_spaces_around_logical_operators = true +ij_typescript_spaces_around_multiplicative_operators = true +ij_typescript_spaces_around_relational_operators = true +ij_typescript_spaces_around_shift_operators = true +ij_typescript_spaces_around_unary_operator = false +ij_typescript_spaces_within_array_initializer_brackets = false +ij_typescript_spaces_within_brackets = false +ij_typescript_spaces_within_catch_parentheses = false +ij_typescript_spaces_within_for_parentheses = false +ij_typescript_spaces_within_if_parentheses = false +ij_typescript_spaces_within_imports = true +ij_typescript_spaces_within_interpolation_expressions = false +ij_typescript_spaces_within_method_call_parentheses = false +ij_typescript_spaces_within_method_parentheses = false +ij_typescript_spaces_within_object_literal_braces = false +ij_typescript_spaces_within_object_type_braces = true +ij_typescript_spaces_within_parentheses = false +ij_typescript_spaces_within_switch_parentheses = false +ij_typescript_spaces_within_type_assertion = false +ij_typescript_spaces_within_union_types = true +ij_typescript_spaces_within_while_parentheses = false +ij_typescript_special_else_if_treatment = true +ij_typescript_ternary_operation_signs_on_next_line = false +ij_typescript_ternary_operation_wrap = off +ij_typescript_union_types_wrap = on_every_item +ij_typescript_use_chained_calls_group_indents = false +ij_typescript_use_double_quotes = false +ij_typescript_use_explicit_js_extension = global +ij_typescript_use_path_mapping = always +ij_typescript_use_public_modifier = false +ij_typescript_use_semicolon_after_statement = true +ij_typescript_var_declaration_wrap = normal +ij_typescript_while_brace_force = never +ij_typescript_while_on_new_line = false +ij_typescript_wrap_comments = false + +[{*.js,*.cjs}] +indent_size = 2 +tab_width = 2 +ij_continuation_indent_size = 4 +ij_javascript_align_imports = false +ij_javascript_align_multiline_array_initializer_expression = false +ij_javascript_align_multiline_binary_operation = false +ij_javascript_align_multiline_chained_methods = false +ij_javascript_align_multiline_extends_list = false +ij_javascript_align_multiline_for = true +ij_javascript_align_multiline_parameters = true +ij_javascript_align_multiline_parameters_in_calls = false +ij_javascript_align_multiline_ternary_operation = false +ij_javascript_align_object_properties = 0 +ij_javascript_align_union_types = false +ij_javascript_align_var_statements = 0 +ij_javascript_array_initializer_new_line_after_left_brace = false +ij_javascript_array_initializer_right_brace_on_new_line = false +ij_javascript_array_initializer_wrap = off +ij_javascript_assignment_wrap = off +ij_javascript_binary_operation_sign_on_next_line = false +ij_javascript_binary_operation_wrap = off +ij_javascript_blacklist_imports = rxjs/Rx, node_modules/**, **/node_modules/**, @angular/material, @angular/material/typings/** +ij_javascript_blank_lines_after_imports = 1 +ij_javascript_blank_lines_around_class = 1 +ij_javascript_blank_lines_around_field = 0 +ij_javascript_blank_lines_around_function = 1 +ij_javascript_blank_lines_around_method = 1 +ij_javascript_block_brace_style = end_of_line +ij_javascript_call_parameters_new_line_after_left_paren = false +ij_javascript_call_parameters_right_paren_on_new_line = false +ij_javascript_call_parameters_wrap = off +ij_javascript_catch_on_new_line = false +ij_javascript_chained_call_dot_on_new_line = true +ij_javascript_class_brace_style = end_of_line +ij_javascript_comma_on_new_line = false +ij_javascript_do_while_brace_force = never +ij_javascript_else_on_new_line = false +ij_javascript_enforce_trailing_comma = remove +ij_javascript_extends_keyword_wrap = off +ij_javascript_extends_list_wrap = off +ij_javascript_field_prefix = _ +ij_javascript_file_name_style = relaxed +ij_javascript_finally_on_new_line = false +ij_javascript_for_brace_force = never +ij_javascript_for_statement_new_line_after_left_paren = false +ij_javascript_for_statement_right_paren_on_new_line = false +ij_javascript_for_statement_wrap = off +ij_javascript_force_quote_style = true +ij_javascript_force_semicolon_style = true +ij_javascript_function_expression_brace_style = end_of_line +ij_javascript_if_brace_force = never +ij_javascript_import_merge_members = global +ij_javascript_import_prefer_absolute_path = global +ij_javascript_import_sort_members = true +ij_javascript_import_sort_module_name = false +ij_javascript_import_use_node_resolution = true +ij_javascript_imports_wrap = on_every_item +ij_javascript_indent_case_from_switch = true +ij_javascript_indent_chained_calls = true +ij_javascript_indent_package_children = 0 +ij_javascript_jsx_attribute_value = braces +ij_javascript_keep_blank_lines_in_code = 2 +ij_javascript_keep_first_column_comment = true +ij_javascript_keep_indents_on_empty_lines = false +ij_javascript_keep_line_breaks = true +ij_javascript_keep_simple_blocks_in_one_line = false +ij_javascript_keep_simple_methods_in_one_line = false +ij_javascript_line_comment_add_space = true +ij_javascript_line_comment_at_first_column = false +ij_javascript_method_brace_style = end_of_line +ij_javascript_method_call_chain_wrap = off +ij_javascript_method_parameters_new_line_after_left_paren = false +ij_javascript_method_parameters_right_paren_on_new_line = false +ij_javascript_method_parameters_wrap = off +ij_javascript_object_literal_wrap = on_every_item +ij_javascript_parentheses_expression_new_line_after_left_paren = false +ij_javascript_parentheses_expression_right_paren_on_new_line = false +ij_javascript_place_assignment_sign_on_next_line = false +ij_javascript_prefer_as_type_cast = false +ij_javascript_prefer_explicit_types_function_expression_returns = false +ij_javascript_prefer_explicit_types_function_returns = false +ij_javascript_prefer_explicit_types_vars_fields = false +ij_javascript_prefer_parameters_wrap = false +ij_javascript_reformat_c_style_comments = false +ij_javascript_space_after_colon = true +ij_javascript_space_after_comma = true +ij_javascript_space_after_dots_in_rest_parameter = false +ij_javascript_space_after_generator_mult = true +ij_javascript_space_after_property_colon = true +ij_javascript_space_after_quest = true +ij_javascript_space_after_type_colon = true +ij_javascript_space_after_unary_not = false +ij_javascript_space_before_async_arrow_lparen = true +ij_javascript_space_before_catch_keyword = true +ij_javascript_space_before_catch_left_brace = true +ij_javascript_space_before_catch_parentheses = true +ij_javascript_space_before_class_lbrace = true +ij_javascript_space_before_class_left_brace = true +ij_javascript_space_before_colon = true +ij_javascript_space_before_comma = false +ij_javascript_space_before_do_left_brace = true +ij_javascript_space_before_else_keyword = true +ij_javascript_space_before_else_left_brace = true +ij_javascript_space_before_finally_keyword = true +ij_javascript_space_before_finally_left_brace = true +ij_javascript_space_before_for_left_brace = true +ij_javascript_space_before_for_parentheses = true +ij_javascript_space_before_for_semicolon = false +ij_javascript_space_before_function_left_parenth = true +ij_javascript_space_before_generator_mult = false +ij_javascript_space_before_if_left_brace = true +ij_javascript_space_before_if_parentheses = true +ij_javascript_space_before_method_call_parentheses = false +ij_javascript_space_before_method_left_brace = true +ij_javascript_space_before_method_parentheses = false +ij_javascript_space_before_property_colon = false +ij_javascript_space_before_quest = true +ij_javascript_space_before_switch_left_brace = true +ij_javascript_space_before_switch_parentheses = true +ij_javascript_space_before_try_left_brace = true +ij_javascript_space_before_type_colon = false +ij_javascript_space_before_unary_not = false +ij_javascript_space_before_while_keyword = true +ij_javascript_space_before_while_left_brace = true +ij_javascript_space_before_while_parentheses = true +ij_javascript_spaces_around_additive_operators = true +ij_javascript_spaces_around_arrow_function_operator = true +ij_javascript_spaces_around_assignment_operators = true +ij_javascript_spaces_around_bitwise_operators = true +ij_javascript_spaces_around_equality_operators = true +ij_javascript_spaces_around_logical_operators = true +ij_javascript_spaces_around_multiplicative_operators = true +ij_javascript_spaces_around_relational_operators = true +ij_javascript_spaces_around_shift_operators = true +ij_javascript_spaces_around_unary_operator = false +ij_javascript_spaces_within_array_initializer_brackets = false +ij_javascript_spaces_within_brackets = false +ij_javascript_spaces_within_catch_parentheses = false +ij_javascript_spaces_within_for_parentheses = false +ij_javascript_spaces_within_if_parentheses = false +ij_javascript_spaces_within_imports = true +ij_javascript_spaces_within_interpolation_expressions = false +ij_javascript_spaces_within_method_call_parentheses = false +ij_javascript_spaces_within_method_parentheses = false +ij_javascript_spaces_within_object_literal_braces = false +ij_javascript_spaces_within_object_type_braces = true +ij_javascript_spaces_within_parentheses = false +ij_javascript_spaces_within_switch_parentheses = false +ij_javascript_spaces_within_type_assertion = false +ij_javascript_spaces_within_union_types = true +ij_javascript_spaces_within_while_parentheses = false +ij_javascript_special_else_if_treatment = true +ij_javascript_ternary_operation_signs_on_next_line = false +ij_javascript_ternary_operation_wrap = off +ij_javascript_union_types_wrap = on_every_item +ij_javascript_use_chained_calls_group_indents = false +ij_javascript_use_double_quotes = false +ij_javascript_use_explicit_js_extension = global +ij_javascript_use_path_mapping = always +ij_javascript_use_public_modifier = false +ij_javascript_use_semicolon_after_statement = true +ij_javascript_var_declaration_wrap = normal +ij_javascript_while_brace_force = never +ij_javascript_while_on_new_line = false +ij_javascript_wrap_comments = false + + +## +# Shell scripts +## +[{*.bash,*.sh,*.zsh}] +indent_size = 2 +tab_width = 2 + + +## +# EditorConfig +## [.editorconfig] ij_editorconfig_align_group_field_declarations = false ij_editorconfig_space_after_colon = false @@ -263,49 +913,3 @@ ij_editorconfig_space_after_comma = true ij_editorconfig_space_before_colon = false ij_editorconfig_space_before_comma = false ij_editorconfig_spaces_around_assignment_operators = true - -[{*.ant, *.fxml, *.jhm, *.jnlp, *.jrxml, *.pom, *.rng, *.tld, *.wsdl, *.xml, *.xsd, *.xsl, *.xslt, *.xul}] -ij_xml_align_attributes = true -ij_xml_align_text = false -ij_xml_attribute_wrap = normal -ij_xml_block_comment_at_first_column = true -ij_xml_keep_blank_lines = 2 -ij_xml_keep_indents_on_empty_lines = false -ij_xml_keep_line_breaks = true -ij_xml_keep_line_breaks_in_text = true -ij_xml_keep_whitespaces = false -ij_xml_keep_whitespaces_around_cdata = preserve -ij_xml_keep_whitespaces_inside_cdata = false -ij_xml_line_comment_at_first_column = true -ij_xml_space_after_tag_name = false -ij_xml_space_around_equals_in_attribute = false -ij_xml_space_inside_empty_tag = false -ij_xml_text_wrap = normal - -[{*.markdown, *.md}] -indent_size = 2 -tab_width = 2 -ij_markdown_force_one_space_after_blockquote_symbol = true -ij_markdown_force_one_space_after_header_symbol = true -ij_markdown_force_one_space_after_list_bullet = true -ij_markdown_force_one_space_between_words = true -ij_markdown_keep_indents_on_empty_lines = false -ij_markdown_max_lines_around_block_elements = 1 -ij_markdown_max_lines_around_header = 1 -ij_markdown_max_lines_between_paragraphs = 1 -ij_markdown_min_lines_around_block_elements = 1 -ij_markdown_min_lines_around_header = 1 -ij_markdown_min_lines_between_paragraphs = 1 - -[{*.yaml, *.yml, *.lang}] -indent_size = 2 -ij_yaml_align_values_properties = do_not_align -ij_yaml_autoinsert_sequence_marker = true -ij_yaml_block_mapping_on_new_line = false -ij_yaml_indent_sequence_value = true -ij_yaml_keep_indents_on_empty_lines = false -ij_yaml_keep_line_breaks = true -ij_yaml_sequence_on_new_line = false -ij_yaml_space_before_colon = false -ij_yaml_spaces_within_braces = true -ij_yaml_spaces_within_brackets = true From 39bdd862fb67ee710afe7ad581167c97e91ba7db Mon Sep 17 00:00:00 2001 From: Christian Koop Date: Sun, 26 Sep 2021 15:27:06 +0200 Subject: [PATCH 04/18] Apply new code style [DEV-2] --- .github/workflows/maven.yml | 4 +- .../core/compatibility/ClassMapping.java | 10 +- .../core/compatibility/CompatibleBiome.java | 59 +- .../core/compatibility/CompatibleHand.java | 34 +- .../compatibility/CompatibleMaterial.java | 190 +- .../CompatibleParticleHandler.java | 651 ++++--- .../core/compatibility/CompatibleSound.java | 16 +- .../core/compatibility/EntityNamespace.java | 173 +- .../compatibility/LegacyMaterialAnalouge.java | 1708 ++++++++--------- .../LegacyMaterialBlockType.java | 1 - .../compatibility/LegacyParticleEffects.java | 511 ++--- .../compatibility/LegacyPotionEffects.java | 99 +- .../core/compatibility/ServerProject.java | 15 +- .../java/com/songoda/core/SongodaCore.java | 112 +- .../java/com/songoda/core/SongodaPlugin.java | 33 +- .../com/songoda/core/chat/ChatMessage.java | 68 +- .../java/com/songoda/core/chat/ColorCode.java | 1 - .../com/songoda/core/chat/ColorContainer.java | 15 +- .../core/commands/AbstractCommand.java | 1 - .../songoda/core/commands/CommandManager.java | 90 +- .../songoda/core/commands/MainCommand.java | 7 +- .../core/commands/SelectorArguments.java | 20 +- .../core/commands/SimpleNestedCommand.java | 1 - .../songoda/core/configuration/Comment.java | 224 +-- .../songoda/core/configuration/Config.java | 68 +- .../ConfigFileConfigurationAdapter.java | 546 +++--- .../configuration/ConfigFormattingRules.java | 9 +- .../configuration/ConfigOptionsAdapter.java | 143 +- .../core/configuration/ConfigSection.java | 1458 +++++++------- .../core/configuration/ConfigSetting.java | 3 +- .../core/configuration/DataStoreObject.java | 65 +- .../core/configuration/SimpleDataStore.java | 23 +- .../configuration/editor/ConfigEditorGui.java | 65 +- .../editor/ConfigEditorListEditorGui.java | 4 +- .../configuration/editor/PluginConfigGui.java | 4 +- .../com/songoda/core/core/LocaleModule.java | 10 +- .../com/songoda/core/core/PluginInfo.java | 3 +- .../songoda/core/core/PluginInfoModule.java | 1 - .../songoda/core/core/SongodaCoreCommand.java | 3 +- .../core/core/SongodaCoreDiagCommand.java | 13 +- .../core/core/SongodaCoreOverviewGUI.java | 24 +- .../core/database/DataManagerAbstract.java | 18 +- .../songoda/core/database/DataMigration.java | 1 - .../core/database/DataMigrationManager.java | 13 +- .../core/database/DatabaseConnector.java | 1 - .../songoda/core/database/MySQLConnector.java | 2 - .../core/database/SQLiteConnector.java | 5 +- .../java/com/songoda/core/gui/AnvilGui.java | 259 +-- .../com/songoda/core/gui/CustomizableGui.java | 504 +++-- .../java/com/songoda/core/gui/DoubleGui.java | 1157 +++++------ .../main/java/com/songoda/core/gui/Gui.java | 117 +- .../java/com/songoda/core/gui/GuiHolder.java | 79 +- .../java/com/songoda/core/gui/GuiManager.java | 578 +++--- .../java/com/songoda/core/gui/GuiType.java | 1 - .../java/com/songoda/core/gui/GuiUtils.java | 149 +- .../com/songoda/core/gui/PopupMessage.java | 16 +- .../com/songoda/core/gui/SimplePagedGui.java | 463 ++--- .../core/gui/events/GuiClickEvent.java | 3 + .../core/gui/events/GuiCloseEvent.java | 1 - .../core/gui/events/GuiDropItemEvent.java | 1 + .../com/songoda/core/gui/events/GuiEvent.java | 1 - .../songoda/core/gui/events/GuiOpenEvent.java | 1 - .../songoda/core/gui/events/GuiPageEvent.java | 1 - .../songoda/core/gui/methods/Clickable.java | 1 - .../songoda/core/gui/methods/Closable.java | 1 - .../songoda/core/gui/methods/Droppable.java | 1 - .../songoda/core/gui/methods/Openable.java | 15 +- .../com/songoda/core/gui/methods/Pagable.java | 1 - .../songoda/core/hooks/EconomyManager.java | 7 +- .../core/hooks/EntityStackerManager.java | 7 +- .../songoda/core/hooks/HologramManager.java | 22 +- .../java/com/songoda/core/hooks/Hook.java | 33 +- .../com/songoda/core/hooks/HookManager.java | 11 +- .../java/com/songoda/core/hooks/JobsHook.java | 500 ++--- .../com/songoda/core/hooks/LogManager.java | 12 +- .../com/songoda/core/hooks/McMMOHook.java | 3 +- .../com/songoda/core/hooks/PluginHook.java | 14 +- .../songoda/core/hooks/ProtectionManager.java | 1 - .../songoda/core/hooks/WorldGuardHook.java | 3 +- .../songoda/core/hooks/economies/Economy.java | 1 - .../hooks/economies/PlayerPointsEconomy.java | 4 +- .../core/hooks/economies/ReserveEconomy.java | 4 +- .../core/hooks/economies/VaultEconomy.java | 6 +- .../core/hooks/holograms/CMIHolograms.java | 18 +- .../core/hooks/holograms/Holograms.java | 3 +- .../hooks/holograms/HologramsHolograms.java | 12 +- .../HolographicDisplaysHolograms.java | 12 +- .../songoda/core/hooks/jobs/JobsHandler.java | 25 +- .../core/hooks/jobs/JobsPlayerHandler.java | 378 ++-- .../core/hooks/log/CoreProtectLog.java | 11 +- .../java/com/songoda/core/hooks/log/Log.java | 1 - .../core/hooks/mcmmo/McMMOHandler.java | 195 +- .../hooks/protection/BentoBoxProtection.java | 2 +- .../protection/GriefPreventionProtection.java | 8 +- .../hooks/protection/LandsProtection.java | 3 +- .../core/hooks/protection/Protection.java | 1 - .../protection/RedProtectProtection.java | 5 +- .../hooks/protection/ResidenceProtection.java | 11 +- .../protection/UltimateClaimsProtection.java | 2 +- .../songoda/core/hooks/stackers/StackMob.java | 1 - .../songoda/core/hooks/stackers/Stacker.java | 1 - .../core/hooks/stackers/UltimateStacker.java | 1 - .../core/hooks/stackers/WildStacker.java | 3 +- .../worldguard/WorldGuardFlagHandler.java | 27 +- .../worldguard/WorldGuardRegionHandler.java | 23 +- .../com/songoda/core/input/ChatPrompt.java | 35 +- .../java/com/songoda/core/locale/Locale.java | 95 +- .../java/com/songoda/core/locale/Message.java | 30 +- .../com/songoda/core/lootables/Lootables.java | 1 - .../com/songoda/core/lootables/Modify.java | 1 - .../lootables/gui/AbstractGuiListEditor.java | 4 +- .../songoda/core/lootables/gui/GuiEditor.java | 29 +- .../core/lootables/gui/GuiEnchantEditor.java | 9 +- .../core/lootables/gui/GuiEntityEditor.java | 7 +- .../core/lootables/gui/GuiLootEditor.java | 78 +- .../core/lootables/gui/GuiLootableEditor.java | 19 +- .../core/lootables/gui/GuiLoreEditor.java | 1 - .../com/songoda/core/lootables/loot/Drop.java | 1 - .../core/lootables/loot/DropUtils.java | 40 +- .../com/songoda/core/lootables/loot/Loot.java | 47 +- .../core/lootables/loot/LootBuilder.java | 12 +- .../core/lootables/loot/LootManager.java | 96 +- .../songoda/core/lootables/loot/Lootable.java | 2 +- .../lootables/loot/objects/EnchantChance.java | 1 - .../main/java/com/songoda/core/math/Eval.java | 74 +- .../java/com/songoda/core/math/MathUtils.java | 1 - .../java/com/songoda/core/nms/NmsManager.java | 266 +-- .../com/songoda/core/utils/BlockUtils.java | 102 +- .../songoda/core/utils/BlockUtilsModern.java | 31 +- .../com/songoda/core/utils/ColorUtils.java | 2 +- .../com/songoda/core/utils/EntityUtils.java | 39 +- .../songoda/core/utils/ItemSerializer.java | 26 +- .../com/songoda/core/utils/ItemUtils.java | 262 ++- .../com/songoda/core/utils/LocationUtils.java | 1 - .../java/com/songoda/core/utils/Metrics.java | 1 - .../java/com/songoda/core/utils/NMSUtils.java | 36 +- .../com/songoda/core/utils/NumberUtils.java | 27 +- .../com/songoda/core/utils/PlayerUtils.java | 41 +- .../songoda/core/utils/ReflectionUtils.java | 107 +- .../com/songoda/core/utils/RotationUtils.java | 3 +- .../com/songoda/core/utils/TextUtils.java | 50 +- .../com/songoda/core/utils/TimeUtils.java | 44 +- .../com/songoda/core/world/SItemStack.java | 16 +- .../java/com/songoda/core/world/SSpawner.java | 15 +- .../java/com/songoda/core/world/SWorld.java | 6 +- .../com/songoda/core/world/SWorldBorder.java | 13 +- .../songoda/core/nms/anvil/CustomAnvil.java | 1 - .../nms/anvil/methods/AnvilTextChange.java | 1 - .../com/songoda/core/nms/nbt/NBTCompound.java | 1 - .../com/songoda/core/nms/nbt/NBTCore.java | 1 - .../com/songoda/core/nms/nbt/NBTEntity.java | 1 - .../com/songoda/core/nms/nbt/NBTItem.java | 1 - .../com/songoda/core/nms/nbt/NBTObject.java | 1 - .../songoda/core/nms/world/SItemStack.java | 1 - .../com/songoda/core/nms/world/SSpawner.java | 11 +- .../com/songoda/core/nms/world/SWorld.java | 1 - .../songoda/core/nms/world/SpawnedEntity.java | 1 - .../core/nms/v1_10_R1/anvil/AnvilCore.java | 1 - .../v1_10_R1/anvil/AnvilInventoryCustom.java | 2 +- .../core/nms/v1_10_R1/anvil/AnvilView.java | 14 +- .../nms/v1_10_R1/nbt/NBTCompoundImpl.java | 21 +- .../core/nms/v1_10_R1/nbt/NBTCoreImpl.java | 2 +- .../core/nms/v1_10_R1/nbt/NBTEntityImpl.java | 9 +- .../core/nms/v1_10_R1/nbt/NBTItemImpl.java | 6 +- .../core/nms/v1_10_R1/nbt/NBTObjectImpl.java | 1 - .../nms/v1_10_R1/world/SItemStackImpl.java | 3 +- .../core/nms/v1_10_R1/world/SSpawnerImpl.java | 34 +- .../core/nms/v1_10_R1/world/SWorldImpl.java | 1 - .../nms/v1_10_R1/world/WorldCoreImpl.java | 38 +- .../world/spawner/BBaseSpawnerImpl.java | 151 +- .../core/nms/v1_11_R1/anvil/AnvilCore.java | 1 - .../v1_11_R1/anvil/AnvilInventoryCustom.java | 2 +- .../core/nms/v1_11_R1/anvil/AnvilView.java | 9 +- .../nms/v1_11_R1/nbt/NBTCompoundImpl.java | 22 +- .../core/nms/v1_11_R1/nbt/NBTCoreImpl.java | 2 +- .../core/nms/v1_11_R1/nbt/NBTEntityImpl.java | 8 +- .../core/nms/v1_11_R1/nbt/NBTItemImpl.java | 6 +- .../core/nms/v1_11_R1/nbt/NBTObjectImpl.java | 1 - .../nms/v1_11_R1/world/SItemStackImpl.java | 4 +- .../core/nms/v1_11_R1/world/SSpawnerImpl.java | 34 +- .../core/nms/v1_11_R1/world/SWorldImpl.java | 1 - .../nms/v1_11_R1/world/WorldCoreImpl.java | 38 +- .../world/spawner/BBaseSpawnerImpl.java | 144 +- .../core/nms/v1_12_R1/anvil/AnvilCore.java | 1 - .../v1_12_R1/anvil/AnvilInventoryCustom.java | 2 +- .../core/nms/v1_12_R1/anvil/AnvilView.java | 13 +- .../nms/v1_12_R1/nbt/NBTCompoundImpl.java | 21 +- .../core/nms/v1_12_R1/nbt/NBTCoreImpl.java | 2 +- .../core/nms/v1_12_R1/nbt/NBTEntityImpl.java | 9 +- .../core/nms/v1_12_R1/nbt/NBTItemImpl.java | 6 +- .../core/nms/v1_12_R1/nbt/NBTObjectImpl.java | 1 - .../nms/v1_12_R1/world/SItemStackImpl.java | 3 +- .../core/nms/v1_12_R1/world/SSpawnerImpl.java | 34 +- .../core/nms/v1_12_R1/world/SWorldImpl.java | 1 - .../nms/v1_12_R1/world/WorldCoreImpl.java | 38 +- .../world/spawner/BBaseSpawnerImpl.java | 148 +- .../core/nms/v1_13_R1/anvil/AnvilCore.java | 1 - .../v1_13_R1/anvil/AnvilInventoryCustom.java | 1 - .../core/nms/v1_13_R1/anvil/AnvilView.java | 14 +- .../nms/v1_13_R1/nbt/NBTCompoundImpl.java | 21 +- .../core/nms/v1_13_R1/nbt/NBTCoreImpl.java | 2 +- .../core/nms/v1_13_R1/nbt/NBTEntityImpl.java | 8 +- .../core/nms/v1_13_R1/nbt/NBTItemImpl.java | 6 +- .../core/nms/v1_13_R1/nbt/NBTObjectImpl.java | 1 - .../nms/v1_13_R1/world/SItemStackImpl.java | 5 +- .../core/nms/v1_13_R1/world/SSpawnerImpl.java | 35 +- .../core/nms/v1_13_R1/world/SWorldImpl.java | 1 - .../nms/v1_13_R1/world/WorldCoreImpl.java | 44 +- .../world/spawner/BBaseSpawnerImpl.java | 147 +- .../core/nms/v1_13_R2/anvil/AnvilCore.java | 1 - .../v1_13_R2/anvil/AnvilInventoryCustom.java | 1 - .../core/nms/v1_13_R2/anvil/AnvilView.java | 9 +- .../nms/v1_13_R2/nbt/NBTCompoundImpl.java | 18 +- .../core/nms/v1_13_R2/nbt/NBTCoreImpl.java | 2 +- .../core/nms/v1_13_R2/nbt/NBTEntityImpl.java | 6 +- .../core/nms/v1_13_R2/nbt/NBTItemImpl.java | 5 +- .../core/nms/v1_13_R2/nbt/NBTObjectImpl.java | 1 - .../nms/v1_13_R2/world/SItemStackImpl.java | 1 - .../core/nms/v1_13_R2/world/SSpawnerImpl.java | 35 +- .../core/nms/v1_13_R2/world/SWorldImpl.java | 1 - .../nms/v1_13_R2/world/WorldCoreImpl.java | 56 +- .../world/spawner/BBaseSpawnerImpl.java | 159 +- .../core/nms/v1_14_R1/anvil/AnvilCore.java | 1 - .../v1_14_R1/anvil/AnvilInventoryCustom.java | 2 +- .../core/nms/v1_14_R1/anvil/AnvilView.java | 18 +- .../nms/v1_14_R1/nbt/NBTCompoundImpl.java | 21 +- .../core/nms/v1_14_R1/nbt/NBTCoreImpl.java | 2 +- .../core/nms/v1_14_R1/nbt/NBTEntityImpl.java | 4 +- .../core/nms/v1_14_R1/nbt/NBTItemImpl.java | 6 +- .../core/nms/v1_14_R1/nbt/NBTObjectImpl.java | 1 - .../nms/v1_14_R1/world/SItemStackImpl.java | 5 +- .../core/nms/v1_14_R1/world/SSpawnerImpl.java | 38 +- .../core/nms/v1_14_R1/world/SWorldImpl.java | 1 - .../nms/v1_14_R1/world/WorldCoreImpl.java | 50 +- .../world/spawner/BBaseSpawnerImpl.java | 163 +- .../core/nms/v1_15_R1/anvil/AnvilCore.java | 3 +- .../v1_15_R1/anvil/AnvilInventoryCustom.java | 2 +- .../core/nms/v1_15_R1/anvil/AnvilView.java | 15 +- .../nms/v1_15_R1/nbt/NBTCompoundImpl.java | 21 +- .../core/nms/v1_15_R1/nbt/NBTCoreImpl.java | 2 +- .../core/nms/v1_15_R1/nbt/NBTEntityImpl.java | 6 +- .../core/nms/v1_15_R1/nbt/NBTItemImpl.java | 6 +- .../core/nms/v1_15_R1/nbt/NBTObjectImpl.java | 1 - .../nms/v1_15_R1/world/SItemStackImpl.java | 5 +- .../core/nms/v1_15_R1/world/SSpawnerImpl.java | 42 +- .../core/nms/v1_15_R1/world/SWorldImpl.java | 1 - .../nms/v1_15_R1/world/WorldCoreImpl.java | 56 +- .../world/spawner/BBaseSpawnerImpl.java | 171 +- .../core/nms/v1_16_R1/anvil/AnvilCore.java | 3 +- .../v1_16_R1/anvil/AnvilInventoryCustom.java | 2 +- .../core/nms/v1_16_R1/anvil/AnvilView.java | 15 +- .../nms/v1_16_R1/nbt/NBTCompoundImpl.java | 21 +- .../core/nms/v1_16_R1/nbt/NBTCoreImpl.java | 1 - .../core/nms/v1_16_R1/nbt/NBTEntityImpl.java | 4 +- .../core/nms/v1_16_R1/nbt/NBTItemImpl.java | 6 +- .../core/nms/v1_16_R1/nbt/NBTObjectImpl.java | 1 - .../nms/v1_16_R1/world/SItemStackImpl.java | 5 +- .../core/nms/v1_16_R1/world/SSpawnerImpl.java | 42 +- .../core/nms/v1_16_R1/world/SWorldImpl.java | 1 - .../nms/v1_16_R1/world/WorldCoreImpl.java | 56 +- .../world/spawner/BBaseSpawnerImpl.java | 161 +- .../core/nms/v1_16_R2/anvil/AnvilCore.java | 1 - .../v1_16_R2/anvil/AnvilInventoryCustom.java | 2 +- .../core/nms/v1_16_R2/anvil/AnvilView.java | 15 +- .../nms/v1_16_R2/nbt/NBTCompoundImpl.java | 21 +- .../core/nms/v1_16_R2/nbt/NBTCoreImpl.java | 2 +- .../core/nms/v1_16_R2/nbt/NBTEntityImpl.java | 4 +- .../core/nms/v1_16_R2/nbt/NBTItemImpl.java | 6 +- .../core/nms/v1_16_R2/nbt/NBTObjectImpl.java | 1 - .../nms/v1_16_R2/world/SItemStackImpl.java | 5 +- .../core/nms/v1_16_R2/world/SSpawnerImpl.java | 42 +- .../core/nms/v1_16_R2/world/SWorldImpl.java | 1 - .../nms/v1_16_R2/world/WorldCoreImpl.java | 56 +- .../world/spawner/BBaseSpawnerImpl.java | 175 +- .../core/nms/v1_16_R3/anvil/AnvilCore.java | 1 - .../v1_16_R3/anvil/AnvilInventoryCustom.java | 2 +- .../core/nms/v1_16_R3/anvil/AnvilView.java | 20 +- .../nms/v1_16_R3/nbt/NBTCompoundImpl.java | 21 +- .../core/nms/v1_16_R3/nbt/NBTCoreImpl.java | 2 +- .../core/nms/v1_16_R3/nbt/NBTEntityImpl.java | 5 +- .../core/nms/v1_16_R3/nbt/NBTItemImpl.java | 6 +- .../core/nms/v1_16_R3/nbt/NBTObjectImpl.java | 1 - .../nms/v1_16_R3/world/SItemStackImpl.java | 5 +- .../core/nms/v1_16_R3/world/SSpawnerImpl.java | 41 +- .../core/nms/v1_16_R3/world/SWorldImpl.java | 1 - .../nms/v1_16_R3/world/WorldCoreImpl.java | 58 +- .../world/spawner/BBaseSpawnerImpl.java | 175 +- .../core/nms/v1_17_R1/anvil/AnvilCore.java | 1 - .../v1_17_R1/anvil/AnvilInventoryCustom.java | 2 +- .../core/nms/v1_17_R1/anvil/AnvilView.java | 14 +- .../nms/v1_17_R1/nbt/NBTCompoundImpl.java | 21 +- .../core/nms/v1_17_R1/nbt/NBTCoreImpl.java | 2 +- .../core/nms/v1_17_R1/nbt/NBTEntityImpl.java | 4 +- .../core/nms/v1_17_R1/nbt/NBTItemImpl.java | 6 +- .../core/nms/v1_17_R1/nbt/NBTObjectImpl.java | 1 - .../nms/v1_17_R1/world/SItemStackImpl.java | 5 +- .../core/nms/v1_17_R1/world/SSpawnerImpl.java | 42 +- .../core/nms/v1_17_R1/world/SWorldImpl.java | 11 +- .../nms/v1_17_R1/world/WorldCoreImpl.java | 53 +- .../world/spawner/BBaseSpawnerImpl.java | 145 +- .../core/nms/v1_8_R1/anvil/AnvilCore.java | 1 - .../v1_8_R1/anvil/AnvilInventoryCustom.java | 2 +- .../core/nms/v1_8_R1/anvil/AnvilView.java | 14 +- .../core/nms/v1_8_R1/nbt/NBTCompoundImpl.java | 22 +- .../core/nms/v1_8_R1/nbt/NBTCoreImpl.java | 2 +- .../core/nms/v1_8_R1/nbt/NBTEntityImpl.java | 16 +- .../core/nms/v1_8_R1/nbt/NBTItemImpl.java | 6 +- .../core/nms/v1_8_R1/nbt/NBTObjectImpl.java | 1 - .../nms/v1_8_R1/world/SItemStackImpl.java | 4 +- .../core/nms/v1_8_R1/world/SSpawnerImpl.java | 34 +- .../core/nms/v1_8_R1/world/SWorldImpl.java | 1 - .../core/nms/v1_8_R1/world/WorldCoreImpl.java | 39 +- .../world/spawner/BBaseSpawnerImpl.java | 115 +- .../core/nms/v1_8_R2/anvil/AnvilCore.java | 1 - .../v1_8_R2/anvil/AnvilInventoryCustom.java | 2 +- .../core/nms/v1_8_R2/anvil/AnvilView.java | 14 +- .../core/nms/v1_8_R2/nbt/NBTCompoundImpl.java | 22 +- .../core/nms/v1_8_R2/nbt/NBTCoreImpl.java | 2 +- .../core/nms/v1_8_R2/nbt/NBTEntityImpl.java | 16 +- .../core/nms/v1_8_R2/nbt/NBTItemImpl.java | 6 +- .../core/nms/v1_8_R2/nbt/NBTObjectImpl.java | 1 - .../nms/v1_8_R2/world/SItemStackImpl.java | 4 +- .../core/nms/v1_8_R2/world/SSpawnerImpl.java | 34 +- .../core/nms/v1_8_R2/world/SWorldImpl.java | 1 - .../core/nms/v1_8_R2/world/WorldCoreImpl.java | 40 +- .../world/spawner/BBaseSpawnerImpl.java | 112 +- .../core/nms/v1_8_R3/anvil/AnvilCore.java | 1 - .../v1_8_R3/anvil/AnvilInventoryCustom.java | 2 +- .../core/nms/v1_8_R3/anvil/AnvilView.java | 14 +- .../core/nms/v1_8_R3/nbt/NBTCompoundImpl.java | 13 +- .../core/nms/v1_8_R3/nbt/NBTCoreImpl.java | 2 +- .../core/nms/v1_8_R3/nbt/NBTEntityImpl.java | 16 +- .../core/nms/v1_8_R3/nbt/NBTItemImpl.java | 1 - .../core/nms/v1_8_R3/nbt/NBTObjectImpl.java | 1 - .../nms/v1_8_R3/world/SItemStackImpl.java | 4 +- .../core/nms/v1_8_R3/world/SSpawnerImpl.java | 31 +- .../core/nms/v1_8_R3/world/SWorldImpl.java | 1 - .../core/nms/v1_8_R3/world/WorldCoreImpl.java | 38 +- .../world/spawner/BBaseSpawnerImpl.java | 116 +- .../core/nms/v1_9_R1/anvil/AnvilCore.java | 1 - .../v1_9_R1/anvil/AnvilInventoryCustom.java | 2 +- .../core/nms/v1_9_R1/anvil/AnvilView.java | 12 +- .../core/nms/v1_9_R1/nbt/NBTCompoundImpl.java | 18 +- .../core/nms/v1_9_R1/nbt/NBTCoreImpl.java | 2 +- .../core/nms/v1_9_R1/nbt/NBTEntityImpl.java | 8 +- .../core/nms/v1_9_R1/nbt/NBTItemImpl.java | 6 +- .../core/nms/v1_9_R1/nbt/NBTObjectImpl.java | 1 - .../nms/v1_9_R1/world/SItemStackImpl.java | 4 +- .../core/nms/v1_9_R1/world/SSpawnerImpl.java | 33 +- .../core/nms/v1_9_R1/world/SWorldImpl.java | 1 - .../core/nms/v1_9_R1/world/WorldCoreImpl.java | 38 +- .../world/spawner/BBaseSpawnerImpl.java | 143 +- .../core/nms/v1_9_R2/anvil/AnvilCore.java | 1 - .../v1_9_R2/anvil/AnvilInventoryCustom.java | 1 - .../core/nms/v1_9_R2/anvil/AnvilView.java | 15 +- .../core/nms/v1_9_R2/nbt/NBTCompoundImpl.java | 21 +- .../core/nms/v1_9_R2/nbt/NBTCoreImpl.java | 2 +- .../core/nms/v1_9_R2/nbt/NBTEntityImpl.java | 8 +- .../core/nms/v1_9_R2/nbt/NBTItemImpl.java | 6 +- .../core/nms/v1_9_R2/nbt/NBTObjectImpl.java | 1 - .../nms/v1_9_R2/world/SItemStackImpl.java | 4 +- .../core/nms/v1_9_R2/world/SSpawnerImpl.java | 34 +- .../core/nms/v1_9_R2/world/SWorldImpl.java | 1 - .../core/nms/v1_9_R2/world/WorldCoreImpl.java | 38 +- .../world/spawner/BBaseSpawnerImpl.java | 141 +- 365 files changed, 9780 insertions(+), 7804 deletions(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index e7f324bb..cd85dca8 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -50,13 +50,13 @@ jobs: if: ${{ success() && (github.ref == 'refs/heads/master' || github.ref == 'refs/heads/development') }} continue-on-error: true run: | - curl -X POST --data "{\"content\":null,\"embeds\":[{\"title\":\"Build succeeded!\",\"description\":\"The build with the ID #$GITHUB_RUN_NUMBER has succeeded!\",\"url\":\"$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID\",\"color\":5490477,\"fields\":[{\"name\":\"Branch\",\"value\":\"$GITHUB_REF\",\"inline\":true}],\"author\":{\"name\":\"$GITHUB_REPOSITORY\",\"url\":\"$GITHUB_SERVER_URL/$GITHUB_REPOSITORY\",\"icon_url\":\"$GITHUB_SERVER_URL/songoda.png\"},\"footer\":{\"text\":\"Initiated by $GITHUB_ACTOR\",\"icon_url\":\"$GITHUB_SERVER_URL/$GITHUB_ACTOR.png\"}}],\"username\":\"OctoAgent\",\"avatar_url\":\"https://github.githubassets.com/images/modules/logos_page/Octocat.png\"}" --header 'Content-Type: application/json' $DISCORD_WEBHOOK + curl -X POST --data "{\"content\":null,\"embeds\":[{\"title\":\"Build succeeded!\",\"description\":\"The build with the ID #$GITHUB_RUN_NUMBER has succeeded!\",\"url\":\"$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID\",\"color\":5490477,\"fields\":[{\"name\":\"Branch\",\"value\":\"$GITHUB_REF\",\"inline\":true}],\"author\":{\"name\":\"$GITHUB_REPOSITORY\",\"url\":\"$GITHUB_SERVER_URL/$GITHUB_REPOSITORY\",\"icon_url\":\"$GITHUB_SERVER_URL/songoda.png\"},\"footer\":{\"text\":\"Initiated by $GITHUB_ACTOR\",\"icon_url\":\"$GITHUB_SERVER_URL/$GITHUB_ACTOR.png\"}}],\"username\":\"OctoAgent\",\"avatar_url\":\"https://github.githubassets.com/images/modules/logos_page/Octocat.png\"}" --header 'Content-Type: application/json' $DISCORD_WEBHOOK env: DISCORD_WEBHOOK: ${{ secrets.DISCORD_BUILD_STATUS_WEBHOOK }} - name: 'Discord Webhook (Failure)' if: ${{ failure() && (github.ref == 'refs/heads/master' || github.ref == 'refs/heads/development') }} continue-on-error: true run: | - curl -X POST --data "{\"content\":null,\"embeds\":[{\"title\":\"Build failed!\",\"description\":\"The build with the ID #$GITHUB_RUN_NUMBER has failed!\",\"url\":\"$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID\",\"color\":15611419,\"fields\":[{\"name\":\"Branch\",\"value\":\"$GITHUB_REF\",\"inline\":true}],\"author\":{\"name\":\"$GITHUB_REPOSITORY\",\"url\":\"$GITHUB_SERVER_URL/$GITHUB_REPOSITORY\",\"icon_url\":\"$GITHUB_SERVER_URL/songoda.png\"},\"footer\":{\"text\":\"Initiated by $GITHUB_ACTOR\",\"icon_url\":\"$GITHUB_SERVER_URL/$GITHUB_ACTOR.png\"}}],\"username\":\"OctoAgent\",\"avatar_url\":\"https://github.githubassets.com/images/modules/logos_page/Octocat.png\"}" --header "Content-Type:application/json" $DISCORD_WEBHOOK + curl -X POST --data "{\"content\":null,\"embeds\":[{\"title\":\"Build failed!\",\"description\":\"The build with the ID #$GITHUB_RUN_NUMBER has failed!\",\"url\":\"$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID\",\"color\":15611419,\"fields\":[{\"name\":\"Branch\",\"value\":\"$GITHUB_REF\",\"inline\":true}],\"author\":{\"name\":\"$GITHUB_REPOSITORY\",\"url\":\"$GITHUB_SERVER_URL/$GITHUB_REPOSITORY\",\"icon_url\":\"$GITHUB_SERVER_URL/songoda.png\"},\"footer\":{\"text\":\"Initiated by $GITHUB_ACTOR\",\"icon_url\":\"$GITHUB_SERVER_URL/$GITHUB_ACTOR.png\"}}],\"username\":\"OctoAgent\",\"avatar_url\":\"https://github.githubassets.com/images/modules/logos_page/Octocat.png\"}" --header "Content-Type:application/json" $DISCORD_WEBHOOK env: DISCORD_WEBHOOK: ${{ secrets.DISCORD_BUILD_STATUS_WEBHOOK }} diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/ClassMapping.java b/Compatibility/src/main/java/com/songoda/core/compatibility/ClassMapping.java index 2322167b..44451307 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/ClassMapping.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/ClassMapping.java @@ -1,7 +1,6 @@ package com.songoda.core.compatibility; public enum ClassMapping { - BIOME_BASE("world.level.biome", "BiomeBase"), BIOME_STORAGE("world.level.chunk", "BiomeStorage"), BLOCK("world.level.block", "Block"), @@ -65,15 +64,18 @@ public enum ClassMapping { public Class getClazz(String sub) { try { String name = sub == null ? className : className + "$" + sub; - if (className.startsWith("Craft")) + if (className.startsWith("Craft")) { return Class.forName("org.bukkit.craftbukkit." + ServerVersion.getServerVersionString() + (packageName == null ? "" : "." + packageName) + "." + name); + } + return Class.forName("net.minecraft." + ( ServerVersion.isServerVersionAtLeast(ServerVersion.V1_17) && packageName != null ? packageName : "server." + ServerVersion.getServerVersionString()) + "." + name); - } catch (ClassNotFoundException e) { - e.printStackTrace(); + } catch (ClassNotFoundException ex) { + ex.printStackTrace(); } + return null; } } diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleBiome.java b/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleBiome.java index c1cce071..83c6a2ac 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleBiome.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleBiome.java @@ -24,7 +24,6 @@ import java.util.Set; * @since 2020-03-27 */ public enum CompatibleBiome { - /* 1.17 */ DRIPSTONE_CAVES(ServerVersion.V1_17), LUSH_CAVES(ServerVersion.V1_17), @@ -121,13 +120,17 @@ public enum CompatibleBiome { private static Field fieldStorageRegistry; static { - for (CompatibleBiome biome : values()) - for (Version version : biome.getVersions()) + for (CompatibleBiome biome : values()) { + for (Version version : biome.getVersions()) { lookupMap.put(version.biome, biome); + } + } - for (CompatibleBiome biome : CompatibleBiome.values()) - if (biome.isCompatible()) + for (CompatibleBiome biome : CompatibleBiome.values()) { + if (biome.isCompatible()) { compatibleBiomes.add(biome); + } + } if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_15)) { try { @@ -148,13 +151,14 @@ public enum CompatibleBiome { try { // If 1.16.5 fieldStorageRegistry = classBiomeStorage.getDeclaredField("registry"); - } catch (NoSuchFieldException e) { + } catch (NoSuchFieldException ex) { // If less than 1.16.5 fieldStorageRegistry = classBiomeStorage.getDeclaredField("g"); } + fieldStorageRegistry.setAccessible(true); - } catch (NoSuchMethodException | NoSuchFieldException e) { - e.printStackTrace(); + } catch (NoSuchMethodException | NoSuchFieldException ex) { + ex.printStackTrace(); } } } @@ -171,6 +175,7 @@ public enum CompatibleBiome { public boolean isCompatible() { Version version = versions.getLast(); ServerVersion.isServerVersionAtLeast(version.version); + return true; } @@ -179,9 +184,12 @@ public enum CompatibleBiome { } public Biome getBiome() { - for (Version version : versions) - if (ServerVersion.isServerVersionAtLeast(version.version)) + for (Version version : versions) { + if (ServerVersion.isServerVersionAtLeast(version.version)) { return Biome.valueOf(version.biome); + } + } + return null; } @@ -201,14 +209,17 @@ public enum CompatibleBiome { Object nmsChunk = null; Object biomeStorage = null; Object biomeBase = null; + if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_15)) { nmsChunk = methodGetHandle.invoke(chunk); biomeStorage = methodGetBiomeIndex.invoke(nmsChunk); + if (isAbove1_16_R1) { Object registry = fieldStorageRegistry.get(biomeStorage); biomeBase = methodBiomeToBiomeBase.invoke(null, registry, getBiome()); - } else + } else { biomeBase = methodBiomeToBiomeBase.invoke(null, getBiome()); + } } World world = chunk.getWorld(); @@ -216,22 +227,31 @@ public enum CompatibleBiome { int chunkZ = chunk.getZ(); for (int x = chunkX << 4; x < (chunkX << 4) + 16; x++) { for (int z = chunkZ << 4; z < (chunkZ << 4) + 16; z++) { - if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_15)) - for (int y = 0; y < world.getMaxHeight(); ++y) + if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_15)) { + for (int y = 0; y < world.getMaxHeight(); ++y) { methodSetBiome.invoke(biomeStorage, x >> 2, y >> 2, z >> 2, biomeBase); - else - chunk.getWorld().setBiome(x, z, getBiome()); + } + + continue; + } + + chunk.getWorld().setBiome(x, z, getBiome()); } } - if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_15)) + + if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_15)) { methodMarkDirty.invoke(nmsChunk); + } } public void setBiome(World world, int x, int y, int z) { - if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_15)) + if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_15)) { world.setBiome(x, y, z, getBiome()); - else - world.setBiome(x, z, getBiome()); + + return; + } + + world.setBiome(x, z, getBiome()); } private static Version v(ServerVersion version, String biome) { @@ -243,7 +263,6 @@ public enum CompatibleBiome { } private static class Version { - final ServerVersion version; final String biome; diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleHand.java b/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleHand.java index 882cf601..2ca62063 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleHand.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleHand.java @@ -16,7 +16,6 @@ import java.util.Map; * @since 2020-03-24 */ public enum CompatibleHand { - MAIN_HAND, OFF_HAND; private static Map methodCache = new HashMap<>(); @@ -25,6 +24,7 @@ public enum CompatibleHand { try { Class clazz = event.getClass(); String className = clazz.getName(); + Method method; if (methodCache.containsKey(className)) { method = methodCache.get(className); @@ -32,10 +32,15 @@ public enum CompatibleHand { method = clazz.getDeclaredMethod("getHand"); methodCache.put(className, method); } + EquipmentSlot slot = (EquipmentSlot) method.invoke(event); - if (slot == EquipmentSlot.OFF_HAND) return OFF_HAND; - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { + + if (slot == EquipmentSlot.OFF_HAND) { + return OFF_HAND; + } + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ignore) { } + return MAIN_HAND; } @@ -65,10 +70,12 @@ public enum CompatibleHand { int result = item.getAmount() - amount; item.setAmount(result); - if (this == CompatibleHand.MAIN_HAND) + if (this == CompatibleHand.MAIN_HAND) { player.setItemInHand(result > 0 ? item : null); - else - player.getInventory().setItemInOffHand(result > 0 ? item : null); + return; + } + + player.getInventory().setItemInOffHand(result > 0 ? item : null); } /** @@ -79,10 +86,11 @@ public enum CompatibleHand { * @return the item */ public ItemStack getItem(Player player) { - if (this == MAIN_HAND) + if (this == MAIN_HAND) { return player.getItemInHand(); - else - return player.getInventory().getItemInOffHand(); + } + + return player.getInventory().getItemInOffHand(); } /** @@ -92,9 +100,11 @@ public enum CompatibleHand { * @param item the item to set */ public void setItem(Player player, ItemStack item) { - if (this == MAIN_HAND) + if (this == MAIN_HAND) { player.setItemInHand(item); - else - player.getInventory().setItemInOffHand(item); + return; + } + + player.getInventory().setItemInOffHand(item); } } diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleMaterial.java b/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleMaterial.java index 1a4fde3c..261ac45a 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleMaterial.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleMaterial.java @@ -21,7 +21,7 @@ import java.util.Set; * @since 2019-08-23 */ public enum CompatibleMaterial { - /* + /* TODO: add another handler for getBlockItem() for materials and fallback materials Legacy has some values not used in modern, eg: @@ -33,7 +33,7 @@ public enum CompatibleMaterial { JUNGLE_DOOR_ITEM(429), ACACIA_DOOR_ITEM(430), DARK_OAK_DOOR_ITEM(431), - */ + */ /* 1.17 */ AMETHYST_BLOCK(), @@ -1304,22 +1304,27 @@ public enum CompatibleMaterial { lookupMap.put(m.legacy, m); continue; } + lookupMap.put(m.name(), m); if (!m.usesCompatibility()) { lookupMap.put(m.material + ":" + (m.data == null ? "" : m.data), m); } } + for (CompatibleMaterial m : values()) { if (!m.usesCompatibility()) { if (m.legacy != null && !lookupMap.containsKey(m.legacy)) { lookupMap.put(m.legacy, m); } + if (m.modern2 != null && !lookupMap.containsKey(m.modern2)) { lookupMap.put(m.modern2, m); } + if (m.legacyBlockMaterial != null && !lookupMap.containsKey(m.legacyBlockMaterial.blockMaterialName)) { lookupMap.put(m.legacyBlockMaterial.blockMaterialName, m); } + if (m.legacyBlockMaterial != null && !lookupMap.containsKey(m.legacyBlockMaterial.alternateBlockMaterialName)) { lookupMap.put(m.legacyBlockMaterial.alternateBlockMaterialName, m); } @@ -1422,8 +1427,6 @@ public enum CompatibleMaterial { /** * Does this material need to use a legacy fallback? - * - * @return */ public boolean usesLegacy() { return legacy != null && ServerVersion.isServerVersionBelow(minVersion); @@ -1431,8 +1434,6 @@ public enum CompatibleMaterial { /** * Does this material need to use a fallback item on this server? - * - * @return */ public boolean usesCompatibility() { return compatibleMaterial != null && material == compatibleMaterial.material; @@ -1441,18 +1442,13 @@ public enum CompatibleMaterial { /** * Is this item reused in later versions of Minecraft? - * - * @return */ public boolean isRecycled() { return usesLegacy() && this == CompatibleMaterial.GRASS; } /** - * Get the legacy data value for this material if there is one, or -1 if - * none - * - * @return + * Get the legacy data value for this material if there is one, or -1 if none */ public byte getData() { return data != null ? data : -1; @@ -1523,6 +1519,7 @@ public enum CompatibleMaterial { if (item == null) { return null; } + String key = item.getType() + ":"; CompatibleMaterial m = lookupMap.get(key); return m != null ? m : lookupMap.get(key + item.getDurability()); @@ -1561,8 +1558,8 @@ public enum CompatibleMaterial { if (ServerVersion.isServerVersionAtOrBelow(ServerVersion.V1_12)) { try { methodGetBlockData = FallingBlock.class.getDeclaredMethod("getBlockData"); - } catch (NoSuchMethodException e) { - e.printStackTrace(); + } catch (NoSuchMethodException ex) { + ex.printStackTrace(); } } } @@ -1575,16 +1572,20 @@ public enum CompatibleMaterial { * @return LegacyMaterial or null if none found */ public static CompatibleMaterial getMaterial(FallingBlock block) { - if (block == null) return null; + if (block == null) { + return null; + } + if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_13)) { return getMaterial(block.getBlockData().getMaterial()); - } else { - try { - return getMaterial(block.getMaterial(), (byte) methodGetBlockData.invoke(block)); - } catch (IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); - } } + + try { + return getMaterial(block.getMaterial(), (byte) methodGetBlockData.invoke(block)); + } catch (IllegalAccessException | InvocationTargetException ex) { + ex.printStackTrace(); + } + return null; } @@ -1599,21 +1600,21 @@ public enum CompatibleMaterial { public static CompatibleMaterial getMaterial(Material mat, byte data) { if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_13)) { // Flattening return CompatibleMaterial.getMaterial(mat); - } else { // Pre-Flattening - if (mat != null) { - if (data != 0) { - for (CompatibleMaterial cm : CompatibleMaterial.values()) { - if (cm.getMaterial() != null - && cm.getMaterial().equals(mat)) { - if (cm.getData() == data) { - return cm; - } - } + } + + // Pre-Flattening + if (mat != null) { + if (data != 0) { + for (CompatibleMaterial cm : CompatibleMaterial.values()) { + if (cm.getMaterial() != null && cm.getMaterial().equals(mat) && cm.getData() == data) { + return cm; } } - return CompatibleMaterial.getMaterial(mat); } + + return CompatibleMaterial.getMaterial(mat); } + return null; } @@ -1621,15 +1622,19 @@ public enum CompatibleMaterial { if (block == null) { return null; } + Material mat = block.getType(); + if (useLegacy) { LegacyMaterialBlockType legacyBlock = LegacyMaterialBlockType.getFromLegacy(mat.name(), block.getData()); if (legacyBlock != null) { return lookupMap.get(legacyBlock.name()); } + CompatibleMaterial withData = lookupMap.get(mat.name() + ":" + block.getData()); return withData == null ? lookupMap.get(mat.name()) : withData; } + return lookupMap.get(mat.name()); } @@ -1645,12 +1650,16 @@ public enum CompatibleMaterial { public static CompatibleMaterial getBlockMaterial(String name) { if (name == null) { return null; - } else if (useLegacy) { + } + + if (useLegacy) { LegacyMaterialBlockType legacyBlock = LegacyMaterialBlockType.getFromLegacy(name.toUpperCase()); + if (legacyBlock != null) { return lookupMap.get(legacyBlock.name()); } } + return lookupMap.get(name.toUpperCase()); } @@ -1667,12 +1676,16 @@ public enum CompatibleMaterial { public static CompatibleMaterial getBlockMaterial(String name, CompatibleMaterial def) { if (name == null) { return def; - } else if (useLegacy) { + } + + if (useLegacy) { LegacyMaterialBlockType legacyBlock = LegacyMaterialBlockType.getFromLegacy(name.toUpperCase()); + if (legacyBlock != null) { return lookupMap.get(legacyBlock.name()); } } + return lookupMap.getOrDefault(name.toUpperCase(), def); } @@ -1686,12 +1699,16 @@ public enum CompatibleMaterial { public static CompatibleMaterial getBlockMaterial(Material mat) { if (mat == null) { return null; - } else if (useLegacy) { + } + + if (useLegacy) { LegacyMaterialBlockType legacyBlock = LegacyMaterialBlockType.getFromLegacy(mat.name()); + if (legacyBlock != null) { return lookupMap.get(legacyBlock.name()); } } + return lookupMap.get(mat.name()); } @@ -1699,13 +1716,15 @@ public enum CompatibleMaterial { public static Set getAllValidItemMaterials() { if (all == null) { - all = new LinkedHashSet(); + all = new LinkedHashSet<>(); + for (CompatibleMaterial mat : values()) { if (mat.isValidItem() && !mat.usesCompatibility()) { all.add(mat); } } } + return Collections.unmodifiableSet(all); } @@ -1723,10 +1742,12 @@ public enum CompatibleMaterial { if (name == null) { return null; } + CompatibleMaterial m = lookupMap.get(name.toUpperCase()); if (m != null) { return m.getItem(); } + Material mat = Material.getMaterial(name); return mat != null ? new ItemStack(mat) : null; } @@ -1737,8 +1758,8 @@ public enum CompatibleMaterial { if (ServerVersion.isServerVersionAtOrBelow(ServerVersion.V1_12)) { try { methodSetData = Block.class.getDeclaredMethod("setData", byte.class); - } catch (NoSuchMethodException e) { - e.printStackTrace(); + } catch (NoSuchMethodException ex) { + ex.printStackTrace(); } } } @@ -1750,12 +1771,14 @@ public enum CompatibleMaterial { */ public void applyToBlock(Block block) { if (block == null) return; + block.setType(material); + if (data != null && data != -1 && ServerVersion.isServerVersionAtOrBelow(ServerVersion.V1_12)) { try { methodSetData.invoke(block, data); - } catch (IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); + } catch (IllegalAccessException | InvocationTargetException ex) { + ex.printStackTrace(); } } } @@ -1768,14 +1791,15 @@ public enum CompatibleMaterial { * @return true if material of the ItemStack matches this item, corrected for legacy data */ public boolean matches(ItemStack item) { - return item != null && !usesCompatibility() && item.getType() == material && (data == null || item.getDurability() == data); // eons ago, ItemStack.getData() would return a byte. 1.7 doesn't, though. + return item != null && + !usesCompatibility() && item.getType() == material && + // eons ago, ItemStack.getData() would return a byte. 1.7 doesn't, though. + (data == null || item.getDurability() == data); } /** * Some blocks change to other materials when placed down. This checks to * see if this one is one of those. - * - * @return */ public boolean hasDifferentBlockItem() { switch (this) { @@ -1832,14 +1856,13 @@ public enum CompatibleMaterial { case CAKE: case COMPARATOR: return usesLegacy(); + default: + return false; } - return false; } /** * Check to see if this is a material that can exist as a block - * - * @return */ public boolean isBlock() { return material != null && material.isBlock(); @@ -1847,8 +1870,6 @@ public enum CompatibleMaterial { /** * Check to see if this is an item that can be consumed to restore hunger - * - * @return */ public boolean isEdible() { return material != null && material.isEdible(); @@ -1856,8 +1877,6 @@ public enum CompatibleMaterial { /** * Check if the material is a block and can be built on - * - * @return */ public boolean isSolid() { return material != null && material.isSolid(); @@ -1865,8 +1884,6 @@ public enum CompatibleMaterial { /** * Check if the material is a block and does not block any light - * - * @return */ public boolean isTransparent() { return material != null && material.isTransparent(); @@ -1874,8 +1891,6 @@ public enum CompatibleMaterial { /** * Check if the material is a block and can catch fire - * - * @return */ public boolean isFlammable() { return material != null && material.isFlammable(); @@ -1883,8 +1898,6 @@ public enum CompatibleMaterial { /** * Check if the material is a block and can be destroyed by burning - * - * @return */ public boolean isBurnable() { return material != null && material.isBurnable(); @@ -1892,8 +1905,6 @@ public enum CompatibleMaterial { /** * Checks if this Material can be used as fuel in a Furnace - * - * @return */ public boolean isFuel() { // this function is not implemented in some older versions, so we need this here.. @@ -2253,8 +2264,6 @@ public enum CompatibleMaterial { /** * Check if the material is air - * - * @return */ public boolean isAir() { switch (this) { @@ -2269,8 +2278,6 @@ public enum CompatibleMaterial { /** * Check if the material is water - * - * @return */ public boolean isWater() { return this == CompatibleMaterial.WATER; @@ -2278,26 +2285,26 @@ public enum CompatibleMaterial { /** * Get the EntityType of the monster spawn egg. - * - * @return */ public EntityType getEggType() { String entityName = this.name().replace("_SPAWN_EGG", ""); - if (entityName.equals("MOOSHROOM")) + + if (entityName.equals("MOOSHROOM")) { entityName = "MUSHROOM_COW"; - else if (entityName.equals("ZOMBIE_PIGMAN")) + } else if (entityName.equals("ZOMBIE_PIGMAN")) { entityName = "PIG_ZOMBIE"; + } + try { return EntityType.valueOf(entityName); - } catch (IllegalArgumentException e) { - return null; + } catch (IllegalArgumentException ignore) { } + + return null; } /** * Check if the material is a block and completely blocks vision - * - * @return */ public boolean isOccluding() { return material != null && material.isOccluding(); @@ -2312,8 +2319,6 @@ public enum CompatibleMaterial { /** * Checks if this Material is an obtainable item. - * - * @return */ public boolean isItem() { // this function is not implemented in some older versions, so we need this here.. @@ -2410,16 +2415,15 @@ public enum CompatibleMaterial { case YELLOW_WALL_BANNER: case ZOMBIE_WALL_HEAD: return false; + default: + return true; } - return true; } /** * Checks if this Material can be interacted with.
* This method will return true if there is at least one state in which * additional interact handling is performed for the material. - * - * @return */ public boolean isInteractable() { // this function is not implemented in some older versions, so we need this here.. @@ -2634,11 +2638,11 @@ public enum CompatibleMaterial { case WHITE_BED: case WHITE_SHULKER_BOX: case YELLOW_BED: - case YELLOW_SHULKER_BOX: { + case YELLOW_SHULKER_BOX: return true; - } + default: + return false; } - return false; } /** @@ -2738,7 +2742,10 @@ public enum CompatibleMaterial { case WHITE_WALL_BANNER: case WITHER_SKELETON_WALL_SKULL: return false; + default: + break; } + if (ServerVersion.isServerVersionAtOrBelow(ServerVersion.V1_12)) { switch (this) { case ACACIA_WOOD: @@ -2754,8 +2761,11 @@ public enum CompatibleMaterial { case STRIPPED_OAK_WOOD: case STRIPPED_SPRUCE_WOOD: return false; + default: + break; } } + return true; } @@ -2801,8 +2811,9 @@ public enum CompatibleMaterial { case COOKED_SALMON: case DRIED_KELP: return true; + default: + return false; } - return false; } /** @@ -2820,8 +2831,9 @@ public enum CompatibleMaterial { case RABBIT: case SALMON: return true; + default: + return false; } - return false; } /** @@ -2836,8 +2848,9 @@ public enum CompatibleMaterial { case PEONY: case TALL_GRASS: return true; + default: + return false; } - return false; } /** @@ -2935,8 +2948,7 @@ public enum CompatibleMaterial { return MOOSHROOM_SPAWN_EGG; } - if (ServerVersion.isServerVersionBelow(ServerVersion.V1_16) - && type == EntityType.valueOf("PIG_ZOMBIE")) { + if (ServerVersion.isServerVersionBelow(ServerVersion.V1_16) && type == EntityType.valueOf("PIG_ZOMBIE")) { return ZOMBIE_PIGMAN_SPAWN_EGG; } @@ -2977,8 +2989,9 @@ public enum CompatibleMaterial { return RED_STAINED_GLASS_PANE; case 15: return BLACK_STAINED_GLASS_PANE; + default: + return WHITE_STAINED_GLASS; } - return WHITE_STAINED_GLASS_PANE; } public static CompatibleMaterial getGlassColor(int color) { @@ -3015,8 +3028,9 @@ public enum CompatibleMaterial { return RED_STAINED_GLASS; case 15: return BLACK_STAINED_GLASS; + default: + return WHITE_STAINED_GLASS; } - return WHITE_STAINED_GLASS; } public static CompatibleMaterial getWoolColor(int color) { @@ -3053,8 +3067,9 @@ public enum CompatibleMaterial { return RED_WOOL; case 15: return BLACK_WOOL; + default: + return WHITE_WOOL; } - return WHITE_WOOL; } public static CompatibleMaterial getDyeColor(int color) { @@ -3091,7 +3106,8 @@ public enum CompatibleMaterial { return ORANGE_DYE; case 15: return WHITE_DYE; + default: + return WHITE_DYE; } - return WHITE_DYE; } } diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleParticleHandler.java b/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleParticleHandler.java index f8622b75..9875c60a 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleParticleHandler.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleParticleHandler.java @@ -1,326 +1,325 @@ -package com.songoda.core.compatibility; - -import org.bukkit.Color; -import org.bukkit.Effect; -import org.bukkit.Location; -import org.bukkit.Particle; -import org.bukkit.block.BlockFace; -import org.bukkit.entity.Player; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Stream; - -public class CompatibleParticleHandler { - - public static enum ParticleType { - EXPLOSION_NORMAL, - EXPLOSION_LARGE, - EXPLOSION_HUGE, - FIREWORKS_SPARK, - WATER_BUBBLE, - WATER_SPLASH, - WATER_WAKE, - SUSPENDED, - SUSPENDED_DEPTH, - CRIT, - CRIT_MAGIC, - SMOKE_NORMAL, - SMOKE_LARGE, - SPELL, - SPELL_INSTANT, - SPELL_MOB, - SPELL_MOB_AMBIENT, - SPELL_WITCH, - DRIP_WATER, - DRIP_LAVA, - VILLAGER_ANGRY, - VILLAGER_HAPPY, - TOWN_AURA, - NOTE, - PORTAL, - ENCHANTMENT_TABLE, - FLAME, - LAVA, - CLOUD, - REDSTONE(), //DustOptions - SNOWBALL, - SNOW_SHOVEL, - SLIME, - HEART, - BARRIER, - ITEM_CRACK(), // ItemStack - BLOCK_CRACK(), // BlockData - BLOCK_DUST(), // BlockData - WATER_DROP, - // 1.8-1.12 included ITEM_TAKE - MOB_APPEARANCE, - /// End 1.8 particles /// - DRAGON_BREATH(ServerVersion.V1_9, "SPELL_MOB_AMBIENT"), - END_ROD(ServerVersion.V1_9, "ENCHANTMENT_TABLE"), - DAMAGE_INDICATOR(ServerVersion.V1_9, "VILLAGER_ANGRY"), - SWEEP_ATTACK(ServerVersion.V1_9, "CRIT"), - /// End 1.9 particles /// - FALLING_DUST(ServerVersion.V1_10, "BLOCK_DUST"), // BlockData - /// End 1.10 /// - TOTEM(ServerVersion.V1_11, "VILLAGER_HAPPY"), - SPIT(ServerVersion.V1_11, "REDSTONE"), - /// End 1.11-1.12 /// - SQUID_INK(ServerVersion.V1_13, "CRIT"), - BUBBLE_POP(ServerVersion.V1_13, "CRIT"), - CURRENT_DOWN(ServerVersion.V1_13, "CRIT"), - BUBBLE_COLUMN_UP(ServerVersion.V1_13, "CRIT"), - NAUTILUS(ServerVersion.V1_13, "ENCHANTMENT_TABLE"), - DOLPHIN(ServerVersion.V1_13, "TOWN_AURA"), - /// End 1.13 /// - SNEEZE(ServerVersion.V1_14, "REDSTONE"), - CAMPFIRE_COSY_SMOKE(ServerVersion.V1_14, "SMOKE_NORMAL"), - CAMPFIRE_SIGNAL_SMOKE(ServerVersion.V1_14, "SMOKE_LARGE"), - COMPOSTER(ServerVersion.V1_14, "CRIT"), - FLASH(ServerVersion.V1_14, "EXPLOSION_NORMAL"), // idk - FALLING_LAVA(ServerVersion.V1_14, "DRIP_LAVA"), - LANDING_LAVA(ServerVersion.V1_14, "LAVA"), - FALLING_WATER(ServerVersion.V1_14, "DRIP_WATER"), - /// End 1.14 /// - DRIPPING_HONEY(ServerVersion.V1_15, "DRIP_WATER"), - FALLING_HONEY(ServerVersion.V1_15, "DRIP_WATER"), - FALLING_NECTAR(ServerVersion.V1_15, "DRIP_WATER"), - LANDING_HONEY(ServerVersion.V1_15, "DRIP_WATER"), - /// End 1.15 /// - // ToDo: Someone needs to make better compatible fall backs. - SOUL_FIRE_FLAME(ServerVersion.V1_16, "DRIP_WATER"), - ASH(ServerVersion.V1_16, "DRIP_WATER"), - CRIMSON_SPORE(ServerVersion.V1_16, "DRIP_WATER"), - WARPED_SPORE(ServerVersion.V1_16, "DRIP_WATER"), - SOUL(ServerVersion.V1_16, "DRIP_WATER"), - DRIPPING_OBSIDIAN_TEAR(ServerVersion.V1_16, "DRIP_WATER"), - FALLING_OBSIDIAN_TEAR(ServerVersion.V1_16, "DRIP_WATER"), - LANDING_OBSIDIAN_TEAR(ServerVersion.V1_16, "DRIP_WATER"), - REVERSE_PORTAL(ServerVersion.V1_16, "DRIP_WATER"), - WHITE_ASH(ServerVersion.V1_16, "DRIP_WATER"), - /// End 1.16 /// - // ToDo: Someone needs to make better compatible fall backs. - LIGHT(ServerVersion.V1_17, "DRIP_WATER"), - DUST_COLOR_TRANSITION(ServerVersion.V1_17, "DRIP_WATER"), - VIBRATION(ServerVersion.V1_17, "DRIP_WATER"), - FALLING_SPORE_BLOSSOM(ServerVersion.V1_17, "DRIP_WATER"), - SPORE_BLOSSOM_AIR(ServerVersion.V1_17, "DRIP_WATER"), - SMALL_FLAME(ServerVersion.V1_17, "DRIP_WATER"), - SNOWFLAKE(ServerVersion.V1_17, "DRIP_WATER"), - DRIPPING_DRIPSTONE_LAVA(ServerVersion.V1_17, "DRIP_WATER"), - FALLING_DRIPSTONE_LAVA(ServerVersion.V1_17, "DRIP_WATER"), - DRIPPING_DRIPSTONE_WATER(ServerVersion.V1_17, "DRIP_WATER"), - FALLING_DRIPSTONE_WATER(ServerVersion.V1_17, "DRIP_WATER"), - GLOW_SQUID_INK(ServerVersion.V1_17, "DRIP_WATER"), - GLOW(ServerVersion.V1_17, "DRIP_WATER"), - WAX_ON(ServerVersion.V1_17, "DRIP_WATER"), - WAX_OFF(ServerVersion.V1_17, "DRIP_WATER"), - ELECTRIC_SPARK(ServerVersion.V1_17, "DRIP_WATER"), - SCRAPE(ServerVersion.V1_17, "DRIP_WATER"), - /// End 1.17 /// - ; - - final boolean compatibilityMode; - final LegacyParticleEffects.Type compatibleEffect; - final Object particle; - final static Map map = new HashMap<>(); - - static { - for (ParticleType t : values()) { - map.put(t.name(), t); - } - } - - private ParticleType() { - if (ServerVersion.isServerVersionAtOrBelow(ServerVersion.V1_8)) { - this.compatibilityMode = true; - this.particle = null; - this.compatibleEffect = LegacyParticleEffects.Type.valueOf(name()); - } else { - this.compatibleEffect = null; - // does this particle exist in our version? - Particle check = Stream.of(Particle.values()).filter(p -> p.name().equals(name())).findFirst().orElse(null); - if (check != null) { - this.particle = check; - this.compatibilityMode = false; - } else { - // this shouldn't happen, really - this.particle = Particle.END_ROD; - this.compatibilityMode = true; - } - } - } - - private ParticleType(ServerVersion minVersion, String compatible) { - // Particle class doesn't exist in 1.8 - if (ServerVersion.isServerVersionAtOrBelow(ServerVersion.V1_8)) { - this.compatibilityMode = true; - this.compatibleEffect = LegacyParticleEffects.Type.valueOf(compatible); - this.particle = null; - } else if (ServerVersion.isServerVersionBelow(minVersion)) { - this.compatibilityMode = true; - this.compatibleEffect = null; - this.particle = Particle.valueOf(compatible); - } else { - this.compatibleEffect = null; - // does this particle exist in our version? - Particle check = Stream.of(Particle.values()).filter(p -> p.name().equals(name())).findFirst().orElse(null); - if (check != null) { - this.particle = check; - this.compatibilityMode = false; - } else { - // this shouldn't happen, really - this.particle = Particle.END_ROD; - this.compatibilityMode = true; - } - } - } - - public static ParticleType getParticle(String name) { - return map.get(name); - } - } - - public static void spawnParticles(String type, Location location) { - spawnParticles(type, location, 0); - } - - public static void spawnParticles(String type, Location location, int count) { - ParticleType pt; - if (type != null && (pt = ParticleType.getParticle(type.toUpperCase())) != null) { - spawnParticles(pt, location, count); - } - } - - public static void spawnParticles(String type, Location location, int count, double offsetX, double offsetY, double offsetZ) { - ParticleType pt; - if (type != null && (pt = ParticleType.getParticle(type.toUpperCase())) != null) { - spawnParticles(pt, location, count, offsetX, offsetY, offsetZ); - } - } - - public static void spawnParticles(ParticleType type, Location location) { - if (ServerVersion.isServerVersionAtOrBelow(ServerVersion.V1_8)) { - LegacyParticleEffects.createParticle(location, type.compatibleEffect); - } else { - location.getWorld().spawnParticle((Particle) type.particle, location, 0); - } - } - - public static void spawnParticles(ParticleType type, Location location, int count) { - if (ServerVersion.isServerVersionAtOrBelow(ServerVersion.V1_8)) { - for (int i = 0; i < count; i++) { - float xx = (float) (1 * (Math.random() - Math.random())); - float yy = (float) (1 * (Math.random() - Math.random())); - float zz = (float) (1 * (Math.random() - Math.random())); - Location at = location.clone().add(xx, yy, zz); - LegacyParticleEffects.createParticle(at, type.compatibleEffect); - } - } else { - location.getWorld().spawnParticle((Particle) type.particle, location, count); - } - } - - public static void spawnParticles(ParticleType type, Location location, int count, double offsetX, double offsetY, double offsetZ) { - if (ServerVersion.isServerVersionAtOrBelow(ServerVersion.V1_8)) { - for (int i = 0; i < count; i++) { - float xx = (float) (offsetX * (Math.random() - Math.random())); - float yy = (float) (offsetY * (Math.random() - Math.random())); - float zz = (float) (offsetZ * (Math.random() - Math.random())); - Location at = location.clone().add(xx, yy, zz); - LegacyParticleEffects.createParticle(at, type.compatibleEffect); - } - } else { - location.getWorld().spawnParticle((Particle) type.particle, location, count, offsetX, offsetY, offsetZ); - } - } - - public static void spawnParticles(ParticleType type, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra) { - spawnParticles(type, location, count, offsetX, offsetY, offsetZ, extra, null); - } - - public static void spawnParticles(ParticleType type, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra, Player receiver) { - if (ServerVersion.isServerVersionAtOrBelow(ServerVersion.V1_8)) { - for (int i = 0; i < count; i++) { - float xx = (float) (offsetX * (Math.random() - Math.random())); - float yy = (float) (offsetY * (Math.random() - Math.random())); - float zz = (float) (offsetZ * (Math.random() - Math.random())); - Location at = location.clone().add(xx, yy, zz); - LegacyParticleEffects.createParticle(at, type.compatibleEffect, 0F, 0F, 0F, (float) extra, 0, receiver != null ? Collections.singletonList(receiver) : null); - } - } else { - if (receiver == null) { - location.getWorld().spawnParticle((Particle) type.particle, location, count, offsetX, offsetY, offsetZ, extra); - } else { - receiver.spawnParticle((Particle) type.particle, location, count, offsetX, offsetY, offsetZ, extra); - } - } - } - - public static void redstoneParticles(Location location, int red, int green, int blue) { - redstoneParticles(location, red, green, blue, 1F, 1, 0, null); - } - - public static void redstoneParticles(Location location, int red, int green, int blue, float size, int count, float radius) { - redstoneParticles(location, red, green, blue, size, count, radius, null); - } - - /** - * Spawn colored redstone particles - * - * @param location area to spawn the particle in - * @param red red value 0-255 - * @param green green value 0-255 - * @param blue blue value 0-255 - * @param size (1.13+) size of the particles - * @param count how many particles to spawn - * @param radius how far to spread out the particles from location - */ - public static void redstoneParticles(Location location, int red, int green, int blue, float size, int count, float radius, Player player) { - if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_13)) { - float xx = (float) (radius * (Math.random() - Math.random())); - float yy = (float) (radius * (Math.random() - Math.random())); - float zz = (float) (radius * (Math.random() - Math.random())); - if (player == null) - location.getWorld().spawnParticle(Particle.REDSTONE, location, count, xx, yy, zz, 1, new Particle.DustOptions(Color.fromBGR(blue, green, red), size)); - else - player.spawnParticle(Particle.REDSTONE, location, count, xx, yy, zz, 1, new Particle.DustOptions(Color.fromBGR(blue, green, red), size)); - } else if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_9)) { - for (int i = 0; i < count; i++) { - float xx = (float) (radius * (Math.random() - Math.random())); - float yy = (float) (radius * (Math.random() - Math.random())); - float zz = (float) (radius * (Math.random() - Math.random())); - Location at = location.clone().add(xx, yy, zz); - if (player == null) - location.getWorld().spawnParticle(Particle.REDSTONE, at, 0, red / 255F, green / 255F, blue / 255F, size); // particle, location, count, red, green, blue, extra data - else - player.spawnParticle(Particle.REDSTONE, at, 0, red / 255F, green / 255F, blue / 255F, size); // particle, location, count, red, green, blue, extra data - } - } else { - // WE NEED MAGIC! - for (int i = 0; i < count; i++) { - float xx = (float) (radius * (Math.random() - Math.random())); - float yy = (float) (radius * (Math.random() - Math.random())); - float zz = (float) (radius * (Math.random() - Math.random())); - Location at = location.clone().add(xx, yy, zz); - LegacyParticleEffects.createParticle(at, LegacyParticleEffects.Type.REDSTONE, - red / 255F, green / 255F, blue / 255F, 1F, - 0, player == null ? null : Collections.singletonList(player)); - } - } - } - - public static void bonemealSmoke(Location l) { - final org.bukkit.World w = l.getWorld(); - w.playEffect(l, Effect.SMOKE, BlockFace.SOUTH_EAST); - w.playEffect(l, Effect.SMOKE, BlockFace.SOUTH); - w.playEffect(l, Effect.SMOKE, BlockFace.SOUTH_WEST); - w.playEffect(l, Effect.SMOKE, BlockFace.EAST); - w.playEffect(l, Effect.SMOKE, BlockFace.SELF); - w.playEffect(l, Effect.SMOKE, BlockFace.WEST); - w.playEffect(l, Effect.SMOKE, BlockFace.NORTH_EAST); - w.playEffect(l, Effect.SMOKE, BlockFace.NORTH); - w.playEffect(l, Effect.SMOKE, BlockFace.NORTH_WEST); - } -} +package com.songoda.core.compatibility; + +import org.bukkit.Color; +import org.bukkit.Effect; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Player; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Stream; + +public class CompatibleParticleHandler { + public static enum ParticleType { + EXPLOSION_NORMAL, + EXPLOSION_LARGE, + EXPLOSION_HUGE, + FIREWORKS_SPARK, + WATER_BUBBLE, + WATER_SPLASH, + WATER_WAKE, + SUSPENDED, + SUSPENDED_DEPTH, + CRIT, + CRIT_MAGIC, + SMOKE_NORMAL, + SMOKE_LARGE, + SPELL, + SPELL_INSTANT, + SPELL_MOB, + SPELL_MOB_AMBIENT, + SPELL_WITCH, + DRIP_WATER, + DRIP_LAVA, + VILLAGER_ANGRY, + VILLAGER_HAPPY, + TOWN_AURA, + NOTE, + PORTAL, + ENCHANTMENT_TABLE, + FLAME, + LAVA, + CLOUD, + REDSTONE(), //DustOptions + SNOWBALL, + SNOW_SHOVEL, + SLIME, + HEART, + BARRIER, + ITEM_CRACK(), // ItemStack + BLOCK_CRACK(), // BlockData + BLOCK_DUST(), // BlockData + WATER_DROP, + // 1.8-1.12 included ITEM_TAKE + MOB_APPEARANCE, + /// End 1.8 particles /// + DRAGON_BREATH(ServerVersion.V1_9, "SPELL_MOB_AMBIENT"), + END_ROD(ServerVersion.V1_9, "ENCHANTMENT_TABLE"), + DAMAGE_INDICATOR(ServerVersion.V1_9, "VILLAGER_ANGRY"), + SWEEP_ATTACK(ServerVersion.V1_9, "CRIT"), + /// End 1.9 particles /// + FALLING_DUST(ServerVersion.V1_10, "BLOCK_DUST"), // BlockData + /// End 1.10 /// + TOTEM(ServerVersion.V1_11, "VILLAGER_HAPPY"), + SPIT(ServerVersion.V1_11, "REDSTONE"), + /// End 1.11-1.12 /// + SQUID_INK(ServerVersion.V1_13, "CRIT"), + BUBBLE_POP(ServerVersion.V1_13, "CRIT"), + CURRENT_DOWN(ServerVersion.V1_13, "CRIT"), + BUBBLE_COLUMN_UP(ServerVersion.V1_13, "CRIT"), + NAUTILUS(ServerVersion.V1_13, "ENCHANTMENT_TABLE"), + DOLPHIN(ServerVersion.V1_13, "TOWN_AURA"), + /// End 1.13 /// + SNEEZE(ServerVersion.V1_14, "REDSTONE"), + CAMPFIRE_COSY_SMOKE(ServerVersion.V1_14, "SMOKE_NORMAL"), + CAMPFIRE_SIGNAL_SMOKE(ServerVersion.V1_14, "SMOKE_LARGE"), + COMPOSTER(ServerVersion.V1_14, "CRIT"), + FLASH(ServerVersion.V1_14, "EXPLOSION_NORMAL"), // idk + FALLING_LAVA(ServerVersion.V1_14, "DRIP_LAVA"), + LANDING_LAVA(ServerVersion.V1_14, "LAVA"), + FALLING_WATER(ServerVersion.V1_14, "DRIP_WATER"), + /// End 1.14 /// + DRIPPING_HONEY(ServerVersion.V1_15, "DRIP_WATER"), + FALLING_HONEY(ServerVersion.V1_15, "DRIP_WATER"), + FALLING_NECTAR(ServerVersion.V1_15, "DRIP_WATER"), + LANDING_HONEY(ServerVersion.V1_15, "DRIP_WATER"), + /// End 1.15 /// + // ToDo: Someone needs to make better compatible fall backs. + SOUL_FIRE_FLAME(ServerVersion.V1_16, "DRIP_WATER"), + ASH(ServerVersion.V1_16, "DRIP_WATER"), + CRIMSON_SPORE(ServerVersion.V1_16, "DRIP_WATER"), + WARPED_SPORE(ServerVersion.V1_16, "DRIP_WATER"), + SOUL(ServerVersion.V1_16, "DRIP_WATER"), + DRIPPING_OBSIDIAN_TEAR(ServerVersion.V1_16, "DRIP_WATER"), + FALLING_OBSIDIAN_TEAR(ServerVersion.V1_16, "DRIP_WATER"), + LANDING_OBSIDIAN_TEAR(ServerVersion.V1_16, "DRIP_WATER"), + REVERSE_PORTAL(ServerVersion.V1_16, "DRIP_WATER"), + WHITE_ASH(ServerVersion.V1_16, "DRIP_WATER"), + /// End 1.16 /// + // ToDo: Someone needs to make better compatible fall backs. + LIGHT(ServerVersion.V1_17, "DRIP_WATER"), + DUST_COLOR_TRANSITION(ServerVersion.V1_17, "DRIP_WATER"), + VIBRATION(ServerVersion.V1_17, "DRIP_WATER"), + FALLING_SPORE_BLOSSOM(ServerVersion.V1_17, "DRIP_WATER"), + SPORE_BLOSSOM_AIR(ServerVersion.V1_17, "DRIP_WATER"), + SMALL_FLAME(ServerVersion.V1_17, "DRIP_WATER"), + SNOWFLAKE(ServerVersion.V1_17, "DRIP_WATER"), + DRIPPING_DRIPSTONE_LAVA(ServerVersion.V1_17, "DRIP_WATER"), + FALLING_DRIPSTONE_LAVA(ServerVersion.V1_17, "DRIP_WATER"), + DRIPPING_DRIPSTONE_WATER(ServerVersion.V1_17, "DRIP_WATER"), + FALLING_DRIPSTONE_WATER(ServerVersion.V1_17, "DRIP_WATER"), + GLOW_SQUID_INK(ServerVersion.V1_17, "DRIP_WATER"), + GLOW(ServerVersion.V1_17, "DRIP_WATER"), + WAX_ON(ServerVersion.V1_17, "DRIP_WATER"), + WAX_OFF(ServerVersion.V1_17, "DRIP_WATER"), + ELECTRIC_SPARK(ServerVersion.V1_17, "DRIP_WATER"), + SCRAPE(ServerVersion.V1_17, "DRIP_WATER"), + /// End 1.17 /// + ; + + final boolean compatibilityMode; + final LegacyParticleEffects.Type compatibleEffect; + final Object particle; + final static Map map = new HashMap<>(); + + static { + for (ParticleType t : values()) { + map.put(t.name(), t); + } + } + + private ParticleType() { + if (ServerVersion.isServerVersionAtOrBelow(ServerVersion.V1_8)) { + this.compatibilityMode = true; + this.particle = null; + this.compatibleEffect = LegacyParticleEffects.Type.valueOf(name()); + } else { + this.compatibleEffect = null; + // does this particle exist in our version? + Particle check = Stream.of(Particle.values()).filter(p -> p.name().equals(name())).findFirst().orElse(null); + if (check != null) { + this.particle = check; + this.compatibilityMode = false; + } else { + // this shouldn't happen, really + this.particle = Particle.END_ROD; + this.compatibilityMode = true; + } + } + } + + private ParticleType(ServerVersion minVersion, String compatible) { + // Particle class doesn't exist in 1.8 + if (ServerVersion.isServerVersionAtOrBelow(ServerVersion.V1_8)) { + this.compatibilityMode = true; + this.compatibleEffect = LegacyParticleEffects.Type.valueOf(compatible); + this.particle = null; + } else if (ServerVersion.isServerVersionBelow(minVersion)) { + this.compatibilityMode = true; + this.compatibleEffect = null; + this.particle = Particle.valueOf(compatible); + } else { + this.compatibleEffect = null; + // does this particle exist in our version? + Particle check = Stream.of(Particle.values()).filter(p -> p.name().equals(name())).findFirst().orElse(null); + if (check != null) { + this.particle = check; + this.compatibilityMode = false; + } else { + // this shouldn't happen, really + this.particle = Particle.END_ROD; + this.compatibilityMode = true; + } + } + } + + public static ParticleType getParticle(String name) { + return map.get(name); + } + } + + public static void spawnParticles(String type, Location location) { + spawnParticles(type, location, 0); + } + + public static void spawnParticles(String type, Location location, int count) { + ParticleType pt; + if (type != null && (pt = ParticleType.getParticle(type.toUpperCase())) != null) { + spawnParticles(pt, location, count); + } + } + + public static void spawnParticles(String type, Location location, int count, double offsetX, double offsetY, double offsetZ) { + ParticleType pt; + if (type != null && (pt = ParticleType.getParticle(type.toUpperCase())) != null) { + spawnParticles(pt, location, count, offsetX, offsetY, offsetZ); + } + } + + public static void spawnParticles(ParticleType type, Location location) { + if (ServerVersion.isServerVersionAtOrBelow(ServerVersion.V1_8)) { + LegacyParticleEffects.createParticle(location, type.compatibleEffect); + } else { + location.getWorld().spawnParticle((Particle) type.particle, location, 0); + } + } + + public static void spawnParticles(ParticleType type, Location location, int count) { + if (ServerVersion.isServerVersionAtOrBelow(ServerVersion.V1_8)) { + for (int i = 0; i < count; i++) { + float xx = (float) (1 * (Math.random() - Math.random())); + float yy = (float) (1 * (Math.random() - Math.random())); + float zz = (float) (1 * (Math.random() - Math.random())); + Location at = location.clone().add(xx, yy, zz); + LegacyParticleEffects.createParticle(at, type.compatibleEffect); + } + } else { + location.getWorld().spawnParticle((Particle) type.particle, location, count); + } + } + + public static void spawnParticles(ParticleType type, Location location, int count, double offsetX, double offsetY, double offsetZ) { + if (ServerVersion.isServerVersionAtOrBelow(ServerVersion.V1_8)) { + for (int i = 0; i < count; i++) { + float xx = (float) (offsetX * (Math.random() - Math.random())); + float yy = (float) (offsetY * (Math.random() - Math.random())); + float zz = (float) (offsetZ * (Math.random() - Math.random())); + Location at = location.clone().add(xx, yy, zz); + LegacyParticleEffects.createParticle(at, type.compatibleEffect); + } + } else { + location.getWorld().spawnParticle((Particle) type.particle, location, count, offsetX, offsetY, offsetZ); + } + } + + public static void spawnParticles(ParticleType type, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra) { + spawnParticles(type, location, count, offsetX, offsetY, offsetZ, extra, null); + } + + public static void spawnParticles(ParticleType type, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra, Player receiver) { + if (ServerVersion.isServerVersionAtOrBelow(ServerVersion.V1_8)) { + for (int i = 0; i < count; i++) { + float xx = (float) (offsetX * (Math.random() - Math.random())); + float yy = (float) (offsetY * (Math.random() - Math.random())); + float zz = (float) (offsetZ * (Math.random() - Math.random())); + Location at = location.clone().add(xx, yy, zz); + LegacyParticleEffects.createParticle(at, type.compatibleEffect, 0F, 0F, 0F, (float) extra, 0, receiver != null ? Collections.singletonList(receiver) : null); + } + } else { + if (receiver == null) { + location.getWorld().spawnParticle((Particle) type.particle, location, count, offsetX, offsetY, offsetZ, extra); + } else { + receiver.spawnParticle((Particle) type.particle, location, count, offsetX, offsetY, offsetZ, extra); + } + } + } + + public static void redstoneParticles(Location location, int red, int green, int blue) { + redstoneParticles(location, red, green, blue, 1F, 1, 0, null); + } + + public static void redstoneParticles(Location location, int red, int green, int blue, float size, int count, float radius) { + redstoneParticles(location, red, green, blue, size, count, radius, null); + } + + /** + * Spawn colored redstone particles + * + * @param location area to spawn the particle in + * @param red red value 0-255 + * @param green green value 0-255 + * @param blue blue value 0-255 + * @param size (1.13+) size of the particles + * @param count how many particles to spawn + * @param radius how far to spread out the particles from location + */ + public static void redstoneParticles(Location location, int red, int green, int blue, float size, int count, float radius, Player player) { + if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_13)) { + float xx = (float) (radius * (Math.random() - Math.random())); + float yy = (float) (radius * (Math.random() - Math.random())); + float zz = (float) (radius * (Math.random() - Math.random())); + if (player == null) + location.getWorld().spawnParticle(Particle.REDSTONE, location, count, xx, yy, zz, 1, new Particle.DustOptions(Color.fromBGR(blue, green, red), size)); + else + player.spawnParticle(Particle.REDSTONE, location, count, xx, yy, zz, 1, new Particle.DustOptions(Color.fromBGR(blue, green, red), size)); + } else if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_9)) { + for (int i = 0; i < count; i++) { + float xx = (float) (radius * (Math.random() - Math.random())); + float yy = (float) (radius * (Math.random() - Math.random())); + float zz = (float) (radius * (Math.random() - Math.random())); + Location at = location.clone().add(xx, yy, zz); + if (player == null) + location.getWorld().spawnParticle(Particle.REDSTONE, at, 0, red / 255F, green / 255F, blue / 255F, size); // particle, location, count, red, green, blue, extra data + else + player.spawnParticle(Particle.REDSTONE, at, 0, red / 255F, green / 255F, blue / 255F, size); // particle, location, count, red, green, blue, extra data + } + } else { + // WE NEED MAGIC! + for (int i = 0; i < count; i++) { + float xx = (float) (radius * (Math.random() - Math.random())); + float yy = (float) (radius * (Math.random() - Math.random())); + float zz = (float) (radius * (Math.random() - Math.random())); + Location at = location.clone().add(xx, yy, zz); + LegacyParticleEffects.createParticle(at, LegacyParticleEffects.Type.REDSTONE, + red / 255F, green / 255F, blue / 255F, 1F, + 0, player == null ? null : Collections.singletonList(player)); + } + } + } + + public static void bonemealSmoke(Location l) { + final org.bukkit.World w = l.getWorld(); + w.playEffect(l, Effect.SMOKE, BlockFace.SOUTH_EAST); + w.playEffect(l, Effect.SMOKE, BlockFace.SOUTH); + w.playEffect(l, Effect.SMOKE, BlockFace.SOUTH_WEST); + w.playEffect(l, Effect.SMOKE, BlockFace.EAST); + w.playEffect(l, Effect.SMOKE, BlockFace.SELF); + w.playEffect(l, Effect.SMOKE, BlockFace.WEST); + w.playEffect(l, Effect.SMOKE, BlockFace.NORTH_EAST); + w.playEffect(l, Effect.SMOKE, BlockFace.NORTH); + w.playEffect(l, Effect.SMOKE, BlockFace.NORTH_WEST); + } +} diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleSound.java b/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleSound.java index d4165184..89f36e05 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleSound.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleSound.java @@ -18,7 +18,6 @@ import org.bukkit.entity.Player; * @since 2019-08-25 */ public enum CompatibleSound { - // some of these values are missing an API value.. // would using the raw strings be better? // 1.8 list: @@ -1247,14 +1246,15 @@ public enum CompatibleSound { private CompatibleSound(String compatibility_18) { try { compatibilityMode = false; + if (ServerVersion.isServerVersionBelow(ServerVersion.V1_9)) { sound = Sound.valueOf(compatibility_18); } else { sound = Sound.valueOf(name()); } - } catch (Exception e) { + } catch (Exception ex) { System.err.println("ERROR loading " + name()); - e.printStackTrace(); + ex.printStackTrace(); } } @@ -1267,12 +1267,13 @@ public enum CompatibleSound { return; } } - } catch (Exception e) { + } catch (Exception ex) { System.err.println("ERROR loading " + name()); for (Version v : versions) { System.err.println(v.version + " - " + v.sound); } - e.printStackTrace(); + + ex.printStackTrace(); } Sound find = null; for (Sound s : Sound.values()) { @@ -1302,12 +1303,13 @@ public enum CompatibleSound { sound = null; compatibilityMode = false; } - } catch (Exception e) { + } catch (Exception ex) { System.err.println("ERROR loading " + name() + " (" + minVersion); for (Version v : versions) { System.err.println(v.version + " - " + v.sound); } - e.printStackTrace(); + + ex.printStackTrace(); } } diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/EntityNamespace.java b/Compatibility/src/main/java/com/songoda/core/compatibility/EntityNamespace.java index b7aa41c1..4f83c87f 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/EntityNamespace.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/EntityNamespace.java @@ -1,85 +1,88 @@ -package com.songoda.core.compatibility; - -import org.bukkit.entity.EntityType; - -import java.util.HashMap; -import java.util.Map; - -public class EntityNamespace { - - static final HashMap validTypes = new HashMap(); - static final HashMap legacyToModernTypes = new HashMap() { - { - put("xporb", "experience_orb"); - put("xp_orb", "experience_orb"); - put("leashknot", "leash_knot"); - put("smallfireball", "small_fireball"); - put("thrownenderpearl", "ender_pearl"); - put("eyeofendersignal", "eye_of_ender"); - put("eye_of_ender_signal", "eye_of_ender"); - put("thrownexpbottle", "experience_bottle"); - put("xp_bottle", "experience_bottle"); - put("itemframe", "item_frame"); - put("witherskull", "wither_skull"); - put("primedtnt", "tnt"); - put("fallingsand", "falling_block"); - put("fireworksrocketentity", "firework_rocket"); - put("fireworks_rocket", "firework_rocket"); - put("spectralarrow", "spectral_arrow"); - put("tippedarrow", "arrow"); - put("shulkerbullet", "shulker_bullet"); - put("dragonfireball", "dragon_fireball"); - put("armorstand", "armor_stand"); - put("minecartcommandblock", "command_block_minecart"); - put("commandblock_minecart", "command_block_minecart"); - put("minecartrideable", "minecart"); - put("minecartchest", "chest_minecart"); - put("minecartfurnace", "furnace_minecart"); - put("minecarttnt", "tnt_minecart"); - put("minecarthopper", "hopper_minecart"); - put("minecartmobspawner", "spawner_minecart"); - put("pigzombie", "zombie_pigman"); - put("cavespider", "cave_spider"); - put("lavaslime", "magma_cube"); - put("enderdragon", "ender_dragon"); - put("witherboss", "wither"); - put("mushroomcow", "mooshroom"); - put("snowman", "snow_golem"); - put("ozelot", "ocelot"); - put("villagergolem", "iron_golem"); - put("villager_golem", "iron_golem"); - put("entityhorse", "horse"); - put("endercrystal", "end_crystal"); - put("ender_crystal", "end_crystal"); - } - }; - - static { - for (EntityType t : EntityType.values()) { - if (t.getName() != null) { - validTypes.put(t.getName().toLowerCase(), t); - } - } - } - - public static EntityType minecraftToBukkit(String entity) { - if (entity == null) { - return null; - } - // first try to translate natively - EntityType type = EntityType.fromName(entity); - if (type == null) { - // try legacy values - type = EntityType.fromName(legacyToModernTypes.get(entity)); - // try converting modern to legacy - if (type == null && legacyToModernTypes.containsValue(entity)) { - for (Map.Entry e : legacyToModernTypes.entrySet()) { - if (e.getValue().equals(entity) && (type = EntityType.fromName(legacyToModernTypes.get(e.getKey()))) != null) { - return type; - } - } - } - } - return type; - } -} +package com.songoda.core.compatibility; + +import org.bukkit.entity.EntityType; + +import java.util.HashMap; +import java.util.Map; + +public class EntityNamespace { + static final HashMap validTypes = new HashMap(); + static final HashMap legacyToModernTypes = new HashMap() { + { + put("xporb", "experience_orb"); + put("xp_orb", "experience_orb"); + put("leashknot", "leash_knot"); + put("smallfireball", "small_fireball"); + put("thrownenderpearl", "ender_pearl"); + put("eyeofendersignal", "eye_of_ender"); + put("eye_of_ender_signal", "eye_of_ender"); + put("thrownexpbottle", "experience_bottle"); + put("xp_bottle", "experience_bottle"); + put("itemframe", "item_frame"); + put("witherskull", "wither_skull"); + put("primedtnt", "tnt"); + put("fallingsand", "falling_block"); + put("fireworksrocketentity", "firework_rocket"); + put("fireworks_rocket", "firework_rocket"); + put("spectralarrow", "spectral_arrow"); + put("tippedarrow", "arrow"); + put("shulkerbullet", "shulker_bullet"); + put("dragonfireball", "dragon_fireball"); + put("armorstand", "armor_stand"); + put("minecartcommandblock", "command_block_minecart"); + put("commandblock_minecart", "command_block_minecart"); + put("minecartrideable", "minecart"); + put("minecartchest", "chest_minecart"); + put("minecartfurnace", "furnace_minecart"); + put("minecarttnt", "tnt_minecart"); + put("minecarthopper", "hopper_minecart"); + put("minecartmobspawner", "spawner_minecart"); + put("pigzombie", "zombie_pigman"); + put("cavespider", "cave_spider"); + put("lavaslime", "magma_cube"); + put("enderdragon", "ender_dragon"); + put("witherboss", "wither"); + put("mushroomcow", "mooshroom"); + put("snowman", "snow_golem"); + put("ozelot", "ocelot"); + put("villagergolem", "iron_golem"); + put("villager_golem", "iron_golem"); + put("entityhorse", "horse"); + put("endercrystal", "end_crystal"); + put("ender_crystal", "end_crystal"); + } + }; + + static { + for (EntityType t : EntityType.values()) { + if (t.getName() != null) { + validTypes.put(t.getName().toLowerCase(), t); + } + } + } + + public static EntityType minecraftToBukkit(String entity) { + if (entity == null) { + return null; + } + + // first try to translate natively + EntityType type = EntityType.fromName(entity); + + if (type == null) { + // try legacy values + type = EntityType.fromName(legacyToModernTypes.get(entity)); + + // try converting modern to legacy + if (type == null && legacyToModernTypes.containsValue(entity)) { + for (Map.Entry e : legacyToModernTypes.entrySet()) { + if (e.getValue().equals(entity) && (type = EntityType.fromName(legacyToModernTypes.get(e.getKey()))) != null) { + return type; + } + } + } + } + + return type; + } +} diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyMaterialAnalouge.java b/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyMaterialAnalouge.java index 7c6dad6e..c4e0fca5 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyMaterialAnalouge.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyMaterialAnalouge.java @@ -1,856 +1,852 @@ -package com.songoda.core.compatibility; - -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; - -import java.util.HashMap; -import java.util.Map; - -/** - * Near-Materials for older servers 1.7+ - * - * @author jascotty2 - * @since 2019-08-23 - */ -public enum LegacyMaterialAnalouge { - - /* 1.17 */ - // ToDo: Improve legal materials. - AMETHYST_BLOCK(ServerVersion.V1_17, "STONE"), - AMETHYST_CLUSTER(ServerVersion.V1_17, "STONE"), - AMETHYST_SHARD(ServerVersion.V1_17, "STONE"), - AXOLOTL_BUCKET(ServerVersion.V1_17, "STONE"), - AXOLOTL_SPAWN_EGG(ServerVersion.V1_17, "STONE"), - AZALEA(ServerVersion.V1_17, "STONE"), - AZALEA_LEAVES(ServerVersion.V1_17, "STONE"), - BIG_DRIPLEAF(ServerVersion.V1_17, "STONE"), - BIG_DRIPLEAF_STEM(ServerVersion.V1_17, "STONE"), - BLACK_CANDLE(ServerVersion.V1_17, "STONE"), - BLACK_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), - BLUE_CANDLE(ServerVersion.V1_17, "STONE"), - BLUE_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), - BROWN_CANDLE(ServerVersion.V1_17, "STONE"), - BROWN_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), - BUDDING_AMETHYST(ServerVersion.V1_17, "STONE"), - BUNDLE(ServerVersion.V1_17, "STONE"), - CALCITE(ServerVersion.V1_17, "STONE"), - CANDLE(ServerVersion.V1_17, "STONE"), - CANDLE_CAKE(ServerVersion.V1_17, "STONE"), - CAVE_VINES(ServerVersion.V1_17, "STONE"), - CAVE_VINES_PLANT(ServerVersion.V1_17, "STONE"), - CHISELED_DEEPSLATE(ServerVersion.V1_17, "STONE"), - COBBLED_DEEPSLATE(ServerVersion.V1_17, "STONE"), - COBBLED_DEEPSLATE_SLAB(ServerVersion.V1_17, "STONE"), - COBBLED_DEEPSLATE_STAIRS(ServerVersion.V1_17, "STONE"), - COBBLED_DEEPSLATE_WALL(ServerVersion.V1_17, "STONE"), - COPPER_BLOCK(ServerVersion.V1_17, "STONE"), - COPPER_INGOT(ServerVersion.V1_17, "STONE"), - COPPER_ORE(ServerVersion.V1_17, "STONE"), - CRACKED_DEEPSLATE_BRICKS(ServerVersion.V1_17, "STONE"), - CRACKED_DEEPSLATE_TILES(ServerVersion.V1_17, "STONE"), - CUT_COPPER(ServerVersion.V1_17, "STONE"), - CUT_COPPER_SLAB(ServerVersion.V1_17, "STONE"), - CUT_COPPER_STAIRS(ServerVersion.V1_17, "STONE"), - CYAN_CANDLE(ServerVersion.V1_17, "STONE"), - CYAN_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), - DEEPSLATE(ServerVersion.V1_17, "STONE"), - DEEPSLATE_BRICKS(ServerVersion.V1_17, "STONE"), - DEEPSLATE_BRICK_SLAB(ServerVersion.V1_17, "STONE"), - DEEPSLATE_BRICK_STAIRS(ServerVersion.V1_17, "STONE"), - DEEPSLATE_BRICK_WALL(ServerVersion.V1_17, "STONE"), - DEEPSLATE_COAL_ORE(ServerVersion.V1_17, "STONE"), - DEEPSLATE_COPPER_ORE(ServerVersion.V1_17, "STONE"), - DEEPSLATE_DIAMOND_ORE(ServerVersion.V1_17, "STONE"), - DEEPSLATE_EMERALD_ORE(ServerVersion.V1_17, "STONE"), - DEEPSLATE_GOLD_ORE(ServerVersion.V1_17, "STONE"), - DEEPSLATE_IRON_ORE(ServerVersion.V1_17, "STONE"), - DEEPSLATE_LAPIS_ORE(ServerVersion.V1_17, "STONE"), - DEEPSLATE_REDSTONE_ORE(ServerVersion.V1_17, "STONE"), - DEEPSLATE_TILES(ServerVersion.V1_17, "STONE"), - DEEPSLATE_TILE_SLAB(ServerVersion.V1_17, "STONE"), - DEEPSLATE_TILE_STAIRS(ServerVersion.V1_17, "STONE"), - DEEPSLATE_TILE_WALL(ServerVersion.V1_17, "STONE"), - DRIPSTONE_BLOCK(ServerVersion.V1_17, "STONE"), - EXPOSED_COPPER(ServerVersion.V1_17, "STONE"), - EXPOSED_CUT_COPPER(ServerVersion.V1_17, "STONE"), - EXPOSED_CUT_COPPER_SLAB(ServerVersion.V1_17, "STONE"), - EXPOSED_CUT_COPPER_STAIRS(ServerVersion.V1_17, "STONE"), - FLOWERING_AZALEA(ServerVersion.V1_17, "STONE"), - FLOWERING_AZALEA_LEAVES(ServerVersion.V1_17, "STONE"), - GLOW_BERRIES(ServerVersion.V1_17, "STONE"), - GLOW_INK_SAC(ServerVersion.V1_17, "STONE"), - GLOW_ITEM_FRAME(ServerVersion.V1_17, "STONE"), - GLOW_LICHEN(ServerVersion.V1_17, "STONE"), - GLOW_SQUID_SPAWN_EGG(ServerVersion.V1_17, "STONE"), - GOAT_SPAWN_EGG(ServerVersion.V1_17, "STONE"), - GRAY_CANDLE(ServerVersion.V1_17, "STONE"), - GRAY_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), - GREEN_CANDLE(ServerVersion.V1_17, "STONE"), - GREEN_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), - HANGING_ROOTS(ServerVersion.V1_17, "STONE"), - INFESTED_DEEPSLATE(ServerVersion.V1_17, "STONE"), - LARGE_AMETHYST_BUD(ServerVersion.V1_17, "STONE"), - LAVA_CAULDRON(ServerVersion.V1_17, "STONE"), - LIGHT(ServerVersion.V1_17, "STONE"), - LIGHTNING_ROD(ServerVersion.V1_17, "STONE"), - LIGHT_BLUE_CANDLE(ServerVersion.V1_17, "STONE"), - LIGHT_BLUE_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), - LIGHT_GRAY_CANDLE(ServerVersion.V1_17, "STONE"), - LIGHT_GRAY_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), - LIME_CANDLE(ServerVersion.V1_17, "STONE"), - LIME_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), - MAGENTA_CANDLE(ServerVersion.V1_17, "STONE"), - MAGENTA_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), - MEDIUM_AMETHYST_BUD(ServerVersion.V1_17, "STONE"), - MOSS_BLOCK(ServerVersion.V1_17, "STONE"), - MOSS_CARPET(ServerVersion.V1_17, "STONE"), - ORANGE_CANDLE(ServerVersion.V1_17, "STONE"), - ORANGE_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), - OXIDIZED_COPPER(ServerVersion.V1_17, "STONE"), - OXIDIZED_CUT_COPPER(ServerVersion.V1_17, "STONE"), - OXIDIZED_CUT_COPPER_SLAB(ServerVersion.V1_17, "STONE"), - OXIDIZED_CUT_COPPER_STAIRS(ServerVersion.V1_17, "STONE"), - PINK_CANDLE(ServerVersion.V1_17, "STONE"), - PINK_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), - POINTED_DRIPSTONE(ServerVersion.V1_17, "STONE"), - POLISHED_DEEPSLATE(ServerVersion.V1_17, "STONE"), - POLISHED_DEEPSLATE_SLAB(ServerVersion.V1_17, "STONE"), - POLISHED_DEEPSLATE_STAIRS(ServerVersion.V1_17, "STONE"), - POLISHED_DEEPSLATE_WALL(ServerVersion.V1_17, "STONE"), - POTTED_AZALEA_BUSH(ServerVersion.V1_17, "STONE"), - POTTED_FLOWERING_AZALEA_BUSH(ServerVersion.V1_17, "STONE"), - POWDER_SNOW(ServerVersion.V1_17, "STONE"), - POWDER_SNOW_BUCKET(ServerVersion.V1_17, "STONE"), - POWDER_SNOW_CAULDRON(ServerVersion.V1_17, "STONE"), - PURPLE_CANDLE(ServerVersion.V1_17, "STONE"), - PURPLE_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), - RAW_COPPER(ServerVersion.V1_17, "STONE"), - RAW_COPPER_BLOCK(ServerVersion.V1_17, "STONE"), - RAW_GOLD(ServerVersion.V1_17, "STONE"), - RAW_GOLD_BLOCK(ServerVersion.V1_17, "STONE"), - RAW_IRON(ServerVersion.V1_17, "STONE"), - RAW_IRON_BLOCK(ServerVersion.V1_17, "STONE"), - RED_CANDLE(ServerVersion.V1_17, "STONE"), - RED_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), - ROOTED_DIRT(ServerVersion.V1_17, "STONE"), - SCULK_SENSOR(ServerVersion.V1_17, "STONE"), - SMALL_AMETHYST_BUD(ServerVersion.V1_17, "STONE"), - SMALL_DRIPLEAF(ServerVersion.V1_17, "STONE"), - SMOOTH_BASALT(ServerVersion.V1_17, "STONE"), - SPORE_BLOSSOM(ServerVersion.V1_17, "STONE"), - SPYGLASS(ServerVersion.V1_17, "STONE"), - TINTED_GLASS(ServerVersion.V1_17, "STONE"), - TUFF(ServerVersion.V1_17, "STONE"), - WATER_CAULDRON(ServerVersion.V1_17, "STONE"), - WAXED_COPPER_BLOCK(ServerVersion.V1_17, "STONE"), - WAXED_CUT_COPPER(ServerVersion.V1_17, "STONE"), - WAXED_CUT_COPPER_SLAB(ServerVersion.V1_17, "STONE"), - WAXED_CUT_COPPER_STAIRS(ServerVersion.V1_17, "STONE"), - WAXED_EXPOSED_COPPER(ServerVersion.V1_17, "STONE"), - WAXED_EXPOSED_CUT_COPPER(ServerVersion.V1_17, "STONE"), - WAXED_EXPOSED_CUT_COPPER_SLAB(ServerVersion.V1_17, "STONE"), - WAXED_EXPOSED_CUT_COPPER_STAIRS(ServerVersion.V1_17, "STONE"), - WAXED_OXIDIZED_COPPER(ServerVersion.V1_17, "STONE"), - WAXED_OXIDIZED_CUT_COPPER(ServerVersion.V1_17, "STONE"), - WAXED_OXIDIZED_CUT_COPPER_SLAB(ServerVersion.V1_17, "STONE"), - WAXED_OXIDIZED_CUT_COPPER_STAIRS(ServerVersion.V1_17, "STONE"), - WAXED_WEATHERED_COPPER(ServerVersion.V1_17, "STONE"), - WAXED_WEATHERED_CUT_COPPER(ServerVersion.V1_17, "STONE"), - WAXED_WEATHERED_CUT_COPPER_SLAB(ServerVersion.V1_17, "STONE"), - WAXED_WEATHERED_CUT_COPPER_STAIRS(ServerVersion.V1_17, "STONE"), - WEATHERED_COPPER(ServerVersion.V1_17, "STONE"), - WEATHERED_CUT_COPPER(ServerVersion.V1_17, "STONE"), - WEATHERED_CUT_COPPER_SLAB(ServerVersion.V1_17, "STONE"), - WEATHERED_CUT_COPPER_STAIRS(ServerVersion.V1_17, "STONE"), - WHITE_CANDLE(ServerVersion.V1_17, "STONE"), - WHITE_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), - YELLOW_CANDLE(ServerVersion.V1_17, "STONE"), - YELLOW_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), - - /* 1.16 */ - // ToDo: Improve legal materials. - ANCIENT_DEBRIES(ServerVersion.V1_16, "STONE"), - BASALT(ServerVersion.V1_16, "STONE"), - BLACKSTONE(ServerVersion.V1_16, "STONE"), - BLACKSTONE_STAIRS(ServerVersion.V1_16, "STONE"), - BLACKSTONE_WALL(ServerVersion.V1_16, "STONE"), - BLASTSTONE_SLAB(ServerVersion.V1_16, "STONE"), - CHAIN(ServerVersion.V1_16, "STONE"), - CHISELED_NETHER_BRICKS(ServerVersion.V1_16, "STONE"), - CHISELED_POLISHED_BLACKSTONE(ServerVersion.V1_16, "STONE"), - CRACKED_NETHER_BRICKS(ServerVersion.V1_16, "STONE"), - CRACKED_POLISHED_BLACKSTONE_BRICKS(ServerVersion.V1_16, "STONE"), - CRIMSON_BUTTON(ServerVersion.V1_16, "STONE"), - CRIMSON_DOOR(ServerVersion.V1_16, "STONE"), - CRIMSON_FENCE(ServerVersion.V1_16, "STONE"), - CRIMSON_FENCE_GATE(ServerVersion.V1_16, "STONE"), - CRIMSON_FUNGUS(ServerVersion.V1_16, "STONE"), - CRIMSON_HYPHAE(ServerVersion.V1_16, "STONE"), - CRIMSON_NYLIUM(ServerVersion.V1_16, "STONE"), - CRIMSON_PLANKS(ServerVersion.V1_16, "STONE"), - CRIMSON_PRESSURE_PLATE(ServerVersion.V1_16, "STONE"), - CRIMSON_ROOTS(ServerVersion.V1_16, "STONE"), - CRIMSON_SIGN(ServerVersion.V1_16, "STONE"), - CRIMSON_SLAB(ServerVersion.V1_16, "STONE"), - CRIMSON_STAIRS(ServerVersion.V1_16, "STONE"), - CRIMSON_STEM(ServerVersion.V1_16, "STONE"), - CRIMSON_TRAPDOOR(ServerVersion.V1_16, "STONE"), - CRIMSON_WALL_SIGN(ServerVersion.V1_16, "STONE"), - CRYING_OBSIDIAN(ServerVersion.V1_16, "STONE"), - GILDED_BLACKSTONE(ServerVersion.V1_16, "STONE"), - HOGLIN_SPAWN_EGG(ServerVersion.V1_16, "STONE"), - LODESTONE(ServerVersion.V1_16, "STONE"), - MUSIC_DISC_PIGSTEP(ServerVersion.V1_16, "STONE"), - NETHERITE_AXE(ServerVersion.V1_16, "STONE"), - NETHERITE_BLOCK(ServerVersion.V1_16, "STONE"), - NETHERITE_BOOTS(ServerVersion.V1_16, "STONE"), - NETHERITE_CHESTPLATE(ServerVersion.V1_16, "STONE"), - NETHERITE_HELMET(ServerVersion.V1_16, "STONE"), - NETHERITE_HOE(ServerVersion.V1_16, "STONE"), - NETHERITE_INGOT(ServerVersion.V1_16, "STONE"), - NETHERITE_LEGGINGS(ServerVersion.V1_16, "STONE"), - NETHERITE_PICKAXE(ServerVersion.V1_16, "STONE"), - NETHERITE_SCRAP(ServerVersion.V1_16, "STONE"), - NETHERITE_SHOVEL(ServerVersion.V1_16, "STONE"), - NETHERITE_SWORD(ServerVersion.V1_16, "STONE"), - NETHER_GOLD_ORE(ServerVersion.V1_16, "STONE"), - NETHER_SPROUTS(ServerVersion.V1_16, "STONE"), - PIGLIN_BANNER_PATTERN(ServerVersion.V1_16, "STONE"), - PIGLIN_SPAWN_EGG(ServerVersion.V1_16, "STONE"), - POLISHED_BASALT(ServerVersion.V1_16, "STONE"), - POLISHED_BLACKSTONE(ServerVersion.V1_16, "STONE"), - POLISHED_BLACKSTONE_BRICKS(ServerVersion.V1_16, "STONE"), - POLISHED_BLACKSTONE_BRICK_SLAB(ServerVersion.V1_16, "STONE"), - POLISHED_BLACKSTONE_BRICK_STAIRS(ServerVersion.V1_16, "STONE"), - POLISHED_BLACKSTONE_BRICK_WALL(ServerVersion.V1_16, "STONE"), - POLISHED_BLACKSTONE_BUTTON(ServerVersion.V1_16, "STONE"), - POLISHED_BLACKSTONE_PRESSURE_PLATE(ServerVersion.V1_16, "STONE"), - POLISHED_BLACKSTONE_SLAB(ServerVersion.V1_16, "STONE"), - POLISHED_BLACKSTONE_STAIRS(ServerVersion.V1_16, "STONE"), - POLISHED_BLACKSTONE_WALL(ServerVersion.V1_16, "STONE"), - POTTED_CRIMSON_FUNGUS(ServerVersion.V1_16, "STONE"), - POTTED_CRIMSON_ROOTS(ServerVersion.V1_16, "STONE"), - POTTED_WARPED_FUNGUS(ServerVersion.V1_16, "STONE"), - POTTED_WARPED_ROOTS(ServerVersion.V1_16, "STONE"), - QUARTZ_BRICKS(ServerVersion.V1_16, "STONE"), - RESPAWN_ANCHOR(ServerVersion.V1_16, "STONE"), - SHROOMLIGHT(ServerVersion.V1_16, "STONE"), - SOUL_CAMPFIRE(ServerVersion.V1_16, "STONE"), - SOUL_FIRE(ServerVersion.V1_16, "STONE"), - SOUL_LANTERN(ServerVersion.V1_16, "STONE"), - SOUL_SOIL(ServerVersion.V1_16, "STONE"), - SOUL_TORCH(ServerVersion.V1_16, "STONE"), - SOUL_WALL_TORCH(ServerVersion.V1_16, "STONE"), - STRIDER_SPAWN_EGG(ServerVersion.V1_16, "STONE"), - STRIPPED_CRIMSON_HYPHAE(ServerVersion.V1_16, "STONE"), - STRIPPED_CRIMSON_STEM(ServerVersion.V1_16, "STONE"), - STRIPPED_WARPED_HYPHAE(ServerVersion.V1_16, "STONE"), - STRIPPED_WARPED_STEM(ServerVersion.V1_16, "STONE"), - TARGET(ServerVersion.V1_16, "STONE"), - TWISTING_VINES(ServerVersion.V1_16, "STONE"), - TWISTING_VINES_PLANT(ServerVersion.V1_16, "STONE"), - WARPED_BUTTON(ServerVersion.V1_16, "STONE"), - WARPED_DOOR(ServerVersion.V1_16, "STONE"), - WARPED_FENCE(ServerVersion.V1_16, "STONE"), - WARPED_FENCE_GATE(ServerVersion.V1_16, "STONE"), - WARPED_FUNGUS(ServerVersion.V1_16, "STONE"), - WARPED_FUNGUS_ON_A_STICK(ServerVersion.V1_16, "STONE"), - WARPED_HYPHAE(ServerVersion.V1_16, "STONE"), - WARPED_NYLIUM(ServerVersion.V1_16, "STONE"), - WARPED_PLANKS(ServerVersion.V1_16, "STONE"), - WARPED_PRESSURE_PLATE(ServerVersion.V1_16, "STONE"), - WARPED_ROOTS(ServerVersion.V1_16, "STONE"), - WARPED_SIGN(ServerVersion.V1_16, "STONE"), - WARPED_SLAB(ServerVersion.V1_16, "STONE"), - WARPED_STAIRS(ServerVersion.V1_16, "STONE"), - WARPED_STEM(ServerVersion.V1_16, "STONE"), - WARPED_TRAPDOOR(ServerVersion.V1_16, "STONE"), - WARPED_WALL_SIGN(ServerVersion.V1_16, "STONE"), - WARPED_WART_BLOCK(ServerVersion.V1_16, "STONE"), - WEEPING_VINES(ServerVersion.V1_16, "STONE"), - WEEPING_VINES_PLANT(ServerVersion.V1_16, "STONE"), - ZOGLIN_SPAWN_EGG(ServerVersion.V1_16, "STONE"), - ZOMBIFIED_PIGLIN_SPAWN_EGG(ServerVersion.V1_16, "STONE"), - - /* 1.15 */ - BEE_SPAWN_EGG(ServerVersion.V1_15, "PARROT_SPAWN_EGG", ServerVersion.V1_12, "MONSTER_EGG", (byte) 65), - BEE_NEST(ServerVersion.V1_15, "BIRCH_LOG", "LOG", (byte) 2), - BEEHIVE(ServerVersion.V1_15, "SLIME_BLOCK", ServerVersion.V1_8, "WOOL", (byte) 4), - HONEY_BLOCK(ServerVersion.V1_15, "SLIME_BLOCK", ServerVersion.V1_8, "WOOL", (byte) 4), - HONEY_BOTTLE(ServerVersion.V1_15, "DRAGON_BREATH", ServerVersion.V1_9, "POTION", (byte) 0), - HONEYCOMB(ServerVersion.V1_15, "SUNFLOWER", "DOUBLE_PLANT", (byte) 0), - HONEYCOMB_BLOCK(ServerVersion.V1_15, "SLIME_BLOCK", ServerVersion.V1_8, "WOOL", (byte) 4), - - ACACIA_BOAT(ServerVersion.V1_9, "BOAT"), - ACACIA_BUTTON(ServerVersion.V1_13, "WOOD_BUTTON"), - ACACIA_DOOR(ServerVersion.V1_8, "WOOD_DOOR"), // TODO? ACACIA_DOOR & WOODEN_DOOR are the legacy block variants - ACACIA_FENCE(ServerVersion.V1_8, "FENCE"), - ACACIA_FENCE_GATE(ServerVersion.V1_8, "FENCE_GATE"), - ACACIA_PRESSURE_PLATE(ServerVersion.V1_13, "WOOD_PLATE"), - ACACIA_SIGN(ServerVersion.V1_14, "SIGN", "SIGN"), - ACACIA_TRAPDOOR(ServerVersion.V1_13, "TRAP_DOOR"), - ACACIA_WALL_SIGN(ServerVersion.V1_14, "WALL_SIGN"), - ANDESITE(ServerVersion.V1_8, "STONE"), - ANDESITE_SLAB(ServerVersion.V1_14, "STONE_SLAB", "STEP", (byte) 0), - ANDESITE_STAIRS(ServerVersion.V1_14, "STONE_BRICK_STAIRS", "SMOOTH_STAIRS"), - ANDESITE_WALL(ServerVersion.V1_14, "COBBLESTONE_WALL", "COBBLE_WALL"), - ARMOR_STAND(ServerVersion.V1_8, "STICK"), // idk, we just need *something* - BAMBOO(ServerVersion.V1_14, "SUGAR_CANE", "SUGAR_CANE_BLOCK"), - BAMBOO_SAPLING(ServerVersion.V1_14, "SUGAR_CANE"), - BARREL(ServerVersion.V1_14, "TRAPPED_CHEST"), - BARRIER(ServerVersion.V1_8, "STAINED_GLASS", (byte) 14), // plain glass would make more sense if this were to be a block.. - BEETROOT(ServerVersion.V1_9, "RAW_BEEF"), - BEETROOT_SEEDS(ServerVersion.V1_9, "SEEDS"), - BEETROOT_SOUP(ServerVersion.V1_9, "MUSHROOM_SOUP"), - BEETROOTS(ServerVersion.V1_9, "CROPS"), - BELL(ServerVersion.V1_14, "GOLD_BLOCK", "GOLD_BLOCK"), - BIRCH_BOAT(ServerVersion.V1_9, "BOAT"), - BIRCH_BUTTON(ServerVersion.V1_13, "WOOD_BUTTON"), - BIRCH_DOOR(ServerVersion.V1_8, "WOOD_DOOR"), - BIRCH_FENCE(ServerVersion.V1_8, "FENCE"), - BIRCH_FENCE_GATE(ServerVersion.V1_8, "FENCE_GATE"), - BIRCH_PRESSURE_PLATE(ServerVersion.V1_13, "WOOD_PLATE"), - BIRCH_SIGN(ServerVersion.V1_14, "SIGN", "SIGN"), - BIRCH_STAIRS(ServerVersion.V1_13, "WOOD_STAIRS"), - BIRCH_TRAPDOOR(ServerVersion.V1_13, "TRAP_DOOR"), - BIRCH_WALL_SIGN(ServerVersion.V1_14, "WALL_SIGN"), - BLACK_BANNER(ServerVersion.V1_8, "SIGN"), - BLACK_BED(ServerVersion.V1_12, "BED"), - BLACK_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 15), - BLACK_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 15), - BLACK_DYE(ServerVersion.V1_14, "INK_SAC", "INK_SACK", (byte) 0), - BLACK_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 15), - BLACK_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), - BLACK_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), - BLAST_FURNACE(ServerVersion.V1_14, "FURNACE"), - BLUE_BANNER(ServerVersion.V1_8, "SIGN"), - BLUE_BED(ServerVersion.V1_12, "BED"), - BLUE_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 11), - BLUE_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 11), - BLUE_DYE(ServerVersion.V1_14, "LAPIS_LAZULI", "INK_SACK", (byte) 4), - BLUE_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 11), - BLUE_ICE(ServerVersion.V1_13, "PACKED_ICE"), - BLUE_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), - BLUE_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), - BONE_BLOCK(ServerVersion.V1_10, "QUARTZ_BLOCK"), - BRAIN_CORAL(ServerVersion.V1_13, "WOOL", (byte) 6), - BRAIN_CORAL_BLOCK(ServerVersion.V1_13, "WOOL", (byte) 6), - BRAIN_CORAL_FAN(ServerVersion.V1_13, "WOOL", (byte) 6), - BRAIN_CORAL_WALL_FAN(ServerVersion.V1_13, "WOOL", (byte) 6), - BRICK_WALL(ServerVersion.V1_14, "COBBLESTONE_WALL", "COBBLE_WALL"), - BROWN_BANNER(ServerVersion.V1_8, "SIGN"), - BROWN_BED(ServerVersion.V1_12, "BED"), - BROWN_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 12), - BROWN_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 12), - BROWN_DYE(ServerVersion.V1_14, "COCOA_BEANS", "INK_SACK", (byte) 3), - BROWN_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 12), - BROWN_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), - BROWN_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), - BUBBLE_COLUMN(ServerVersion.V1_13, "WATER"), - BUBBLE_CORAL(ServerVersion.V1_13, "WOOL", (byte) 2), - BUBBLE_CORAL_BLOCK(ServerVersion.V1_13, "WOOL", (byte) 2), - BUBBLE_CORAL_FAN(ServerVersion.V1_13, "WOOL", (byte) 2), - BUBBLE_CORAL_WALL_FAN(ServerVersion.V1_13, "WOOL", (byte) 2), - CAMPFIRE(ServerVersion.V1_14, "FURNACE", "BURNING_FURNACE"), - CARTOGRAPHY_TABLE(ServerVersion.V1_14, "BOOKSHELF"), - CAT_SPAWN_EGG(ServerVersion.V1_14, "OCELOT_SPAWN_EGG", "MONSTER_EGG", (byte) 98), - CAVE_AIR(ServerVersion.V1_13, "AIR"), - CHAIN_COMMAND_BLOCK(ServerVersion.V1_9, "COMMAND"), - CHISELED_RED_SANDSTONE(ServerVersion.V1_8, "SANDSTONE", (byte) 1), - CHORUS_FLOWER(ServerVersion.V1_9, "WOOL", (byte) 2), - CHORUS_FRUIT(ServerVersion.V1_9, "APPLE"), - CHORUS_PLANT(ServerVersion.V1_9, "WOOL", (byte) 10), - COARSE_DIRT(ServerVersion.V1_8, "DIRT"), - COD_BUCKET(ServerVersion.V1_13, "WATER_BUCKET"), - COD_SPAWN_EGG(ServerVersion.V1_13, "MONSTER_EGG", (byte) 60), - COMPOSTER(ServerVersion.V1_14, "FLOWER_POT", "FLOWER_POT_ITEM"), - CONDUIT(ServerVersion.V1_13, "MELON"), - COOKED_MUTTON(ServerVersion.V1_8, "COOKED_BEEF"), - COOKED_RABBIT(ServerVersion.V1_8, "COOKED_BEEF"), - CORNFLOWER(ServerVersion.V1_14, "BLUE_ORCHID", "RED_ROSE", (byte) 1), - CREEPER_BANNER_PATTERN(ServerVersion.V1_14, "PAPER"), - CROSSBOW(ServerVersion.V1_14, "BOW"), - CUT_RED_SANDSTONE(ServerVersion.V1_13, "RED_SANDSTONE", (byte) 2, ServerVersion.V1_8, "SANDSTONE", (byte) 0), - CUT_RED_SANDSTONE_SLAB(ServerVersion.V1_14, "STONE_SLAB", "STEP", (byte) 0), - CUT_SANDSTONE(ServerVersion.V1_13, "SANDSTONE", (byte) 2), - CUT_SANDSTONE_SLAB(ServerVersion.V1_14, "STONE_SLAB", "STEP", (byte) 0), - CYAN_BANNER(ServerVersion.V1_8, "SIGN"), - CYAN_BED(ServerVersion.V1_12, "BED"), - CYAN_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 9), - CYAN_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 9), - CYAN_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 9), - CYAN_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), - CYAN_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), - DARK_OAK_BOAT(ServerVersion.V1_9, "BOAT"), - DARK_OAK_BUTTON(ServerVersion.V1_13, "WOOD_BUTTON"), - DARK_OAK_DOOR(ServerVersion.V1_8, "WOOD_DOOR"), - DARK_OAK_FENCE(ServerVersion.V1_8, "FENCE"), - DARK_OAK_FENCE_GATE(ServerVersion.V1_8, "FENCE_GATE"), - DARK_OAK_PRESSURE_PLATE(ServerVersion.V1_13, "WOOD_PLATE"), - DARK_OAK_SIGN(ServerVersion.V1_14, "SIGN"), - DARK_OAK_TRAPDOOR(ServerVersion.V1_13, "TRAP_DOOR"), - DARK_OAK_WALL_SIGN(ServerVersion.V1_14, "WALL_SIGN"), - DARK_PRISMARINE(ServerVersion.V1_8, "WOOL", (byte) 7), - DARK_PRISMARINE_SLAB(ServerVersion.V1_13, "STEP", (byte) 0), - DARK_PRISMARINE_STAIRS(ServerVersion.V1_13, "NETHER_BRICK_STAIRS"), - DEAD_BRAIN_CORAL(ServerVersion.V1_13, "COBBLESTONE"), - DEAD_BRAIN_CORAL_BLOCK(ServerVersion.V1_13, "COBBLESTONE"), - DEAD_BRAIN_CORAL_FAN(ServerVersion.V1_13, "COBBLESTONE"), - DEAD_BRAIN_CORAL_WALL_FAN(ServerVersion.V1_13, "COBBLESTONE"), - DEAD_BUBBLE_CORAL(ServerVersion.V1_13, "COBBLESTONE"), - DEAD_BUBBLE_CORAL_BLOCK(ServerVersion.V1_13, "COBBLESTONE"), - DEAD_BUBBLE_CORAL_FAN(ServerVersion.V1_13, "COBBLESTONE"), - DEAD_BUBBLE_CORAL_WALL_FAN(ServerVersion.V1_13, "COBBLESTONE"), - DEAD_FIRE_CORAL(ServerVersion.V1_13, "COBBLESTONE"), - DEAD_FIRE_CORAL_BLOCK(ServerVersion.V1_13, "COBBLESTONE"), - DEAD_FIRE_CORAL_FAN(ServerVersion.V1_13, "COBBLESTONE"), - DEAD_FIRE_CORAL_WALL_FAN(ServerVersion.V1_13, "COBBLESTONE"), - DEAD_HORN_CORAL(ServerVersion.V1_13, "COBBLESTONE"), - DEAD_HORN_CORAL_BLOCK(ServerVersion.V1_13, "COBBLESTONE"), - DEAD_HORN_CORAL_FAN(ServerVersion.V1_13, "COBBLESTONE"), - DEAD_HORN_CORAL_WALL_FAN(ServerVersion.V1_13, "COBBLESTONE"), - DEAD_TUBE_CORAL(ServerVersion.V1_13, "COBBLESTONE"), - DEAD_TUBE_CORAL_BLOCK(ServerVersion.V1_13, "COBBLESTONE"), - DEAD_TUBE_CORAL_FAN(ServerVersion.V1_13, "COBBLESTONE"), // these could also be a dead_bush ? - DEAD_TUBE_CORAL_WALL_FAN(ServerVersion.V1_13, "COBBLESTONE"), - DEBUG_STICK(ServerVersion.V1_13, "STICK"), - DIORITE(ServerVersion.V1_8, "STONE"), - DIORITE_SLAB(ServerVersion.V1_14, "STONE_SLAB", "STEP", (byte) 0), - DIORITE_STAIRS(ServerVersion.V1_14, "STONE_BRICK_STAIRS", "SMOOTH_STAIRS"), - DIORITE_WALL(ServerVersion.V1_14, "COBBLESTONE_WALL", "COBBLE_WALL"), - DOLPHIN_SPAWN_EGG(ServerVersion.V1_13, "MONSTER_EGG", (byte) 0), - DONKEY_SPAWN_EGG(ServerVersion.V1_11, "MONSTER_EGG", (byte) 100), - DRAGON_BREATH(ServerVersion.V1_9, "POTION", (byte) 0), // or maybe glowstone.. - DRAGON_HEAD(ServerVersion.V1_9, "SKULL_ITEM", (byte) 4), - DRAGON_WALL_HEAD(ServerVersion.V1_9, "SKULL", (byte) 4), - DRIED_KELP(ServerVersion.V1_13, "POTATO_ITEM"), - DRIED_KELP_BLOCK(ServerVersion.V1_13, "HAY_BLOCK"), - DROWNED_SPAWN_EGG(ServerVersion.V1_13, "MONSTER_EGG", (byte) 54), - ELDER_GUARDIAN_SPAWN_EGG(ServerVersion.V1_11, "MONSTER_EGG", (byte) 51), - ELYTRA(ServerVersion.V1_9, "IRON_CHESTPLATE"), - END_CRYSTAL(ServerVersion.V1_9, "STAINED_GLASS", (byte) 0), - END_GATEWAY(ServerVersion.V1_9, "BEACON"), - END_PORTAL(ServerVersion.V1_9, "ENDER_PORTAL"), - END_ROD(ServerVersion.V1_9, "STAINED_GLASS_PANE", (byte) 0), - END_STONE_BRICK_SLAB(ServerVersion.V1_14, "STONE_SLAB", "STEP", (byte) 0), - END_STONE_BRICK_STAIRS(ServerVersion.V1_14, "SANDSTONE_STAIRS"), - END_STONE_BRICK_WALL(ServerVersion.V1_14, "COBBLESTONE_WALL", "COBBLE_WALL"), - END_STONE_BRICKS(ServerVersion.V1_9, "SANDSTONE", (byte) 2), - ENDERMITE_SPAWN_EGG(ServerVersion.V1_8, "MONSTER_EGG", (byte) 60), - EVOKER_SPAWN_EGG(ServerVersion.V1_11, "MONSTER_EGG", (byte) 51), - FILLED_MAP(ServerVersion.V1_13, "EMPTY_MAP"), - FIRE_CORAL(ServerVersion.V1_13, "WOOL", (byte) 14), - FIRE_CORAL_BLOCK(ServerVersion.V1_13, "WOOL", (byte) 14), - FIRE_CORAL_FAN(ServerVersion.V1_13, "WOOL", (byte) 14), - FIRE_CORAL_WALL_FAN(ServerVersion.V1_13, "WOOL", (byte) 14), - FLETCHING_TABLE(ServerVersion.V1_14, "CRAFTING_TABLE", "WORKBENCH"), - FLOWER_BANNER_PATTERN(ServerVersion.V1_14, "PAPER"), - FOX_SPAWN_EGG(ServerVersion.V1_14, "OCELOT_SPAWN_EGG", "MONSTER_EGG", (byte) 98), - FROSTED_ICE(ServerVersion.V1_13, "ICE"), - GLOBE_BANNER_PATTERN(ServerVersion.V1_14, "PAPER"), - GRANITE(ServerVersion.V1_8, "STONE"), - GRANITE_SLAB(ServerVersion.V1_14, "STONE_SLAB", "STEP", (byte) 0), - GRANITE_STAIRS(ServerVersion.V1_14, "STONE_BRICK_STAIRS", "SMOOTH_STAIRS"), - GRANITE_WALL(ServerVersion.V1_14, "COBBLESTONE_WALL", "COBBLE_WALL"), - GRASS_PATH(ServerVersion.V1_9, "DIRT", (byte) 1, ServerVersion.V1_8, "DIRT"), - GRAY_BANNER(ServerVersion.V1_8, "SIGN"), - GRAY_BED(ServerVersion.V1_12, "BED"), - GRAY_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 7), - GRAY_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 7), - GRAY_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 7), - GRAY_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), - GRAY_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), - GREEN_BANNER(ServerVersion.V1_8, "SIGN"), - GREEN_BED(ServerVersion.V1_12, "BED"), - GREEN_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 13), - GREEN_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 13), - GREEN_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 13), - GREEN_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), - GREEN_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), - GRINDSTONE(ServerVersion.V1_14, "ANVIL"), - GUARDIAN_SPAWN_EGG(ServerVersion.V1_8, "MONSTER_EGG", (byte) 51), - HEART_OF_THE_SEA(ServerVersion.V1_13, "DIAMOND"), - HORN_CORAL(ServerVersion.V1_13, "WOOL", (byte) 4), - HORN_CORAL_BLOCK(ServerVersion.V1_13, "WOOL", (byte) 4), - HORN_CORAL_FAN(ServerVersion.V1_13, "WOOL", (byte) 4), - HORN_CORAL_WALL_FAN(ServerVersion.V1_13, "WOOL", (byte) 4), - HUSK_SPAWN_EGG(ServerVersion.V1_11, "MONSTER_EGG", (byte) 54), - IRON_NUGGET(ServerVersion.V1_11, "IRON_INGOT"), - IRON_TRAPDOOR(ServerVersion.V1_8, "TRAP_DOOR"), - JIGSAW(ServerVersion.V1_14, "ANVIL"), - JUNGLE_BOAT(ServerVersion.V1_9, "BOAT"), - JUNGLE_BUTTON(ServerVersion.V1_13, "WOOD_BUTTON"), - JUNGLE_DOOR(ServerVersion.V1_8, "WOOD_DOOR"), - JUNGLE_FENCE(ServerVersion.V1_8, "FENCE"), - JUNGLE_FENCE_GATE(ServerVersion.V1_8, "FENCE_GATE"), - JUNGLE_PRESSURE_PLATE(ServerVersion.V1_13, "WOOD_PLATE"), - JUNGLE_SIGN(ServerVersion.V1_14, "SIGN"), - JUNGLE_TRAPDOOR(ServerVersion.V1_13, "TRAP_DOOR"), - JUNGLE_WALL_SIGN(ServerVersion.V1_14, "WALL_SIGN"), - KELP(ServerVersion.V1_13, "POTATO_ITEM"), - KELP_PLANT(ServerVersion.V1_13, "WATER"), // idk. - KNOWLEDGE_BOOK(ServerVersion.V1_12, "BOOK"), - LANTERN(ServerVersion.V1_14, "GLOWSTONE"), - LEATHER_HORSE_ARMOR(ServerVersion.V1_14, "IRON_BARDING"), - LECTERN(ServerVersion.V1_14, "BOOKSHELF"), - LIGHT_BLUE_BANNER(ServerVersion.V1_8, "SIGN"), - LIGHT_BLUE_BED(ServerVersion.V1_12, "BED"), - LIGHT_BLUE_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 3), - LIGHT_BLUE_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 3), - LIGHT_BLUE_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 3), - LIGHT_BLUE_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), - LIGHT_BLUE_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), - LIGHT_GRAY_BANNER(ServerVersion.V1_8, "SIGN"), - LIGHT_GRAY_BED(ServerVersion.V1_12, "BED"), - LIGHT_GRAY_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 8), - LIGHT_GRAY_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 8), - LIGHT_GRAY_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 8), - LIGHT_GRAY_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), - LIGHT_GRAY_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), - LILY_OF_THE_VALLEY(ServerVersion.V1_14, "AZURE_BLUET", "RED_ROSE", (byte) 3), - LIME_BANNER(ServerVersion.V1_8, "SIGN"), - LIME_BED(ServerVersion.V1_12, "BED"), - LIME_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 5), - LIME_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 5), - LIME_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 5), - LIME_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), - LIME_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), - LINGERING_POTION(ServerVersion.V1_9, "POTION", (byte) 0), - LLAMA_SPAWN_EGG(ServerVersion.V1_11, "MONSTER_EGG", (byte) 0), - LOOM(ServerVersion.V1_14, "CRAFTING_TABLE", "WORKBENCH"), - MAGENTA_BANNER(ServerVersion.V1_8, "SIGN"), - MAGENTA_BED(ServerVersion.V1_12, "BED"), - MAGENTA_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 2), - MAGENTA_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 2), - MAGENTA_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 2), - MAGENTA_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), - MAGENTA_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), - MAGMA_BLOCK(ServerVersion.V1_10, "NETHER_BRICK"), - MOJANG_BANNER_PATTERN(ServerVersion.V1_14, "PAPER"), - MOSSY_COBBLESTONE_SLAB(ServerVersion.V1_14, "COBBLESTONE_SLAB", "STEP", (byte) 3), - MOSSY_COBBLESTONE_STAIRS(ServerVersion.V1_14, "COBBLESTONE_STAIRS"), - MOSSY_COBBLESTONE_WALL(ServerVersion.V1_14, "COBBLESTONE_WALL", "COBBLE_WALL"), - MOSSY_STONE_BRICK_SLAB(ServerVersion.V1_14, "BRICK_SLAB", "STEP", (byte) 4), - MOSSY_STONE_BRICK_STAIRS(ServerVersion.V1_14, "STONE_BRICK_STAIRS", "SMOOTH_STAIRS"), - MOSSY_STONE_BRICK_WALL(ServerVersion.V1_14, "COBBLESTONE_WALL", "COBBLE_WALL"), - MULE_SPAWN_EGG(ServerVersion.V1_11, "MONSTER_EGG", (byte) 100), - MUTTON(ServerVersion.V1_8, "RAW_BEEF"), - NAUTILUS_SHELL(ServerVersion.V1_13, "SNOW_BALL"), - NETHER_BRICK_FENCE(ServerVersion.V1_13, "FENCE"), - NETHER_BRICK_WALL(ServerVersion.V1_14, "COBBLESTONE_WALL", "COBBLE_WALL"), - NETHER_WART_BLOCK(ServerVersion.V1_10, "NETHERRACK"), - OAK_BOAT(ServerVersion.V1_9, "BOAT"), - OBSERVER(ServerVersion.V1_11, "DISPENSER"), - ORANGE_BANNER(ServerVersion.V1_8, "SIGN"), - ORANGE_BED(ServerVersion.V1_12, "BED"), - ORANGE_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 1), - ORANGE_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 1), - ORANGE_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 1), - ORANGE_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), - ORANGE_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), - PANDA_SPAWN_EGG(ServerVersion.V1_14, "COW_SPAWN_EGG", "MONSTER_EGG", (byte) 92), - PARROT_SPAWN_EGG(ServerVersion.V1_12, "MONSTER_EGG", (byte) 65), - PHANTOM_MEMBRANE(ServerVersion.V1_13, "FEATHER"), - PHANTOM_SPAWN_EGG(ServerVersion.V1_13, "MONSTER_EGG", (byte) 65), - PILLAGER_SPAWN_EGG(ServerVersion.V1_14, "VILLAGER_SPAWN_EGG", "MONSTER_EGG", (byte) 120), - PINK_BANNER(ServerVersion.V1_8, "SIGN"), - PINK_BED(ServerVersion.V1_12, "BED"), - PINK_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 6), - PINK_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 6), - PINK_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 6), - PINK_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), - PINK_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), - PODZOL(ServerVersion.V1_8, "DIRT"), - POLAR_BEAR_SPAWN_EGG(ServerVersion.V1_10, "MONSTER_EGG", (byte) 0), - POLISHED_ANDESITE(ServerVersion.V1_8, "STONE"), - POLISHED_ANDESITE_SLAB(ServerVersion.V1_14, "STONE_SLAB", "STEP", (byte) 0), - POLISHED_ANDESITE_STAIRS(ServerVersion.V1_14, "STONE_BRICK_STAIRS", "SMOOTH_STAIRS"), - POLISHED_DIORITE(ServerVersion.V1_8, "STONE"), - POLISHED_DIORITE_SLAB(ServerVersion.V1_14, "STONE_SLAB", "STEP", (byte) 0), - POLISHED_DIORITE_STAIRS(ServerVersion.V1_14, "STONE_BRICK_STAIRS", "SMOOTH_STAIRS"), - POLISHED_GRANITE(ServerVersion.V1_8, "STONE"), - POLISHED_GRANITE_SLAB(ServerVersion.V1_14, "STONE_SLAB", "STEP", (byte) 0), - POLISHED_GRANITE_STAIRS(ServerVersion.V1_14, "STONE_BRICK_STAIRS", "SMOOTH_STAIRS"), - POPPED_CHORUS_FRUIT(ServerVersion.V1_9, "GOLDEN_APPLE"), - POTTED_ACACIA_SAPLING(ServerVersion.V1_13, "FLOWER_POT_ITEM"), - POTTED_ALLIUM(ServerVersion.V1_13, "FLOWER_POT_ITEM"), - POTTED_AZURE_BLUET(ServerVersion.V1_13, "FLOWER_POT_ITEM"), - POTTED_BAMBOO(ServerVersion.V1_14, "FLOWER_POT", "FLOWER_POT_ITEM"), - POTTED_BIRCH_SAPLING(ServerVersion.V1_13, "FLOWER_POT_ITEM"), - POTTED_BLUE_ORCHID(ServerVersion.V1_13, "FLOWER_POT_ITEM"), - POTTED_BROWN_MUSHROOM(ServerVersion.V1_13, "FLOWER_POT_ITEM"), - POTTED_CACTUS(ServerVersion.V1_13, "FLOWER_POT_ITEM"), - POTTED_CORNFLOWER(ServerVersion.V1_14, "FLOWER_POT", "FLOWER_POT_ITEM"), - POTTED_DANDELION(ServerVersion.V1_13, "FLOWER_POT_ITEM"), - POTTED_DARK_OAK_SAPLING(ServerVersion.V1_13, "FLOWER_POT_ITEM"), - POTTED_DEAD_BUSH(ServerVersion.V1_13, "FLOWER_POT_ITEM"), - POTTED_FERN(ServerVersion.V1_13, "FLOWER_POT_ITEM"), - POTTED_JUNGLE_SAPLING(ServerVersion.V1_13, "FLOWER_POT_ITEM"), - POTTED_LILY_OF_THE_VALLEY(ServerVersion.V1_14, "FLOWER_POT", "FLOWER_POT_ITEM"), - POTTED_OAK_SAPLING(ServerVersion.V1_13, "FLOWER_POT_ITEM"), - POTTED_ORANGE_TULIP(ServerVersion.V1_13, "FLOWER_POT_ITEM"), - POTTED_OXEYE_DAISY(ServerVersion.V1_13, "FLOWER_POT_ITEM"), - POTTED_PINK_TULIP(ServerVersion.V1_13, "FLOWER_POT_ITEM"), - POTTED_POPPY(ServerVersion.V1_13, "FLOWER_POT_ITEM"), - POTTED_RED_MUSHROOM(ServerVersion.V1_13, "FLOWER_POT_ITEM"), - POTTED_RED_TULIP(ServerVersion.V1_13, "FLOWER_POT_ITEM"), - POTTED_SPRUCE_SAPLING(ServerVersion.V1_13, "FLOWER_POT_ITEM"), - POTTED_WHITE_TULIP(ServerVersion.V1_13, "FLOWER_POT_ITEM"), - POTTED_WITHER_ROSE(ServerVersion.V1_14, "FLOWER_POT", "FLOWER_POT_ITEM"), - PRISMARINE(ServerVersion.V1_8, "WOOL", (byte) 9), - PRISMARINE_BRICK_SLAB(ServerVersion.V1_14, "STONE_SLAB", "STEP", (byte) 0), - PRISMARINE_BRICK_STAIRS(ServerVersion.V1_13, "SMOOTH_STAIRS"), - PRISMARINE_BRICKS(ServerVersion.V1_8, "WOOL", (byte) 9), - PRISMARINE_CRYSTALS(ServerVersion.V1_8, "CLAY_BALL"), - PRISMARINE_SHARD(ServerVersion.V1_8, "FLINT"), - PRISMARINE_SLAB(ServerVersion.V1_13, "STEP", (byte) 0), - PRISMARINE_STAIRS(ServerVersion.V1_13, "COBBLESTONE_STAIRS"), - PRISMARINE_WALL(ServerVersion.V1_14, "COBBLESTONE_WALL", "COBBLE_WALL"), - PUFFERFISH_BUCKET(ServerVersion.V1_13, "WATER_BUCKET"), - PUFFERFISH_SPAWN_EGG(ServerVersion.V1_13, "MONSTER_EGG", (byte) 60), - PURPLE_BANNER(ServerVersion.V1_8, "SIGN"), - PURPLE_BED(ServerVersion.V1_12, "BED"), - PURPLE_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 10), - PURPLE_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 10), - PURPLE_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 10), - PURPLE_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), - PURPLE_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), - PURPUR_BLOCK(ServerVersion.V1_9, "WOOL", (byte) 2), - PURPUR_PILLAR(ServerVersion.V1_9, "WOOL", (byte) 2), - PURPUR_SLAB(ServerVersion.V1_9, "STEP", (byte) 0), - PURPUR_STAIRS(ServerVersion.V1_9, "BRICK_STAIRS"), - RABBIT(ServerVersion.V1_8, "RAW_BEEF"), - RABBIT_FOOT(ServerVersion.V1_8, "ROTTEN_FLESH"), - RABBIT_HIDE(ServerVersion.V1_8, "ROTTEN_FLESH"), - RABBIT_SPAWN_EGG(ServerVersion.V1_8, "MONSTER_EGG", (byte) 0), - RABBIT_STEW(ServerVersion.V1_8, "MUSHROOM_SOUP"), - RAVAGER_SPAWN_EGG(ServerVersion.V1_14, "COW_SPAWN_EGG", "MONSTER_EGG", (byte) 92), - RED_BANNER(ServerVersion.V1_8, "SIGN"), - RED_BED(ServerVersion.V1_12, "BED"), - RED_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 14), - RED_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 14), - RED_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 14), - RED_NETHER_BRICK_SLAB(ServerVersion.V1_14, "STONE_SLAB", "STEP", (byte) 0), - RED_NETHER_BRICK_STAIRS(ServerVersion.V1_14, "NETHER_BRICK_STAIRS"), - RED_NETHER_BRICK_WALL(ServerVersion.V1_14, "COBBLESTONE_WALL", "COBBLE_WALL"), - RED_NETHER_BRICKS(ServerVersion.V1_10, "NETHER_BRICK"), - RED_SANDSTONE(ServerVersion.V1_8, "SANDSTONE", (byte) 0), - RED_SANDSTONE_SLAB(ServerVersion.V1_8, "STEP", (byte) 0), - RED_SANDSTONE_STAIRS(ServerVersion.V1_8, "SANDSTONE_STAIRS"), - RED_SANDSTONE_WALL(ServerVersion.V1_14, "COBBLESTONE_WALL", "COBBLE_WALL"), - RED_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), - RED_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), - REDSTONE_WALL_TORCH(ServerVersion.V1_13, "REDSTONE_TORCH_ON"), - REPEATING_COMMAND_BLOCK(ServerVersion.V1_9, "COMMAND"), - SALMON_BUCKET(ServerVersion.V1_13, "WATER_BUCKET"), - SALMON_SPAWN_EGG(ServerVersion.V1_13, "MONSTER_EGG", (byte) 60), - SANDSTONE_WALL(ServerVersion.V1_14, "COBBLESTONE_WALL", "COBBLE_WALL"), - SCAFFOLDING(ServerVersion.V1_14, "LADDER"), - SCUTE(ServerVersion.V1_13, "SLIME_BALL"), - SEA_LANTERN(ServerVersion.V1_8, "GLOWSTONE"), - SEA_PICKLE(ServerVersion.V1_13, "CACTUS"), - SEAGRASS(ServerVersion.V1_13, "LONG_GRASS", (byte) 1), - SHIELD(ServerVersion.V1_9, "BANNER", (byte) 3, ServerVersion.V1_8, "WOOD_DOOR"), - SHULKER_BOX(ServerVersion.V1_13, "ENDER_CHEST"), - SHULKER_SHELL(ServerVersion.V1_11, "SUGAR"), - SHULKER_SPAWN_EGG(ServerVersion.V1_9, "MONSTER_EGG", (byte) 0), - SKELETON_HORSE_SPAWN_EGG(ServerVersion.V1_11, "MONSTER_EGG", (byte) 0), - SKULL_BANNER_PATTERN(ServerVersion.V1_14, "PAPER"), - SLIME_BLOCK(ServerVersion.V1_8, "WOOL", (byte) 5), - SMITHING_TABLE(ServerVersion.V1_14, "CRAFTING_TABLE", "WORKBENCH"), - SMOKER(ServerVersion.V1_14, "FURNACE"), - SMOOTH_QUARTZ(ServerVersion.V1_13, "QUARTZ_BLOCK", (byte) 0), - SMOOTH_QUARTZ_SLAB(ServerVersion.V1_14, "QUARTZ_SLAB", "STEP", (byte) 7), - SMOOTH_QUARTZ_STAIRS(ServerVersion.V1_14, "QUARTZ_STAIRS"), - SMOOTH_RED_SANDSTONE(ServerVersion.V1_13, "RED_SANDSTONE", (byte) 0, ServerVersion.V1_8, "SANDSTONE", (byte) 0), - SMOOTH_RED_SANDSTONE_SLAB(ServerVersion.V1_14, "SANDSTONE_SLAB", "STEP", (byte) 1), - SMOOTH_RED_SANDSTONE_STAIRS(ServerVersion.V1_14, "RED_SANDSTONE_STAIRS", ServerVersion.V1_8, "SANDSTONE_STAIRS"), - SMOOTH_SANDSTONE_SLAB(ServerVersion.V1_14, "SANDSTONE_SLAB", "STEP", (byte) 1), - SMOOTH_SANDSTONE_STAIRS(ServerVersion.V1_14, "SANDSTONE_STAIRS"), - SMOOTH_STONE(ServerVersion.V1_13, "STONE"), // DOUBLE_STEP is a closer texture match - SMOOTH_STONE_SLAB(ServerVersion.V1_14, "STONE_SLAB", "STEP", (byte) 0), - SPECTRAL_ARROW(ServerVersion.V1_9, "ARROW"), - SPRUCE_BOAT(ServerVersion.V1_9, "BOAT"), - SPRUCE_BUTTON(ServerVersion.V1_13, "WOOD_BUTTON"), - SPRUCE_DOOR(ServerVersion.V1_8, "WOOD_DOOR"), - SPRUCE_FENCE(ServerVersion.V1_8, "FENCE"), - SPRUCE_FENCE_GATE(ServerVersion.V1_8, "FENCE_GATE"), - SPRUCE_PRESSURE_PLATE(ServerVersion.V1_13, "WOOD_PLATE"), - SPRUCE_SIGN(ServerVersion.V1_14, "SIGN"), - SPRUCE_TRAPDOOR(ServerVersion.V1_13, "TRAP_DOOR"), - SPRUCE_WALL_SIGN(ServerVersion.V1_14, "WALL_SIGN"), - //STONE(ServerVersion.V1_8, "STONE"), // funny how that happened, heh. Non-data to data to non-data again - STONE_BRICK_WALL(ServerVersion.V1_14, "COBBLESTONE_WALL", "COBBLE_WALL"), - STONE_SLAB(ServerVersion.V1_13, "STEP", (byte) 0), - STONE_STAIRS(ServerVersion.V1_14, "STONE_BRICK_STAIRS", "SMOOTH_STAIRS"), - STONECUTTER(ServerVersion.V1_14, "ANVIL"), - STRAY_SPAWN_EGG(ServerVersion.V1_11, "MONSTER_EGG", (byte) 0), - STRIPPED_ACACIA_LOG(ServerVersion.V1_13, "LOG_2", (byte) 0), - STRIPPED_ACACIA_WOOD(ServerVersion.V1_13, "LOG_2", (byte) 12), - STRIPPED_BIRCH_LOG(ServerVersion.V1_13, "LOG", (byte) 2), - STRIPPED_BIRCH_WOOD(ServerVersion.V1_13, "LOG", (byte) 14), - STRIPPED_DARK_OAK_LOG(ServerVersion.V1_13, "LOG_2", (byte) 1), - STRIPPED_DARK_OAK_WOOD(ServerVersion.V1_13, "LOG_2", (byte) 13), - STRIPPED_JUNGLE_LOG(ServerVersion.V1_13, "LOG", (byte) 3), - STRIPPED_JUNGLE_WOOD(ServerVersion.V1_13, "LOG", (byte) 15), - STRIPPED_OAK_LOG(ServerVersion.V1_13, "LOG", (byte) 0), - STRIPPED_OAK_WOOD(ServerVersion.V1_13, "LOG", (byte) 12), - STRIPPED_SPRUCE_LOG(ServerVersion.V1_13, "LOG", (byte) 1), - STRIPPED_SPRUCE_WOOD(ServerVersion.V1_13, "LOG", (byte) 13), - STRUCTURE_BLOCK(ServerVersion.V1_9, "COMMAND"), - STRUCTURE_VOID(ServerVersion.V1_10, "BARRIER", ServerVersion.V1_8, "STAINED_GLASS", (byte) 14), // Block would be air, but these make more sense as an item - SUSPICIOUS_STEW(ServerVersion.V1_14, "MUSHROOM_SOUP"), - SWEET_BERRIES(ServerVersion.V1_14, "POTATO", "POTATO_ITEM"), - SWEET_BERRY_BUSH(ServerVersion.V1_14, "OAK_LEAVES", "LEAVES", (byte) 3), - TALL_SEAGRASS(ServerVersion.V1_13, "LONG_GRASS", (byte) 1), - TIPPED_ARROW(ServerVersion.V1_9, "ARROW"), - TOTEM_OF_UNDYING(ServerVersion.V1_11, "CHAINMAIL_CHESTPLATE"), - TRADER_LLAMA_SPAWN_EGG(ServerVersion.V1_14, "LLAMA_SPAWN_EGG", "MONSTER_EGG", (byte) 103), // todo? should we change the item here? llamas are v1.11+ - TRIDENT(ServerVersion.V1_13, "ARROW"), - TROPICAL_FISH_BUCKET(ServerVersion.V1_13, "WATER_BUCKET"), - TROPICAL_FISH_SPAWN_EGG(ServerVersion.V1_13, "MONSTER_EGG", (byte) 60), - TUBE_CORAL(ServerVersion.V1_13, "WOOL", (byte) 11), - TUBE_CORAL_BLOCK(ServerVersion.V1_13, "WOOL", (byte) 11), - TUBE_CORAL_FAN(ServerVersion.V1_13, "WOOL", (byte) 11), - TUBE_CORAL_WALL_FAN(ServerVersion.V1_13, "WOOL", (byte) 11), - TURTLE_EGG(ServerVersion.V1_13, "DRAGON_EGG"), - TURTLE_HELMET(ServerVersion.V1_13, "LEATHER_HELMET"), // would be cool to color it green.. - TURTLE_SPAWN_EGG(ServerVersion.V1_13, "MONSTER_EGG", (byte) 60), - VEX_SPAWN_EGG(ServerVersion.V1_11, "MONSTER_EGG", (byte) 0), - VINDICATOR_SPAWN_EGG(ServerVersion.V1_11, "MONSTER_EGG", (byte) 0), - VOID_AIR(ServerVersion.V1_13, "AIR"), - WALL_TORCH(ServerVersion.V1_13, "TORCH"), - WANDERING_TRADER_SPAWN_EGG(ServerVersion.V1_14, "VILLAGER_SPAWN_EGG", "MONSTER_EGG", (byte) 120), - WHITE_BANNER(ServerVersion.V1_8, "SIGN"), - WHITE_BED(ServerVersion.V1_12, "BED"), - WHITE_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 0), - WHITE_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 0), - WHITE_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 0), - WHITE_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), - WHITE_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), - WITHER_ROSE(ServerVersion.V1_14, "POPPY", "RED_ROSE", (byte) 0), - WITHER_SKELETON_SPAWN_EGG(ServerVersion.V1_11, "MONSTER_EGG", (byte) 0), - YELLOW_BANNER(ServerVersion.V1_8, "SIGN"), - YELLOW_BED(ServerVersion.V1_12, "BED"), - YELLOW_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 4), - YELLOW_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 4), - YELLOW_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 4), - YELLOW_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), - YELLOW_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), - ZOMBIE_HORSE_SPAWN_EGG(ServerVersion.V1_11, "MONSTER_EGG", (byte) 0), - ZOMBIE_VILLAGER_SPAWN_EGG(ServerVersion.V1_11, "MONSTER_EGG", (byte) 0), - - ; - - final ServerVersion versionLessThan; - final String modernMaterial; - final String legacyMaterial; - final Byte legacyData; - final ServerVersion legacyMinimumVersion; - final String compatibleMaterial; - final Byte compatibleData; - final Material material; - final Byte data; - - // map to speed up name->material lookups - private static final Map lookupMap = new HashMap(); - - static { - for (LegacyMaterialAnalouge m : values()) { - lookupMap.put(m.name(), m); - } - } - - public static LegacyMaterialAnalouge lookupAnalouge(String material) { - return lookupMap.get(material); - } - - private LegacyMaterialAnalouge(ServerVersion versionLessThan, String legacyMaterial, byte legacyData) { - this(versionLessThan, null, legacyMaterial, legacyData, null, null, null); - } - - private LegacyMaterialAnalouge(ServerVersion versionLessThan, String legacyMaterial) { - this(versionLessThan, null, legacyMaterial, null, null, null, null); - } - - private LegacyMaterialAnalouge(ServerVersion versionLessThan, String modernAnalouge, String legacyMaterial) { - this(versionLessThan, modernAnalouge, legacyMaterial, null, null, null, null); - } - - private LegacyMaterialAnalouge(ServerVersion versionLessThan, String modernAnalouge, String legacyMaterial, byte legacyData) { - this(versionLessThan, modernAnalouge, legacyMaterial, legacyData, null, null, null); - } - - private LegacyMaterialAnalouge(ServerVersion versionLessThan, String legacyMaterial, byte legacyData, ServerVersion legacyMinimum, String compatMaterial, byte compatData) { - this(versionLessThan, null, legacyMaterial, legacyData, legacyMinimum, compatMaterial, compatData); - } - - private LegacyMaterialAnalouge(ServerVersion versionLessThan, String legacyMaterial, ServerVersion legacyMinimum, String compatMaterial, byte compatData) { - this(versionLessThan, null, legacyMaterial, null, legacyMinimum, compatMaterial, compatData); - } - - private LegacyMaterialAnalouge(ServerVersion versionLessThan, String legacyMaterial, byte legacyData, ServerVersion legacyMinimum, String compatMaterial) { - this(versionLessThan, null, legacyMaterial, legacyData, legacyMinimum, compatMaterial, null); - } - - private LegacyMaterialAnalouge(ServerVersion versionLessThan, String legacyMaterial, ServerVersion legacyMinimum, String compatMaterial) { - this(versionLessThan, null, legacyMaterial, null, legacyMinimum, compatMaterial, null); - } - - /** - * @param versionLessThan AKA, what server version was this material added to minecraft? - * @param modernAnalouge post-1.13 material name, if applicable - * @param legacyMaterial pre-1.13 material name - * @param legacyData data for defining specific legacy items - */ - private LegacyMaterialAnalouge(ServerVersion versionLessThan, String modernAnalouge, String legacyMaterial, Byte legacyData, ServerVersion legacyMinimum, String compatMaterial, Byte compatData) { - this.versionLessThan = versionLessThan; - this.modernMaterial = modernAnalouge; - this.legacyMaterial = legacyMaterial; - this.legacyData = legacyData; - - this.legacyMinimumVersion = legacyMinimum; - this.compatibleMaterial = compatMaterial; - this.compatibleData = compatData; - - if (ServerVersion.isServerVersionBelow(versionLessThan)) { - if (legacyMinimumVersion != null && ServerVersion.isServerVersionBelow(legacyMinimumVersion)) { - // fallback material not available, so use its fallback - material = Material.getMaterial(compatibleMaterial); - data = compatibleData; - } else if (modernMaterial == null || ServerVersion.isServerVersionBelow(ServerVersion.V1_13)) { - // use legacy material if on legacy - material = Material.getMaterial(legacyMaterial); - data = legacyData; - } else if (modernMaterial != null) { - material = Material.getMaterial(modernMaterial); - data = null; - } else { - material = null; - data = null; - } - } else { - material = null; - data = null; - } - } - - public Material getMaterial() { - return material; - } - - public boolean usesData() { - return data != null; - } - - public byte getData() { - return data == null ? 0 : data; - } - - public ItemStack getItem() { - if (material == null) { - return null; - } - return data != null ? new ItemStack(material, 1, data) : new ItemStack(material); - } -} +package com.songoda.core.compatibility; + +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.HashMap; +import java.util.Map; + +/** + * Near-Materials for older servers 1.7+ + * + * @author jascotty2 + * @since 2019-08-23 + */ +public enum LegacyMaterialAnalouge { + /* 1.17 */ + // ToDo: Improve legal materials. + AMETHYST_BLOCK(ServerVersion.V1_17, "STONE"), + AMETHYST_CLUSTER(ServerVersion.V1_17, "STONE"), + AMETHYST_SHARD(ServerVersion.V1_17, "STONE"), + AXOLOTL_BUCKET(ServerVersion.V1_17, "STONE"), + AXOLOTL_SPAWN_EGG(ServerVersion.V1_17, "STONE"), + AZALEA(ServerVersion.V1_17, "STONE"), + AZALEA_LEAVES(ServerVersion.V1_17, "STONE"), + BIG_DRIPLEAF(ServerVersion.V1_17, "STONE"), + BIG_DRIPLEAF_STEM(ServerVersion.V1_17, "STONE"), + BLACK_CANDLE(ServerVersion.V1_17, "STONE"), + BLACK_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), + BLUE_CANDLE(ServerVersion.V1_17, "STONE"), + BLUE_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), + BROWN_CANDLE(ServerVersion.V1_17, "STONE"), + BROWN_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), + BUDDING_AMETHYST(ServerVersion.V1_17, "STONE"), + BUNDLE(ServerVersion.V1_17, "STONE"), + CALCITE(ServerVersion.V1_17, "STONE"), + CANDLE(ServerVersion.V1_17, "STONE"), + CANDLE_CAKE(ServerVersion.V1_17, "STONE"), + CAVE_VINES(ServerVersion.V1_17, "STONE"), + CAVE_VINES_PLANT(ServerVersion.V1_17, "STONE"), + CHISELED_DEEPSLATE(ServerVersion.V1_17, "STONE"), + COBBLED_DEEPSLATE(ServerVersion.V1_17, "STONE"), + COBBLED_DEEPSLATE_SLAB(ServerVersion.V1_17, "STONE"), + COBBLED_DEEPSLATE_STAIRS(ServerVersion.V1_17, "STONE"), + COBBLED_DEEPSLATE_WALL(ServerVersion.V1_17, "STONE"), + COPPER_BLOCK(ServerVersion.V1_17, "STONE"), + COPPER_INGOT(ServerVersion.V1_17, "STONE"), + COPPER_ORE(ServerVersion.V1_17, "STONE"), + CRACKED_DEEPSLATE_BRICKS(ServerVersion.V1_17, "STONE"), + CRACKED_DEEPSLATE_TILES(ServerVersion.V1_17, "STONE"), + CUT_COPPER(ServerVersion.V1_17, "STONE"), + CUT_COPPER_SLAB(ServerVersion.V1_17, "STONE"), + CUT_COPPER_STAIRS(ServerVersion.V1_17, "STONE"), + CYAN_CANDLE(ServerVersion.V1_17, "STONE"), + CYAN_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), + DEEPSLATE(ServerVersion.V1_17, "STONE"), + DEEPSLATE_BRICKS(ServerVersion.V1_17, "STONE"), + DEEPSLATE_BRICK_SLAB(ServerVersion.V1_17, "STONE"), + DEEPSLATE_BRICK_STAIRS(ServerVersion.V1_17, "STONE"), + DEEPSLATE_BRICK_WALL(ServerVersion.V1_17, "STONE"), + DEEPSLATE_COAL_ORE(ServerVersion.V1_17, "STONE"), + DEEPSLATE_COPPER_ORE(ServerVersion.V1_17, "STONE"), + DEEPSLATE_DIAMOND_ORE(ServerVersion.V1_17, "STONE"), + DEEPSLATE_EMERALD_ORE(ServerVersion.V1_17, "STONE"), + DEEPSLATE_GOLD_ORE(ServerVersion.V1_17, "STONE"), + DEEPSLATE_IRON_ORE(ServerVersion.V1_17, "STONE"), + DEEPSLATE_LAPIS_ORE(ServerVersion.V1_17, "STONE"), + DEEPSLATE_REDSTONE_ORE(ServerVersion.V1_17, "STONE"), + DEEPSLATE_TILES(ServerVersion.V1_17, "STONE"), + DEEPSLATE_TILE_SLAB(ServerVersion.V1_17, "STONE"), + DEEPSLATE_TILE_STAIRS(ServerVersion.V1_17, "STONE"), + DEEPSLATE_TILE_WALL(ServerVersion.V1_17, "STONE"), + DRIPSTONE_BLOCK(ServerVersion.V1_17, "STONE"), + EXPOSED_COPPER(ServerVersion.V1_17, "STONE"), + EXPOSED_CUT_COPPER(ServerVersion.V1_17, "STONE"), + EXPOSED_CUT_COPPER_SLAB(ServerVersion.V1_17, "STONE"), + EXPOSED_CUT_COPPER_STAIRS(ServerVersion.V1_17, "STONE"), + FLOWERING_AZALEA(ServerVersion.V1_17, "STONE"), + FLOWERING_AZALEA_LEAVES(ServerVersion.V1_17, "STONE"), + GLOW_BERRIES(ServerVersion.V1_17, "STONE"), + GLOW_INK_SAC(ServerVersion.V1_17, "STONE"), + GLOW_ITEM_FRAME(ServerVersion.V1_17, "STONE"), + GLOW_LICHEN(ServerVersion.V1_17, "STONE"), + GLOW_SQUID_SPAWN_EGG(ServerVersion.V1_17, "STONE"), + GOAT_SPAWN_EGG(ServerVersion.V1_17, "STONE"), + GRAY_CANDLE(ServerVersion.V1_17, "STONE"), + GRAY_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), + GREEN_CANDLE(ServerVersion.V1_17, "STONE"), + GREEN_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), + HANGING_ROOTS(ServerVersion.V1_17, "STONE"), + INFESTED_DEEPSLATE(ServerVersion.V1_17, "STONE"), + LARGE_AMETHYST_BUD(ServerVersion.V1_17, "STONE"), + LAVA_CAULDRON(ServerVersion.V1_17, "STONE"), + LIGHT(ServerVersion.V1_17, "STONE"), + LIGHTNING_ROD(ServerVersion.V1_17, "STONE"), + LIGHT_BLUE_CANDLE(ServerVersion.V1_17, "STONE"), + LIGHT_BLUE_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), + LIGHT_GRAY_CANDLE(ServerVersion.V1_17, "STONE"), + LIGHT_GRAY_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), + LIME_CANDLE(ServerVersion.V1_17, "STONE"), + LIME_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), + MAGENTA_CANDLE(ServerVersion.V1_17, "STONE"), + MAGENTA_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), + MEDIUM_AMETHYST_BUD(ServerVersion.V1_17, "STONE"), + MOSS_BLOCK(ServerVersion.V1_17, "STONE"), + MOSS_CARPET(ServerVersion.V1_17, "STONE"), + ORANGE_CANDLE(ServerVersion.V1_17, "STONE"), + ORANGE_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), + OXIDIZED_COPPER(ServerVersion.V1_17, "STONE"), + OXIDIZED_CUT_COPPER(ServerVersion.V1_17, "STONE"), + OXIDIZED_CUT_COPPER_SLAB(ServerVersion.V1_17, "STONE"), + OXIDIZED_CUT_COPPER_STAIRS(ServerVersion.V1_17, "STONE"), + PINK_CANDLE(ServerVersion.V1_17, "STONE"), + PINK_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), + POINTED_DRIPSTONE(ServerVersion.V1_17, "STONE"), + POLISHED_DEEPSLATE(ServerVersion.V1_17, "STONE"), + POLISHED_DEEPSLATE_SLAB(ServerVersion.V1_17, "STONE"), + POLISHED_DEEPSLATE_STAIRS(ServerVersion.V1_17, "STONE"), + POLISHED_DEEPSLATE_WALL(ServerVersion.V1_17, "STONE"), + POTTED_AZALEA_BUSH(ServerVersion.V1_17, "STONE"), + POTTED_FLOWERING_AZALEA_BUSH(ServerVersion.V1_17, "STONE"), + POWDER_SNOW(ServerVersion.V1_17, "STONE"), + POWDER_SNOW_BUCKET(ServerVersion.V1_17, "STONE"), + POWDER_SNOW_CAULDRON(ServerVersion.V1_17, "STONE"), + PURPLE_CANDLE(ServerVersion.V1_17, "STONE"), + PURPLE_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), + RAW_COPPER(ServerVersion.V1_17, "STONE"), + RAW_COPPER_BLOCK(ServerVersion.V1_17, "STONE"), + RAW_GOLD(ServerVersion.V1_17, "STONE"), + RAW_GOLD_BLOCK(ServerVersion.V1_17, "STONE"), + RAW_IRON(ServerVersion.V1_17, "STONE"), + RAW_IRON_BLOCK(ServerVersion.V1_17, "STONE"), + RED_CANDLE(ServerVersion.V1_17, "STONE"), + RED_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), + ROOTED_DIRT(ServerVersion.V1_17, "STONE"), + SCULK_SENSOR(ServerVersion.V1_17, "STONE"), + SMALL_AMETHYST_BUD(ServerVersion.V1_17, "STONE"), + SMALL_DRIPLEAF(ServerVersion.V1_17, "STONE"), + SMOOTH_BASALT(ServerVersion.V1_17, "STONE"), + SPORE_BLOSSOM(ServerVersion.V1_17, "STONE"), + SPYGLASS(ServerVersion.V1_17, "STONE"), + TINTED_GLASS(ServerVersion.V1_17, "STONE"), + TUFF(ServerVersion.V1_17, "STONE"), + WATER_CAULDRON(ServerVersion.V1_17, "STONE"), + WAXED_COPPER_BLOCK(ServerVersion.V1_17, "STONE"), + WAXED_CUT_COPPER(ServerVersion.V1_17, "STONE"), + WAXED_CUT_COPPER_SLAB(ServerVersion.V1_17, "STONE"), + WAXED_CUT_COPPER_STAIRS(ServerVersion.V1_17, "STONE"), + WAXED_EXPOSED_COPPER(ServerVersion.V1_17, "STONE"), + WAXED_EXPOSED_CUT_COPPER(ServerVersion.V1_17, "STONE"), + WAXED_EXPOSED_CUT_COPPER_SLAB(ServerVersion.V1_17, "STONE"), + WAXED_EXPOSED_CUT_COPPER_STAIRS(ServerVersion.V1_17, "STONE"), + WAXED_OXIDIZED_COPPER(ServerVersion.V1_17, "STONE"), + WAXED_OXIDIZED_CUT_COPPER(ServerVersion.V1_17, "STONE"), + WAXED_OXIDIZED_CUT_COPPER_SLAB(ServerVersion.V1_17, "STONE"), + WAXED_OXIDIZED_CUT_COPPER_STAIRS(ServerVersion.V1_17, "STONE"), + WAXED_WEATHERED_COPPER(ServerVersion.V1_17, "STONE"), + WAXED_WEATHERED_CUT_COPPER(ServerVersion.V1_17, "STONE"), + WAXED_WEATHERED_CUT_COPPER_SLAB(ServerVersion.V1_17, "STONE"), + WAXED_WEATHERED_CUT_COPPER_STAIRS(ServerVersion.V1_17, "STONE"), + WEATHERED_COPPER(ServerVersion.V1_17, "STONE"), + WEATHERED_CUT_COPPER(ServerVersion.V1_17, "STONE"), + WEATHERED_CUT_COPPER_SLAB(ServerVersion.V1_17, "STONE"), + WEATHERED_CUT_COPPER_STAIRS(ServerVersion.V1_17, "STONE"), + WHITE_CANDLE(ServerVersion.V1_17, "STONE"), + WHITE_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), + YELLOW_CANDLE(ServerVersion.V1_17, "STONE"), + YELLOW_CANDLE_CAKE(ServerVersion.V1_17, "STONE"), + + /* 1.16 */ + // ToDo: Improve legal materials. + ANCIENT_DEBRIES(ServerVersion.V1_16, "STONE"), + BASALT(ServerVersion.V1_16, "STONE"), + BLACKSTONE(ServerVersion.V1_16, "STONE"), + BLACKSTONE_STAIRS(ServerVersion.V1_16, "STONE"), + BLACKSTONE_WALL(ServerVersion.V1_16, "STONE"), + BLASTSTONE_SLAB(ServerVersion.V1_16, "STONE"), + CHAIN(ServerVersion.V1_16, "STONE"), + CHISELED_NETHER_BRICKS(ServerVersion.V1_16, "STONE"), + CHISELED_POLISHED_BLACKSTONE(ServerVersion.V1_16, "STONE"), + CRACKED_NETHER_BRICKS(ServerVersion.V1_16, "STONE"), + CRACKED_POLISHED_BLACKSTONE_BRICKS(ServerVersion.V1_16, "STONE"), + CRIMSON_BUTTON(ServerVersion.V1_16, "STONE"), + CRIMSON_DOOR(ServerVersion.V1_16, "STONE"), + CRIMSON_FENCE(ServerVersion.V1_16, "STONE"), + CRIMSON_FENCE_GATE(ServerVersion.V1_16, "STONE"), + CRIMSON_FUNGUS(ServerVersion.V1_16, "STONE"), + CRIMSON_HYPHAE(ServerVersion.V1_16, "STONE"), + CRIMSON_NYLIUM(ServerVersion.V1_16, "STONE"), + CRIMSON_PLANKS(ServerVersion.V1_16, "STONE"), + CRIMSON_PRESSURE_PLATE(ServerVersion.V1_16, "STONE"), + CRIMSON_ROOTS(ServerVersion.V1_16, "STONE"), + CRIMSON_SIGN(ServerVersion.V1_16, "STONE"), + CRIMSON_SLAB(ServerVersion.V1_16, "STONE"), + CRIMSON_STAIRS(ServerVersion.V1_16, "STONE"), + CRIMSON_STEM(ServerVersion.V1_16, "STONE"), + CRIMSON_TRAPDOOR(ServerVersion.V1_16, "STONE"), + CRIMSON_WALL_SIGN(ServerVersion.V1_16, "STONE"), + CRYING_OBSIDIAN(ServerVersion.V1_16, "STONE"), + GILDED_BLACKSTONE(ServerVersion.V1_16, "STONE"), + HOGLIN_SPAWN_EGG(ServerVersion.V1_16, "STONE"), + LODESTONE(ServerVersion.V1_16, "STONE"), + MUSIC_DISC_PIGSTEP(ServerVersion.V1_16, "STONE"), + NETHERITE_AXE(ServerVersion.V1_16, "STONE"), + NETHERITE_BLOCK(ServerVersion.V1_16, "STONE"), + NETHERITE_BOOTS(ServerVersion.V1_16, "STONE"), + NETHERITE_CHESTPLATE(ServerVersion.V1_16, "STONE"), + NETHERITE_HELMET(ServerVersion.V1_16, "STONE"), + NETHERITE_HOE(ServerVersion.V1_16, "STONE"), + NETHERITE_INGOT(ServerVersion.V1_16, "STONE"), + NETHERITE_LEGGINGS(ServerVersion.V1_16, "STONE"), + NETHERITE_PICKAXE(ServerVersion.V1_16, "STONE"), + NETHERITE_SCRAP(ServerVersion.V1_16, "STONE"), + NETHERITE_SHOVEL(ServerVersion.V1_16, "STONE"), + NETHERITE_SWORD(ServerVersion.V1_16, "STONE"), + NETHER_GOLD_ORE(ServerVersion.V1_16, "STONE"), + NETHER_SPROUTS(ServerVersion.V1_16, "STONE"), + PIGLIN_BANNER_PATTERN(ServerVersion.V1_16, "STONE"), + PIGLIN_SPAWN_EGG(ServerVersion.V1_16, "STONE"), + POLISHED_BASALT(ServerVersion.V1_16, "STONE"), + POLISHED_BLACKSTONE(ServerVersion.V1_16, "STONE"), + POLISHED_BLACKSTONE_BRICKS(ServerVersion.V1_16, "STONE"), + POLISHED_BLACKSTONE_BRICK_SLAB(ServerVersion.V1_16, "STONE"), + POLISHED_BLACKSTONE_BRICK_STAIRS(ServerVersion.V1_16, "STONE"), + POLISHED_BLACKSTONE_BRICK_WALL(ServerVersion.V1_16, "STONE"), + POLISHED_BLACKSTONE_BUTTON(ServerVersion.V1_16, "STONE"), + POLISHED_BLACKSTONE_PRESSURE_PLATE(ServerVersion.V1_16, "STONE"), + POLISHED_BLACKSTONE_SLAB(ServerVersion.V1_16, "STONE"), + POLISHED_BLACKSTONE_STAIRS(ServerVersion.V1_16, "STONE"), + POLISHED_BLACKSTONE_WALL(ServerVersion.V1_16, "STONE"), + POTTED_CRIMSON_FUNGUS(ServerVersion.V1_16, "STONE"), + POTTED_CRIMSON_ROOTS(ServerVersion.V1_16, "STONE"), + POTTED_WARPED_FUNGUS(ServerVersion.V1_16, "STONE"), + POTTED_WARPED_ROOTS(ServerVersion.V1_16, "STONE"), + QUARTZ_BRICKS(ServerVersion.V1_16, "STONE"), + RESPAWN_ANCHOR(ServerVersion.V1_16, "STONE"), + SHROOMLIGHT(ServerVersion.V1_16, "STONE"), + SOUL_CAMPFIRE(ServerVersion.V1_16, "STONE"), + SOUL_FIRE(ServerVersion.V1_16, "STONE"), + SOUL_LANTERN(ServerVersion.V1_16, "STONE"), + SOUL_SOIL(ServerVersion.V1_16, "STONE"), + SOUL_TORCH(ServerVersion.V1_16, "STONE"), + SOUL_WALL_TORCH(ServerVersion.V1_16, "STONE"), + STRIDER_SPAWN_EGG(ServerVersion.V1_16, "STONE"), + STRIPPED_CRIMSON_HYPHAE(ServerVersion.V1_16, "STONE"), + STRIPPED_CRIMSON_STEM(ServerVersion.V1_16, "STONE"), + STRIPPED_WARPED_HYPHAE(ServerVersion.V1_16, "STONE"), + STRIPPED_WARPED_STEM(ServerVersion.V1_16, "STONE"), + TARGET(ServerVersion.V1_16, "STONE"), + TWISTING_VINES(ServerVersion.V1_16, "STONE"), + TWISTING_VINES_PLANT(ServerVersion.V1_16, "STONE"), + WARPED_BUTTON(ServerVersion.V1_16, "STONE"), + WARPED_DOOR(ServerVersion.V1_16, "STONE"), + WARPED_FENCE(ServerVersion.V1_16, "STONE"), + WARPED_FENCE_GATE(ServerVersion.V1_16, "STONE"), + WARPED_FUNGUS(ServerVersion.V1_16, "STONE"), + WARPED_FUNGUS_ON_A_STICK(ServerVersion.V1_16, "STONE"), + WARPED_HYPHAE(ServerVersion.V1_16, "STONE"), + WARPED_NYLIUM(ServerVersion.V1_16, "STONE"), + WARPED_PLANKS(ServerVersion.V1_16, "STONE"), + WARPED_PRESSURE_PLATE(ServerVersion.V1_16, "STONE"), + WARPED_ROOTS(ServerVersion.V1_16, "STONE"), + WARPED_SIGN(ServerVersion.V1_16, "STONE"), + WARPED_SLAB(ServerVersion.V1_16, "STONE"), + WARPED_STAIRS(ServerVersion.V1_16, "STONE"), + WARPED_STEM(ServerVersion.V1_16, "STONE"), + WARPED_TRAPDOOR(ServerVersion.V1_16, "STONE"), + WARPED_WALL_SIGN(ServerVersion.V1_16, "STONE"), + WARPED_WART_BLOCK(ServerVersion.V1_16, "STONE"), + WEEPING_VINES(ServerVersion.V1_16, "STONE"), + WEEPING_VINES_PLANT(ServerVersion.V1_16, "STONE"), + ZOGLIN_SPAWN_EGG(ServerVersion.V1_16, "STONE"), + ZOMBIFIED_PIGLIN_SPAWN_EGG(ServerVersion.V1_16, "STONE"), + + /* 1.15 */ + BEE_SPAWN_EGG(ServerVersion.V1_15, "PARROT_SPAWN_EGG", ServerVersion.V1_12, "MONSTER_EGG", (byte) 65), + BEE_NEST(ServerVersion.V1_15, "BIRCH_LOG", "LOG", (byte) 2), + BEEHIVE(ServerVersion.V1_15, "SLIME_BLOCK", ServerVersion.V1_8, "WOOL", (byte) 4), + HONEY_BLOCK(ServerVersion.V1_15, "SLIME_BLOCK", ServerVersion.V1_8, "WOOL", (byte) 4), + HONEY_BOTTLE(ServerVersion.V1_15, "DRAGON_BREATH", ServerVersion.V1_9, "POTION", (byte) 0), + HONEYCOMB(ServerVersion.V1_15, "SUNFLOWER", "DOUBLE_PLANT", (byte) 0), + HONEYCOMB_BLOCK(ServerVersion.V1_15, "SLIME_BLOCK", ServerVersion.V1_8, "WOOL", (byte) 4), + + ACACIA_BOAT(ServerVersion.V1_9, "BOAT"), + ACACIA_BUTTON(ServerVersion.V1_13, "WOOD_BUTTON"), + ACACIA_DOOR(ServerVersion.V1_8, "WOOD_DOOR"), // TODO? ACACIA_DOOR & WOODEN_DOOR are the legacy block variants + ACACIA_FENCE(ServerVersion.V1_8, "FENCE"), + ACACIA_FENCE_GATE(ServerVersion.V1_8, "FENCE_GATE"), + ACACIA_PRESSURE_PLATE(ServerVersion.V1_13, "WOOD_PLATE"), + ACACIA_SIGN(ServerVersion.V1_14, "SIGN", "SIGN"), + ACACIA_TRAPDOOR(ServerVersion.V1_13, "TRAP_DOOR"), + ACACIA_WALL_SIGN(ServerVersion.V1_14, "WALL_SIGN"), + ANDESITE(ServerVersion.V1_8, "STONE"), + ANDESITE_SLAB(ServerVersion.V1_14, "STONE_SLAB", "STEP", (byte) 0), + ANDESITE_STAIRS(ServerVersion.V1_14, "STONE_BRICK_STAIRS", "SMOOTH_STAIRS"), + ANDESITE_WALL(ServerVersion.V1_14, "COBBLESTONE_WALL", "COBBLE_WALL"), + ARMOR_STAND(ServerVersion.V1_8, "STICK"), // idk, we just need *something* + BAMBOO(ServerVersion.V1_14, "SUGAR_CANE", "SUGAR_CANE_BLOCK"), + BAMBOO_SAPLING(ServerVersion.V1_14, "SUGAR_CANE"), + BARREL(ServerVersion.V1_14, "TRAPPED_CHEST"), + BARRIER(ServerVersion.V1_8, "STAINED_GLASS", (byte) 14), // plain glass would make more sense if this were to be a block.. + BEETROOT(ServerVersion.V1_9, "RAW_BEEF"), + BEETROOT_SEEDS(ServerVersion.V1_9, "SEEDS"), + BEETROOT_SOUP(ServerVersion.V1_9, "MUSHROOM_SOUP"), + BEETROOTS(ServerVersion.V1_9, "CROPS"), + BELL(ServerVersion.V1_14, "GOLD_BLOCK", "GOLD_BLOCK"), + BIRCH_BOAT(ServerVersion.V1_9, "BOAT"), + BIRCH_BUTTON(ServerVersion.V1_13, "WOOD_BUTTON"), + BIRCH_DOOR(ServerVersion.V1_8, "WOOD_DOOR"), + BIRCH_FENCE(ServerVersion.V1_8, "FENCE"), + BIRCH_FENCE_GATE(ServerVersion.V1_8, "FENCE_GATE"), + BIRCH_PRESSURE_PLATE(ServerVersion.V1_13, "WOOD_PLATE"), + BIRCH_SIGN(ServerVersion.V1_14, "SIGN", "SIGN"), + BIRCH_STAIRS(ServerVersion.V1_13, "WOOD_STAIRS"), + BIRCH_TRAPDOOR(ServerVersion.V1_13, "TRAP_DOOR"), + BIRCH_WALL_SIGN(ServerVersion.V1_14, "WALL_SIGN"), + BLACK_BANNER(ServerVersion.V1_8, "SIGN"), + BLACK_BED(ServerVersion.V1_12, "BED"), + BLACK_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 15), + BLACK_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 15), + BLACK_DYE(ServerVersion.V1_14, "INK_SAC", "INK_SACK", (byte) 0), + BLACK_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 15), + BLACK_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), + BLACK_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), + BLAST_FURNACE(ServerVersion.V1_14, "FURNACE"), + BLUE_BANNER(ServerVersion.V1_8, "SIGN"), + BLUE_BED(ServerVersion.V1_12, "BED"), + BLUE_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 11), + BLUE_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 11), + BLUE_DYE(ServerVersion.V1_14, "LAPIS_LAZULI", "INK_SACK", (byte) 4), + BLUE_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 11), + BLUE_ICE(ServerVersion.V1_13, "PACKED_ICE"), + BLUE_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), + BLUE_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), + BONE_BLOCK(ServerVersion.V1_10, "QUARTZ_BLOCK"), + BRAIN_CORAL(ServerVersion.V1_13, "WOOL", (byte) 6), + BRAIN_CORAL_BLOCK(ServerVersion.V1_13, "WOOL", (byte) 6), + BRAIN_CORAL_FAN(ServerVersion.V1_13, "WOOL", (byte) 6), + BRAIN_CORAL_WALL_FAN(ServerVersion.V1_13, "WOOL", (byte) 6), + BRICK_WALL(ServerVersion.V1_14, "COBBLESTONE_WALL", "COBBLE_WALL"), + BROWN_BANNER(ServerVersion.V1_8, "SIGN"), + BROWN_BED(ServerVersion.V1_12, "BED"), + BROWN_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 12), + BROWN_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 12), + BROWN_DYE(ServerVersion.V1_14, "COCOA_BEANS", "INK_SACK", (byte) 3), + BROWN_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 12), + BROWN_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), + BROWN_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), + BUBBLE_COLUMN(ServerVersion.V1_13, "WATER"), + BUBBLE_CORAL(ServerVersion.V1_13, "WOOL", (byte) 2), + BUBBLE_CORAL_BLOCK(ServerVersion.V1_13, "WOOL", (byte) 2), + BUBBLE_CORAL_FAN(ServerVersion.V1_13, "WOOL", (byte) 2), + BUBBLE_CORAL_WALL_FAN(ServerVersion.V1_13, "WOOL", (byte) 2), + CAMPFIRE(ServerVersion.V1_14, "FURNACE", "BURNING_FURNACE"), + CARTOGRAPHY_TABLE(ServerVersion.V1_14, "BOOKSHELF"), + CAT_SPAWN_EGG(ServerVersion.V1_14, "OCELOT_SPAWN_EGG", "MONSTER_EGG", (byte) 98), + CAVE_AIR(ServerVersion.V1_13, "AIR"), + CHAIN_COMMAND_BLOCK(ServerVersion.V1_9, "COMMAND"), + CHISELED_RED_SANDSTONE(ServerVersion.V1_8, "SANDSTONE", (byte) 1), + CHORUS_FLOWER(ServerVersion.V1_9, "WOOL", (byte) 2), + CHORUS_FRUIT(ServerVersion.V1_9, "APPLE"), + CHORUS_PLANT(ServerVersion.V1_9, "WOOL", (byte) 10), + COARSE_DIRT(ServerVersion.V1_8, "DIRT"), + COD_BUCKET(ServerVersion.V1_13, "WATER_BUCKET"), + COD_SPAWN_EGG(ServerVersion.V1_13, "MONSTER_EGG", (byte) 60), + COMPOSTER(ServerVersion.V1_14, "FLOWER_POT", "FLOWER_POT_ITEM"), + CONDUIT(ServerVersion.V1_13, "MELON"), + COOKED_MUTTON(ServerVersion.V1_8, "COOKED_BEEF"), + COOKED_RABBIT(ServerVersion.V1_8, "COOKED_BEEF"), + CORNFLOWER(ServerVersion.V1_14, "BLUE_ORCHID", "RED_ROSE", (byte) 1), + CREEPER_BANNER_PATTERN(ServerVersion.V1_14, "PAPER"), + CROSSBOW(ServerVersion.V1_14, "BOW"), + CUT_RED_SANDSTONE(ServerVersion.V1_13, "RED_SANDSTONE", (byte) 2, ServerVersion.V1_8, "SANDSTONE", (byte) 0), + CUT_RED_SANDSTONE_SLAB(ServerVersion.V1_14, "STONE_SLAB", "STEP", (byte) 0), + CUT_SANDSTONE(ServerVersion.V1_13, "SANDSTONE", (byte) 2), + CUT_SANDSTONE_SLAB(ServerVersion.V1_14, "STONE_SLAB", "STEP", (byte) 0), + CYAN_BANNER(ServerVersion.V1_8, "SIGN"), + CYAN_BED(ServerVersion.V1_12, "BED"), + CYAN_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 9), + CYAN_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 9), + CYAN_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 9), + CYAN_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), + CYAN_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), + DARK_OAK_BOAT(ServerVersion.V1_9, "BOAT"), + DARK_OAK_BUTTON(ServerVersion.V1_13, "WOOD_BUTTON"), + DARK_OAK_DOOR(ServerVersion.V1_8, "WOOD_DOOR"), + DARK_OAK_FENCE(ServerVersion.V1_8, "FENCE"), + DARK_OAK_FENCE_GATE(ServerVersion.V1_8, "FENCE_GATE"), + DARK_OAK_PRESSURE_PLATE(ServerVersion.V1_13, "WOOD_PLATE"), + DARK_OAK_SIGN(ServerVersion.V1_14, "SIGN"), + DARK_OAK_TRAPDOOR(ServerVersion.V1_13, "TRAP_DOOR"), + DARK_OAK_WALL_SIGN(ServerVersion.V1_14, "WALL_SIGN"), + DARK_PRISMARINE(ServerVersion.V1_8, "WOOL", (byte) 7), + DARK_PRISMARINE_SLAB(ServerVersion.V1_13, "STEP", (byte) 0), + DARK_PRISMARINE_STAIRS(ServerVersion.V1_13, "NETHER_BRICK_STAIRS"), + DEAD_BRAIN_CORAL(ServerVersion.V1_13, "COBBLESTONE"), + DEAD_BRAIN_CORAL_BLOCK(ServerVersion.V1_13, "COBBLESTONE"), + DEAD_BRAIN_CORAL_FAN(ServerVersion.V1_13, "COBBLESTONE"), + DEAD_BRAIN_CORAL_WALL_FAN(ServerVersion.V1_13, "COBBLESTONE"), + DEAD_BUBBLE_CORAL(ServerVersion.V1_13, "COBBLESTONE"), + DEAD_BUBBLE_CORAL_BLOCK(ServerVersion.V1_13, "COBBLESTONE"), + DEAD_BUBBLE_CORAL_FAN(ServerVersion.V1_13, "COBBLESTONE"), + DEAD_BUBBLE_CORAL_WALL_FAN(ServerVersion.V1_13, "COBBLESTONE"), + DEAD_FIRE_CORAL(ServerVersion.V1_13, "COBBLESTONE"), + DEAD_FIRE_CORAL_BLOCK(ServerVersion.V1_13, "COBBLESTONE"), + DEAD_FIRE_CORAL_FAN(ServerVersion.V1_13, "COBBLESTONE"), + DEAD_FIRE_CORAL_WALL_FAN(ServerVersion.V1_13, "COBBLESTONE"), + DEAD_HORN_CORAL(ServerVersion.V1_13, "COBBLESTONE"), + DEAD_HORN_CORAL_BLOCK(ServerVersion.V1_13, "COBBLESTONE"), + DEAD_HORN_CORAL_FAN(ServerVersion.V1_13, "COBBLESTONE"), + DEAD_HORN_CORAL_WALL_FAN(ServerVersion.V1_13, "COBBLESTONE"), + DEAD_TUBE_CORAL(ServerVersion.V1_13, "COBBLESTONE"), + DEAD_TUBE_CORAL_BLOCK(ServerVersion.V1_13, "COBBLESTONE"), + DEAD_TUBE_CORAL_FAN(ServerVersion.V1_13, "COBBLESTONE"), // these could also be a dead_bush ? + DEAD_TUBE_CORAL_WALL_FAN(ServerVersion.V1_13, "COBBLESTONE"), + DEBUG_STICK(ServerVersion.V1_13, "STICK"), + DIORITE(ServerVersion.V1_8, "STONE"), + DIORITE_SLAB(ServerVersion.V1_14, "STONE_SLAB", "STEP", (byte) 0), + DIORITE_STAIRS(ServerVersion.V1_14, "STONE_BRICK_STAIRS", "SMOOTH_STAIRS"), + DIORITE_WALL(ServerVersion.V1_14, "COBBLESTONE_WALL", "COBBLE_WALL"), + DOLPHIN_SPAWN_EGG(ServerVersion.V1_13, "MONSTER_EGG", (byte) 0), + DONKEY_SPAWN_EGG(ServerVersion.V1_11, "MONSTER_EGG", (byte) 100), + DRAGON_BREATH(ServerVersion.V1_9, "POTION", (byte) 0), // or maybe glowstone.. + DRAGON_HEAD(ServerVersion.V1_9, "SKULL_ITEM", (byte) 4), + DRAGON_WALL_HEAD(ServerVersion.V1_9, "SKULL", (byte) 4), + DRIED_KELP(ServerVersion.V1_13, "POTATO_ITEM"), + DRIED_KELP_BLOCK(ServerVersion.V1_13, "HAY_BLOCK"), + DROWNED_SPAWN_EGG(ServerVersion.V1_13, "MONSTER_EGG", (byte) 54), + ELDER_GUARDIAN_SPAWN_EGG(ServerVersion.V1_11, "MONSTER_EGG", (byte) 51), + ELYTRA(ServerVersion.V1_9, "IRON_CHESTPLATE"), + END_CRYSTAL(ServerVersion.V1_9, "STAINED_GLASS", (byte) 0), + END_GATEWAY(ServerVersion.V1_9, "BEACON"), + END_PORTAL(ServerVersion.V1_9, "ENDER_PORTAL"), + END_ROD(ServerVersion.V1_9, "STAINED_GLASS_PANE", (byte) 0), + END_STONE_BRICK_SLAB(ServerVersion.V1_14, "STONE_SLAB", "STEP", (byte) 0), + END_STONE_BRICK_STAIRS(ServerVersion.V1_14, "SANDSTONE_STAIRS"), + END_STONE_BRICK_WALL(ServerVersion.V1_14, "COBBLESTONE_WALL", "COBBLE_WALL"), + END_STONE_BRICKS(ServerVersion.V1_9, "SANDSTONE", (byte) 2), + ENDERMITE_SPAWN_EGG(ServerVersion.V1_8, "MONSTER_EGG", (byte) 60), + EVOKER_SPAWN_EGG(ServerVersion.V1_11, "MONSTER_EGG", (byte) 51), + FILLED_MAP(ServerVersion.V1_13, "EMPTY_MAP"), + FIRE_CORAL(ServerVersion.V1_13, "WOOL", (byte) 14), + FIRE_CORAL_BLOCK(ServerVersion.V1_13, "WOOL", (byte) 14), + FIRE_CORAL_FAN(ServerVersion.V1_13, "WOOL", (byte) 14), + FIRE_CORAL_WALL_FAN(ServerVersion.V1_13, "WOOL", (byte) 14), + FLETCHING_TABLE(ServerVersion.V1_14, "CRAFTING_TABLE", "WORKBENCH"), + FLOWER_BANNER_PATTERN(ServerVersion.V1_14, "PAPER"), + FOX_SPAWN_EGG(ServerVersion.V1_14, "OCELOT_SPAWN_EGG", "MONSTER_EGG", (byte) 98), + FROSTED_ICE(ServerVersion.V1_13, "ICE"), + GLOBE_BANNER_PATTERN(ServerVersion.V1_14, "PAPER"), + GRANITE(ServerVersion.V1_8, "STONE"), + GRANITE_SLAB(ServerVersion.V1_14, "STONE_SLAB", "STEP", (byte) 0), + GRANITE_STAIRS(ServerVersion.V1_14, "STONE_BRICK_STAIRS", "SMOOTH_STAIRS"), + GRANITE_WALL(ServerVersion.V1_14, "COBBLESTONE_WALL", "COBBLE_WALL"), + GRASS_PATH(ServerVersion.V1_9, "DIRT", (byte) 1, ServerVersion.V1_8, "DIRT"), + GRAY_BANNER(ServerVersion.V1_8, "SIGN"), + GRAY_BED(ServerVersion.V1_12, "BED"), + GRAY_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 7), + GRAY_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 7), + GRAY_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 7), + GRAY_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), + GRAY_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), + GREEN_BANNER(ServerVersion.V1_8, "SIGN"), + GREEN_BED(ServerVersion.V1_12, "BED"), + GREEN_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 13), + GREEN_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 13), + GREEN_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 13), + GREEN_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), + GREEN_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), + GRINDSTONE(ServerVersion.V1_14, "ANVIL"), + GUARDIAN_SPAWN_EGG(ServerVersion.V1_8, "MONSTER_EGG", (byte) 51), + HEART_OF_THE_SEA(ServerVersion.V1_13, "DIAMOND"), + HORN_CORAL(ServerVersion.V1_13, "WOOL", (byte) 4), + HORN_CORAL_BLOCK(ServerVersion.V1_13, "WOOL", (byte) 4), + HORN_CORAL_FAN(ServerVersion.V1_13, "WOOL", (byte) 4), + HORN_CORAL_WALL_FAN(ServerVersion.V1_13, "WOOL", (byte) 4), + HUSK_SPAWN_EGG(ServerVersion.V1_11, "MONSTER_EGG", (byte) 54), + IRON_NUGGET(ServerVersion.V1_11, "IRON_INGOT"), + IRON_TRAPDOOR(ServerVersion.V1_8, "TRAP_DOOR"), + JIGSAW(ServerVersion.V1_14, "ANVIL"), + JUNGLE_BOAT(ServerVersion.V1_9, "BOAT"), + JUNGLE_BUTTON(ServerVersion.V1_13, "WOOD_BUTTON"), + JUNGLE_DOOR(ServerVersion.V1_8, "WOOD_DOOR"), + JUNGLE_FENCE(ServerVersion.V1_8, "FENCE"), + JUNGLE_FENCE_GATE(ServerVersion.V1_8, "FENCE_GATE"), + JUNGLE_PRESSURE_PLATE(ServerVersion.V1_13, "WOOD_PLATE"), + JUNGLE_SIGN(ServerVersion.V1_14, "SIGN"), + JUNGLE_TRAPDOOR(ServerVersion.V1_13, "TRAP_DOOR"), + JUNGLE_WALL_SIGN(ServerVersion.V1_14, "WALL_SIGN"), + KELP(ServerVersion.V1_13, "POTATO_ITEM"), + KELP_PLANT(ServerVersion.V1_13, "WATER"), // idk. + KNOWLEDGE_BOOK(ServerVersion.V1_12, "BOOK"), + LANTERN(ServerVersion.V1_14, "GLOWSTONE"), + LEATHER_HORSE_ARMOR(ServerVersion.V1_14, "IRON_BARDING"), + LECTERN(ServerVersion.V1_14, "BOOKSHELF"), + LIGHT_BLUE_BANNER(ServerVersion.V1_8, "SIGN"), + LIGHT_BLUE_BED(ServerVersion.V1_12, "BED"), + LIGHT_BLUE_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 3), + LIGHT_BLUE_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 3), + LIGHT_BLUE_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 3), + LIGHT_BLUE_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), + LIGHT_BLUE_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), + LIGHT_GRAY_BANNER(ServerVersion.V1_8, "SIGN"), + LIGHT_GRAY_BED(ServerVersion.V1_12, "BED"), + LIGHT_GRAY_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 8), + LIGHT_GRAY_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 8), + LIGHT_GRAY_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 8), + LIGHT_GRAY_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), + LIGHT_GRAY_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), + LILY_OF_THE_VALLEY(ServerVersion.V1_14, "AZURE_BLUET", "RED_ROSE", (byte) 3), + LIME_BANNER(ServerVersion.V1_8, "SIGN"), + LIME_BED(ServerVersion.V1_12, "BED"), + LIME_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 5), + LIME_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 5), + LIME_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 5), + LIME_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), + LIME_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), + LINGERING_POTION(ServerVersion.V1_9, "POTION", (byte) 0), + LLAMA_SPAWN_EGG(ServerVersion.V1_11, "MONSTER_EGG", (byte) 0), + LOOM(ServerVersion.V1_14, "CRAFTING_TABLE", "WORKBENCH"), + MAGENTA_BANNER(ServerVersion.V1_8, "SIGN"), + MAGENTA_BED(ServerVersion.V1_12, "BED"), + MAGENTA_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 2), + MAGENTA_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 2), + MAGENTA_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 2), + MAGENTA_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), + MAGENTA_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), + MAGMA_BLOCK(ServerVersion.V1_10, "NETHER_BRICK"), + MOJANG_BANNER_PATTERN(ServerVersion.V1_14, "PAPER"), + MOSSY_COBBLESTONE_SLAB(ServerVersion.V1_14, "COBBLESTONE_SLAB", "STEP", (byte) 3), + MOSSY_COBBLESTONE_STAIRS(ServerVersion.V1_14, "COBBLESTONE_STAIRS"), + MOSSY_COBBLESTONE_WALL(ServerVersion.V1_14, "COBBLESTONE_WALL", "COBBLE_WALL"), + MOSSY_STONE_BRICK_SLAB(ServerVersion.V1_14, "BRICK_SLAB", "STEP", (byte) 4), + MOSSY_STONE_BRICK_STAIRS(ServerVersion.V1_14, "STONE_BRICK_STAIRS", "SMOOTH_STAIRS"), + MOSSY_STONE_BRICK_WALL(ServerVersion.V1_14, "COBBLESTONE_WALL", "COBBLE_WALL"), + MULE_SPAWN_EGG(ServerVersion.V1_11, "MONSTER_EGG", (byte) 100), + MUTTON(ServerVersion.V1_8, "RAW_BEEF"), + NAUTILUS_SHELL(ServerVersion.V1_13, "SNOW_BALL"), + NETHER_BRICK_FENCE(ServerVersion.V1_13, "FENCE"), + NETHER_BRICK_WALL(ServerVersion.V1_14, "COBBLESTONE_WALL", "COBBLE_WALL"), + NETHER_WART_BLOCK(ServerVersion.V1_10, "NETHERRACK"), + OAK_BOAT(ServerVersion.V1_9, "BOAT"), + OBSERVER(ServerVersion.V1_11, "DISPENSER"), + ORANGE_BANNER(ServerVersion.V1_8, "SIGN"), + ORANGE_BED(ServerVersion.V1_12, "BED"), + ORANGE_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 1), + ORANGE_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 1), + ORANGE_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 1), + ORANGE_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), + ORANGE_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), + PANDA_SPAWN_EGG(ServerVersion.V1_14, "COW_SPAWN_EGG", "MONSTER_EGG", (byte) 92), + PARROT_SPAWN_EGG(ServerVersion.V1_12, "MONSTER_EGG", (byte) 65), + PHANTOM_MEMBRANE(ServerVersion.V1_13, "FEATHER"), + PHANTOM_SPAWN_EGG(ServerVersion.V1_13, "MONSTER_EGG", (byte) 65), + PILLAGER_SPAWN_EGG(ServerVersion.V1_14, "VILLAGER_SPAWN_EGG", "MONSTER_EGG", (byte) 120), + PINK_BANNER(ServerVersion.V1_8, "SIGN"), + PINK_BED(ServerVersion.V1_12, "BED"), + PINK_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 6), + PINK_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 6), + PINK_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 6), + PINK_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), + PINK_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), + PODZOL(ServerVersion.V1_8, "DIRT"), + POLAR_BEAR_SPAWN_EGG(ServerVersion.V1_10, "MONSTER_EGG", (byte) 0), + POLISHED_ANDESITE(ServerVersion.V1_8, "STONE"), + POLISHED_ANDESITE_SLAB(ServerVersion.V1_14, "STONE_SLAB", "STEP", (byte) 0), + POLISHED_ANDESITE_STAIRS(ServerVersion.V1_14, "STONE_BRICK_STAIRS", "SMOOTH_STAIRS"), + POLISHED_DIORITE(ServerVersion.V1_8, "STONE"), + POLISHED_DIORITE_SLAB(ServerVersion.V1_14, "STONE_SLAB", "STEP", (byte) 0), + POLISHED_DIORITE_STAIRS(ServerVersion.V1_14, "STONE_BRICK_STAIRS", "SMOOTH_STAIRS"), + POLISHED_GRANITE(ServerVersion.V1_8, "STONE"), + POLISHED_GRANITE_SLAB(ServerVersion.V1_14, "STONE_SLAB", "STEP", (byte) 0), + POLISHED_GRANITE_STAIRS(ServerVersion.V1_14, "STONE_BRICK_STAIRS", "SMOOTH_STAIRS"), + POPPED_CHORUS_FRUIT(ServerVersion.V1_9, "GOLDEN_APPLE"), + POTTED_ACACIA_SAPLING(ServerVersion.V1_13, "FLOWER_POT_ITEM"), + POTTED_ALLIUM(ServerVersion.V1_13, "FLOWER_POT_ITEM"), + POTTED_AZURE_BLUET(ServerVersion.V1_13, "FLOWER_POT_ITEM"), + POTTED_BAMBOO(ServerVersion.V1_14, "FLOWER_POT", "FLOWER_POT_ITEM"), + POTTED_BIRCH_SAPLING(ServerVersion.V1_13, "FLOWER_POT_ITEM"), + POTTED_BLUE_ORCHID(ServerVersion.V1_13, "FLOWER_POT_ITEM"), + POTTED_BROWN_MUSHROOM(ServerVersion.V1_13, "FLOWER_POT_ITEM"), + POTTED_CACTUS(ServerVersion.V1_13, "FLOWER_POT_ITEM"), + POTTED_CORNFLOWER(ServerVersion.V1_14, "FLOWER_POT", "FLOWER_POT_ITEM"), + POTTED_DANDELION(ServerVersion.V1_13, "FLOWER_POT_ITEM"), + POTTED_DARK_OAK_SAPLING(ServerVersion.V1_13, "FLOWER_POT_ITEM"), + POTTED_DEAD_BUSH(ServerVersion.V1_13, "FLOWER_POT_ITEM"), + POTTED_FERN(ServerVersion.V1_13, "FLOWER_POT_ITEM"), + POTTED_JUNGLE_SAPLING(ServerVersion.V1_13, "FLOWER_POT_ITEM"), + POTTED_LILY_OF_THE_VALLEY(ServerVersion.V1_14, "FLOWER_POT", "FLOWER_POT_ITEM"), + POTTED_OAK_SAPLING(ServerVersion.V1_13, "FLOWER_POT_ITEM"), + POTTED_ORANGE_TULIP(ServerVersion.V1_13, "FLOWER_POT_ITEM"), + POTTED_OXEYE_DAISY(ServerVersion.V1_13, "FLOWER_POT_ITEM"), + POTTED_PINK_TULIP(ServerVersion.V1_13, "FLOWER_POT_ITEM"), + POTTED_POPPY(ServerVersion.V1_13, "FLOWER_POT_ITEM"), + POTTED_RED_MUSHROOM(ServerVersion.V1_13, "FLOWER_POT_ITEM"), + POTTED_RED_TULIP(ServerVersion.V1_13, "FLOWER_POT_ITEM"), + POTTED_SPRUCE_SAPLING(ServerVersion.V1_13, "FLOWER_POT_ITEM"), + POTTED_WHITE_TULIP(ServerVersion.V1_13, "FLOWER_POT_ITEM"), + POTTED_WITHER_ROSE(ServerVersion.V1_14, "FLOWER_POT", "FLOWER_POT_ITEM"), + PRISMARINE(ServerVersion.V1_8, "WOOL", (byte) 9), + PRISMARINE_BRICK_SLAB(ServerVersion.V1_14, "STONE_SLAB", "STEP", (byte) 0), + PRISMARINE_BRICK_STAIRS(ServerVersion.V1_13, "SMOOTH_STAIRS"), + PRISMARINE_BRICKS(ServerVersion.V1_8, "WOOL", (byte) 9), + PRISMARINE_CRYSTALS(ServerVersion.V1_8, "CLAY_BALL"), + PRISMARINE_SHARD(ServerVersion.V1_8, "FLINT"), + PRISMARINE_SLAB(ServerVersion.V1_13, "STEP", (byte) 0), + PRISMARINE_STAIRS(ServerVersion.V1_13, "COBBLESTONE_STAIRS"), + PRISMARINE_WALL(ServerVersion.V1_14, "COBBLESTONE_WALL", "COBBLE_WALL"), + PUFFERFISH_BUCKET(ServerVersion.V1_13, "WATER_BUCKET"), + PUFFERFISH_SPAWN_EGG(ServerVersion.V1_13, "MONSTER_EGG", (byte) 60), + PURPLE_BANNER(ServerVersion.V1_8, "SIGN"), + PURPLE_BED(ServerVersion.V1_12, "BED"), + PURPLE_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 10), + PURPLE_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 10), + PURPLE_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 10), + PURPLE_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), + PURPLE_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), + PURPUR_BLOCK(ServerVersion.V1_9, "WOOL", (byte) 2), + PURPUR_PILLAR(ServerVersion.V1_9, "WOOL", (byte) 2), + PURPUR_SLAB(ServerVersion.V1_9, "STEP", (byte) 0), + PURPUR_STAIRS(ServerVersion.V1_9, "BRICK_STAIRS"), + RABBIT(ServerVersion.V1_8, "RAW_BEEF"), + RABBIT_FOOT(ServerVersion.V1_8, "ROTTEN_FLESH"), + RABBIT_HIDE(ServerVersion.V1_8, "ROTTEN_FLESH"), + RABBIT_SPAWN_EGG(ServerVersion.V1_8, "MONSTER_EGG", (byte) 0), + RABBIT_STEW(ServerVersion.V1_8, "MUSHROOM_SOUP"), + RAVAGER_SPAWN_EGG(ServerVersion.V1_14, "COW_SPAWN_EGG", "MONSTER_EGG", (byte) 92), + RED_BANNER(ServerVersion.V1_8, "SIGN"), + RED_BED(ServerVersion.V1_12, "BED"), + RED_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 14), + RED_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 14), + RED_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 14), + RED_NETHER_BRICK_SLAB(ServerVersion.V1_14, "STONE_SLAB", "STEP", (byte) 0), + RED_NETHER_BRICK_STAIRS(ServerVersion.V1_14, "NETHER_BRICK_STAIRS"), + RED_NETHER_BRICK_WALL(ServerVersion.V1_14, "COBBLESTONE_WALL", "COBBLE_WALL"), + RED_NETHER_BRICKS(ServerVersion.V1_10, "NETHER_BRICK"), + RED_SANDSTONE(ServerVersion.V1_8, "SANDSTONE", (byte) 0), + RED_SANDSTONE_SLAB(ServerVersion.V1_8, "STEP", (byte) 0), + RED_SANDSTONE_STAIRS(ServerVersion.V1_8, "SANDSTONE_STAIRS"), + RED_SANDSTONE_WALL(ServerVersion.V1_14, "COBBLESTONE_WALL", "COBBLE_WALL"), + RED_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), + RED_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), + REDSTONE_WALL_TORCH(ServerVersion.V1_13, "REDSTONE_TORCH_ON"), + REPEATING_COMMAND_BLOCK(ServerVersion.V1_9, "COMMAND"), + SALMON_BUCKET(ServerVersion.V1_13, "WATER_BUCKET"), + SALMON_SPAWN_EGG(ServerVersion.V1_13, "MONSTER_EGG", (byte) 60), + SANDSTONE_WALL(ServerVersion.V1_14, "COBBLESTONE_WALL", "COBBLE_WALL"), + SCAFFOLDING(ServerVersion.V1_14, "LADDER"), + SCUTE(ServerVersion.V1_13, "SLIME_BALL"), + SEA_LANTERN(ServerVersion.V1_8, "GLOWSTONE"), + SEA_PICKLE(ServerVersion.V1_13, "CACTUS"), + SEAGRASS(ServerVersion.V1_13, "LONG_GRASS", (byte) 1), + SHIELD(ServerVersion.V1_9, "BANNER", (byte) 3, ServerVersion.V1_8, "WOOD_DOOR"), + SHULKER_BOX(ServerVersion.V1_13, "ENDER_CHEST"), + SHULKER_SHELL(ServerVersion.V1_11, "SUGAR"), + SHULKER_SPAWN_EGG(ServerVersion.V1_9, "MONSTER_EGG", (byte) 0), + SKELETON_HORSE_SPAWN_EGG(ServerVersion.V1_11, "MONSTER_EGG", (byte) 0), + SKULL_BANNER_PATTERN(ServerVersion.V1_14, "PAPER"), + SLIME_BLOCK(ServerVersion.V1_8, "WOOL", (byte) 5), + SMITHING_TABLE(ServerVersion.V1_14, "CRAFTING_TABLE", "WORKBENCH"), + SMOKER(ServerVersion.V1_14, "FURNACE"), + SMOOTH_QUARTZ(ServerVersion.V1_13, "QUARTZ_BLOCK", (byte) 0), + SMOOTH_QUARTZ_SLAB(ServerVersion.V1_14, "QUARTZ_SLAB", "STEP", (byte) 7), + SMOOTH_QUARTZ_STAIRS(ServerVersion.V1_14, "QUARTZ_STAIRS"), + SMOOTH_RED_SANDSTONE(ServerVersion.V1_13, "RED_SANDSTONE", (byte) 0, ServerVersion.V1_8, "SANDSTONE", (byte) 0), + SMOOTH_RED_SANDSTONE_SLAB(ServerVersion.V1_14, "SANDSTONE_SLAB", "STEP", (byte) 1), + SMOOTH_RED_SANDSTONE_STAIRS(ServerVersion.V1_14, "RED_SANDSTONE_STAIRS", ServerVersion.V1_8, "SANDSTONE_STAIRS"), + SMOOTH_SANDSTONE_SLAB(ServerVersion.V1_14, "SANDSTONE_SLAB", "STEP", (byte) 1), + SMOOTH_SANDSTONE_STAIRS(ServerVersion.V1_14, "SANDSTONE_STAIRS"), + SMOOTH_STONE(ServerVersion.V1_13, "STONE"), // DOUBLE_STEP is a closer texture match + SMOOTH_STONE_SLAB(ServerVersion.V1_14, "STONE_SLAB", "STEP", (byte) 0), + SPECTRAL_ARROW(ServerVersion.V1_9, "ARROW"), + SPRUCE_BOAT(ServerVersion.V1_9, "BOAT"), + SPRUCE_BUTTON(ServerVersion.V1_13, "WOOD_BUTTON"), + SPRUCE_DOOR(ServerVersion.V1_8, "WOOD_DOOR"), + SPRUCE_FENCE(ServerVersion.V1_8, "FENCE"), + SPRUCE_FENCE_GATE(ServerVersion.V1_8, "FENCE_GATE"), + SPRUCE_PRESSURE_PLATE(ServerVersion.V1_13, "WOOD_PLATE"), + SPRUCE_SIGN(ServerVersion.V1_14, "SIGN"), + SPRUCE_TRAPDOOR(ServerVersion.V1_13, "TRAP_DOOR"), + SPRUCE_WALL_SIGN(ServerVersion.V1_14, "WALL_SIGN"), + //STONE(ServerVersion.V1_8, "STONE"), // funny how that happened, heh. Non-data to data to non-data again + STONE_BRICK_WALL(ServerVersion.V1_14, "COBBLESTONE_WALL", "COBBLE_WALL"), + STONE_SLAB(ServerVersion.V1_13, "STEP", (byte) 0), + STONE_STAIRS(ServerVersion.V1_14, "STONE_BRICK_STAIRS", "SMOOTH_STAIRS"), + STONECUTTER(ServerVersion.V1_14, "ANVIL"), + STRAY_SPAWN_EGG(ServerVersion.V1_11, "MONSTER_EGG", (byte) 0), + STRIPPED_ACACIA_LOG(ServerVersion.V1_13, "LOG_2", (byte) 0), + STRIPPED_ACACIA_WOOD(ServerVersion.V1_13, "LOG_2", (byte) 12), + STRIPPED_BIRCH_LOG(ServerVersion.V1_13, "LOG", (byte) 2), + STRIPPED_BIRCH_WOOD(ServerVersion.V1_13, "LOG", (byte) 14), + STRIPPED_DARK_OAK_LOG(ServerVersion.V1_13, "LOG_2", (byte) 1), + STRIPPED_DARK_OAK_WOOD(ServerVersion.V1_13, "LOG_2", (byte) 13), + STRIPPED_JUNGLE_LOG(ServerVersion.V1_13, "LOG", (byte) 3), + STRIPPED_JUNGLE_WOOD(ServerVersion.V1_13, "LOG", (byte) 15), + STRIPPED_OAK_LOG(ServerVersion.V1_13, "LOG", (byte) 0), + STRIPPED_OAK_WOOD(ServerVersion.V1_13, "LOG", (byte) 12), + STRIPPED_SPRUCE_LOG(ServerVersion.V1_13, "LOG", (byte) 1), + STRIPPED_SPRUCE_WOOD(ServerVersion.V1_13, "LOG", (byte) 13), + STRUCTURE_BLOCK(ServerVersion.V1_9, "COMMAND"), + STRUCTURE_VOID(ServerVersion.V1_10, "BARRIER", ServerVersion.V1_8, "STAINED_GLASS", (byte) 14), // Block would be air, but these make more sense as an item + SUSPICIOUS_STEW(ServerVersion.V1_14, "MUSHROOM_SOUP"), + SWEET_BERRIES(ServerVersion.V1_14, "POTATO", "POTATO_ITEM"), + SWEET_BERRY_BUSH(ServerVersion.V1_14, "OAK_LEAVES", "LEAVES", (byte) 3), + TALL_SEAGRASS(ServerVersion.V1_13, "LONG_GRASS", (byte) 1), + TIPPED_ARROW(ServerVersion.V1_9, "ARROW"), + TOTEM_OF_UNDYING(ServerVersion.V1_11, "CHAINMAIL_CHESTPLATE"), + TRADER_LLAMA_SPAWN_EGG(ServerVersion.V1_14, "LLAMA_SPAWN_EGG", "MONSTER_EGG", (byte) 103), // todo? should we change the item here? llamas are v1.11+ + TRIDENT(ServerVersion.V1_13, "ARROW"), + TROPICAL_FISH_BUCKET(ServerVersion.V1_13, "WATER_BUCKET"), + TROPICAL_FISH_SPAWN_EGG(ServerVersion.V1_13, "MONSTER_EGG", (byte) 60), + TUBE_CORAL(ServerVersion.V1_13, "WOOL", (byte) 11), + TUBE_CORAL_BLOCK(ServerVersion.V1_13, "WOOL", (byte) 11), + TUBE_CORAL_FAN(ServerVersion.V1_13, "WOOL", (byte) 11), + TUBE_CORAL_WALL_FAN(ServerVersion.V1_13, "WOOL", (byte) 11), + TURTLE_EGG(ServerVersion.V1_13, "DRAGON_EGG"), + TURTLE_HELMET(ServerVersion.V1_13, "LEATHER_HELMET"), // would be cool to color it green.. + TURTLE_SPAWN_EGG(ServerVersion.V1_13, "MONSTER_EGG", (byte) 60), + VEX_SPAWN_EGG(ServerVersion.V1_11, "MONSTER_EGG", (byte) 0), + VINDICATOR_SPAWN_EGG(ServerVersion.V1_11, "MONSTER_EGG", (byte) 0), + VOID_AIR(ServerVersion.V1_13, "AIR"), + WALL_TORCH(ServerVersion.V1_13, "TORCH"), + WANDERING_TRADER_SPAWN_EGG(ServerVersion.V1_14, "VILLAGER_SPAWN_EGG", "MONSTER_EGG", (byte) 120), + WHITE_BANNER(ServerVersion.V1_8, "SIGN"), + WHITE_BED(ServerVersion.V1_12, "BED"), + WHITE_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 0), + WHITE_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 0), + WHITE_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 0), + WHITE_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), + WHITE_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), + WITHER_ROSE(ServerVersion.V1_14, "POPPY", "RED_ROSE", (byte) 0), + WITHER_SKELETON_SPAWN_EGG(ServerVersion.V1_11, "MONSTER_EGG", (byte) 0), + YELLOW_BANNER(ServerVersion.V1_8, "SIGN"), + YELLOW_BED(ServerVersion.V1_12, "BED"), + YELLOW_CONCRETE(ServerVersion.V1_12, "STAINED_CLAY", (byte) 4), + YELLOW_CONCRETE_POWDER(ServerVersion.V1_12, "STAINED_CLAY", (byte) 4), + YELLOW_GLAZED_TERRACOTTA(ServerVersion.V1_12, "STAINED_CLAY", (byte) 4), + YELLOW_SHULKER_BOX(ServerVersion.V1_11, "ENDER_CHEST"), + YELLOW_WALL_BANNER(ServerVersion.V1_8, "WALL_SIGN"), + ZOMBIE_HORSE_SPAWN_EGG(ServerVersion.V1_11, "MONSTER_EGG", (byte) 0), + ZOMBIE_VILLAGER_SPAWN_EGG(ServerVersion.V1_11, "MONSTER_EGG", (byte) 0), + ; + + final ServerVersion versionLessThan; + final String modernMaterial; + final String legacyMaterial; + final Byte legacyData; + final ServerVersion legacyMinimumVersion; + final String compatibleMaterial; + final Byte compatibleData; + final Material material; + final Byte data; + + // map to speed up name->material lookups + private static final Map lookupMap = new HashMap(); + + static { + for (LegacyMaterialAnalouge m : values()) { + lookupMap.put(m.name(), m); + } + } + + public static LegacyMaterialAnalouge lookupAnalouge(String material) { + return lookupMap.get(material); + } + + private LegacyMaterialAnalouge(ServerVersion versionLessThan, String legacyMaterial, byte legacyData) { + this(versionLessThan, null, legacyMaterial, legacyData, null, null, null); + } + + private LegacyMaterialAnalouge(ServerVersion versionLessThan, String legacyMaterial) { + this(versionLessThan, null, legacyMaterial, null, null, null, null); + } + + private LegacyMaterialAnalouge(ServerVersion versionLessThan, String modernAnalouge, String legacyMaterial) { + this(versionLessThan, modernAnalouge, legacyMaterial, null, null, null, null); + } + + private LegacyMaterialAnalouge(ServerVersion versionLessThan, String modernAnalouge, String legacyMaterial, byte legacyData) { + this(versionLessThan, modernAnalouge, legacyMaterial, legacyData, null, null, null); + } + + private LegacyMaterialAnalouge(ServerVersion versionLessThan, String legacyMaterial, byte legacyData, ServerVersion legacyMinimum, String compatMaterial, byte compatData) { + this(versionLessThan, null, legacyMaterial, legacyData, legacyMinimum, compatMaterial, compatData); + } + + private LegacyMaterialAnalouge(ServerVersion versionLessThan, String legacyMaterial, ServerVersion legacyMinimum, String compatMaterial, byte compatData) { + this(versionLessThan, null, legacyMaterial, null, legacyMinimum, compatMaterial, compatData); + } + + private LegacyMaterialAnalouge(ServerVersion versionLessThan, String legacyMaterial, byte legacyData, ServerVersion legacyMinimum, String compatMaterial) { + this(versionLessThan, null, legacyMaterial, legacyData, legacyMinimum, compatMaterial, null); + } + + private LegacyMaterialAnalouge(ServerVersion versionLessThan, String legacyMaterial, ServerVersion legacyMinimum, String compatMaterial) { + this(versionLessThan, null, legacyMaterial, null, legacyMinimum, compatMaterial, null); + } + + /** + * @param versionLessThan AKA, what server version was this material added to minecraft? + * @param modernAnalouge post-1.13 material name, if applicable + * @param legacyMaterial pre-1.13 material name + * @param legacyData data for defining specific legacy items + */ + private LegacyMaterialAnalouge(ServerVersion versionLessThan, String modernAnalouge, String legacyMaterial, Byte legacyData, ServerVersion legacyMinimum, String compatMaterial, Byte compatData) { + this.versionLessThan = versionLessThan; + this.modernMaterial = modernAnalouge; + this.legacyMaterial = legacyMaterial; + this.legacyData = legacyData; + + this.legacyMinimumVersion = legacyMinimum; + this.compatibleMaterial = compatMaterial; + this.compatibleData = compatData; + + if (ServerVersion.isServerVersionBelow(versionLessThan)) { + if (legacyMinimumVersion != null && ServerVersion.isServerVersionBelow(legacyMinimumVersion)) { + // fallback material not available, so use its fallback + material = Material.getMaterial(compatibleMaterial); + data = compatibleData; + } else if (modernMaterial == null || ServerVersion.isServerVersionBelow(ServerVersion.V1_13)) { + // use legacy material if on legacy + material = Material.getMaterial(legacyMaterial); + data = legacyData; + } else { + material = Material.getMaterial(modernMaterial); + data = null; + } + } else { + material = null; + data = null; + } + } + + public Material getMaterial() { + return material; + } + + public boolean usesData() { + return data != null; + } + + public byte getData() { + return data == null ? 0 : data; + } + + public ItemStack getItem() { + if (material == null) { + return null; + } + + return data != null ? new ItemStack(material, 1, data) : new ItemStack(material); + } +} diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyMaterialBlockType.java b/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyMaterialBlockType.java index 137cc7d7..abcc507c 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyMaterialBlockType.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyMaterialBlockType.java @@ -13,7 +13,6 @@ import java.util.Map; * @since 2019-09-12 */ public enum LegacyMaterialBlockType { - OAK_LEAVES("LEAVES", (byte) 8, true), SPRUCE_LEAVES("LEAVES", (byte) 9, true), BIRCH_LEAVES("LEAVES", (byte) 10, true), diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyParticleEffects.java b/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyParticleEffects.java index 92b7e887..6e26bf90 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyParticleEffects.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyParticleEffects.java @@ -1,255 +1,256 @@ -package com.songoda.core.compatibility; - -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.entity.Player; - -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Particle effects for servers 1.8 and below - * - * @author jascotty2 - * @since 2019-08-23 - */ -public class LegacyParticleEffects { - - public static enum Type { - - EXPLOSION_NORMAL("explode"), - EXPLOSION_LARGE("largeexplode"), - EXPLOSION_HUGE("hugeexplosion"), - FIREWORKS_SPARK("fireworksSpark"), - WATER_BUBBLE("bubble"), - WATER_SPLASH("splash"), - WATER_WAKE("wake", ServerVersion.V1_8), - SUSPENDED("suspended"), - SUSPENDED_DEPTH("depthsuspend"), - CRIT("crit"), - CRIT_MAGIC("magicCrit"), - SMOKE_NORMAL("smoke"), - SMOKE_LARGE("largesmoke"), - SPELL("spell"), - SPELL_INSTANT("instantSpell"), - SPELL_MOB("mobSpell"), - SPELL_MOB_AMBIENT("mobSpellAmbient"), - SPELL_WITCH("witchMagic"), - DRIP_WATER("dripWater"), - DRIP_LAVA("dripLava"), - VILLAGER_ANGRY("angryVillager"), - VILLAGER_HAPPY("happyVillager"), - TOWN_AURA("townaura"), - NOTE("note"), - PORTAL("portal"), - ENCHANTMENT_TABLE("enchantmenttable"), - FLAME("flame"), - LAVA("lava"), - FOOTSTEP("footstep"), - CLOUD("cloud"), - REDSTONE("reddust"), - SNOWBALL("snowballpoof"), - SNOW_SHOVEL("snowshovel"), - SLIME("slime"), - HEART("heart"), - BARRIER("barrier", ServerVersion.V1_8), - /** - * Used when a block is broken - */ - ITEM_CRACK("iconcrack_"), - BLOCK_CRACK("blockcrack_", ServerVersion.V1_8), - BLOCK_DUST("blockdust_", ServerVersion.V1_8), - WATER_DROP("droplet", ServerVersion.V1_8), - ITEM_TAKE("take", ServerVersion.V1_8), - MOB_APPEARANCE("mobappearance", ServerVersion.V1_8), - TOOL_BREAK("tilecrack_", ServerVersion.UNKNOWN, ServerVersion.V1_7); - - public final String name; - public final ServerVersion minVersion; - public final ServerVersion maxVersion; - - private Type(String name) { - this.name = name; - this.minVersion = ServerVersion.UNKNOWN; - this.maxVersion = null; - } - - private Type(String name, ServerVersion minVersion) { - this.name = name; - this.minVersion = minVersion; - this.maxVersion = null; - } - - private Type(String name, ServerVersion minVersion, ServerVersion maxVersion) { - this.name = name; - this.minVersion = minVersion; - this.maxVersion = maxVersion; - } - - public static Type getById(String id) { - for (Type t : Type.values()) { - if (t.name.equalsIgnoreCase(id) || t.name().equalsIgnoreCase(id)) { - return t; - } - } - return null; - } - } - - private static final String version = getNMSVersion(); - private static boolean enabled = true; - private static Class mc_packetPlayOutWorldParticlesClazz; - private static Class cb_craftPlayerClazz; - private static Method cb_craftPlayer_getHandle; - private static Class mc_entityPlayerClazz; - private static Class mc_playerConnectionClazz; - private static Field mc_entityPlayer_playerConnection; - private static Class mc_PacketInterface; - private static Method mc_playerConnection_sendPacket; - private static Class mc_EnumParticle; - private static Method mc_EnumParticle_valueOf; - - static { - try { - // lower versions use "Packet63WorldParticles" - if (!version.startsWith("v1_7") && !version.startsWith("v1_8")) { - mc_packetPlayOutWorldParticlesClazz = Class.forName("net.minecraft.server." + version + ".Packet63WorldParticles"); - } else { - mc_packetPlayOutWorldParticlesClazz = Class.forName("net.minecraft.server." + version + ".PacketPlayOutWorldParticles"); - } - cb_craftPlayerClazz = Class.forName("org.bukkit.craftbukkit." + version + ".entity.CraftPlayer"); - cb_craftPlayer_getHandle = cb_craftPlayerClazz.getDeclaredMethod("getHandle"); - mc_entityPlayerClazz = Class.forName("net.minecraft.server." + version + ".EntityPlayer"); - mc_entityPlayer_playerConnection = mc_entityPlayerClazz.getDeclaredField("playerConnection"); - mc_playerConnectionClazz = Class.forName("net.minecraft.server." + version + ".PlayerConnection"); - mc_PacketInterface = Class.forName("net.minecraft.server." + version + ".Packet"); - mc_playerConnection_sendPacket = mc_playerConnectionClazz.getDeclaredMethod("sendPacket", mc_PacketInterface); - if (version.startsWith("v1_8")) { - // Aren't worrying about anything after 1.8 in this class here - mc_EnumParticle = Class.forName("net.minecraft.server." + version + ".EnumParticle"); - mc_EnumParticle_valueOf = mc_EnumParticle.getDeclaredMethod("valueOf", String.class); - } - } catch (Throwable ex) { - Logger.getAnonymousLogger().log(Level.WARNING, "Problem preparing particle packets (disabling further packets)", ex); - enabled = false; - } - } - - private static String getNMSVersion() { - String ver = Bukkit.getServer().getClass().getPackage().getName(); - return ver.substring(ver.lastIndexOf('.') + 1); - } - - public static void createParticle(Location l, Type e) { - createParticle(l, e, 0F, 0F, 0F, 1, 0, null); - } - - public static void createParticle(Location l, Type e, List localOnly) { - createParticle(l, e, 0F, 0F, 0F, 1, 0, localOnly); - } - - public static void createParticle(Location l, Type e, float effectSpeed, int amountOfParticles) { - createParticle(l, e, 0F, 0F, 0F, effectSpeed, amountOfParticles, null); - } - - /** - * @param l exact location to spawn the particle - * @param e particle effect type - * @param xx for notes, this is a value 0-1 for the color ([0-24]/24), for - * redstone this is the red value 0-1 ([0-255]/255). - * Otherwise this is the distance for particles to fly on the x-axis. - * @param yy for redstone this is the green value 0-1 ([0-255]/255) - * Otherwise this is the distance for particles to fly on the y-axis. - * @param zz for redstone this is the blue value 0-1 ([0-255]/255) - * Otherwise this is the distance for particles to fly on the z-axis. - * @param effectSpeed particle effect speed - * @param amountOfParticles extra particles to spawn (client-side) - * @param localOnly list of players to send the packets to, or null for all players - */ - public static void createParticle(Location l, Type e, float xx, float yy, float zz, float effectSpeed, int amountOfParticles, List localOnly) { - if (!enabled || e == null || effectSpeed < 0 || amountOfParticles < 0 - || !ServerVersion.isServerVersionAtLeast(e.minVersion) - || (e.maxVersion != null && !ServerVersion.isServerVersionBelow(e.maxVersion))) { - return; - } - final int rangeSquared = 256; // apparently there is no way to override this (unless to make smaller, of course) - // collect a list of players to send this packet to - List sendTo = new ArrayList(); - if (localOnly == null) { - for (Player p : l.getWorld().getPlayers()) { - if (p.getLocation().distanceSquared(l) <= rangeSquared) { - sendTo.add(p); - } - } - } else { - final World w = l.getWorld(); - for (Player p : localOnly) { - if (p.getWorld() == w && p.getLocation().distanceSquared(l) <= rangeSquared) { - sendTo.add(p); - } - } - } - if (sendTo.isEmpty()) { - return; - } - try { - // Make an instance of the packet! - Object sPacket = mc_packetPlayOutWorldParticlesClazz.newInstance(); - for (Field field : sPacket.getClass().getDeclaredFields()) { - // Set those fields we need to be accessible! - field.setAccessible(true); - final String fieldName = field.getName(); - // Set them to what we want! - if (fieldName.equals("a")) { - // we're just going to assume it's either 1.7 or 1.8 - if (version.startsWith("v1_8")) { - // 1.8 uses an Enum - field.set(sPacket, mc_EnumParticle_valueOf.invoke(null, e.name())); - } else { - field.set(sPacket, e.name); - } - } else if (fieldName.equals("b")) { - field.setFloat(sPacket, (float) l.getX()); // x - } else if (fieldName.equals("c")) { - field.setFloat(sPacket, (float) l.getY()); // y - } else if (fieldName.equals("d")) { - field.setFloat(sPacket, (float) l.getZ()); // z - } else if (fieldName.equals("e")) { - field.setFloat(sPacket, xx); // xOffset - } else if (fieldName.equals("f")) { - field.setFloat(sPacket, yy); // yOffset - } else if (fieldName.equals("g")) { - field.setFloat(sPacket, zz); // zOffset - } else if (fieldName.equals("h")) { - field.setFloat(sPacket, effectSpeed); - } else if (fieldName.equals("i")) { - field.setInt(sPacket, amountOfParticles); - } - /* - 1.8 also includes other data: - j = boolean, set if view distance is increased from 256 to 65536 - k = int[] for packet data (like block type for ITEM_CRACK) - */ - } - // send it on its way! - for (Player p : sendTo) { - sendPacket(sPacket, p); - } - } catch (Throwable ex) { - Logger.getAnonymousLogger().log(Level.WARNING, "Problem preparing a particle packet (disabling further packets)", ex); - enabled = false; - } - } - - private static void sendPacket(Object packet, Player to) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Object cbPlayer = cb_craftPlayer_getHandle.invoke(to); - Object mcConnection = mc_entityPlayer_playerConnection.get(cbPlayer); - mc_playerConnection_sendPacket.invoke(mcConnection, packet); - } -} +package com.songoda.core.compatibility; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Player; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Particle effects for servers 1.8 and below + * + * @author jascotty2 + * @since 2019-08-23 + */ +public class LegacyParticleEffects { + public static enum Type { + EXPLOSION_NORMAL("explode"), + EXPLOSION_LARGE("largeexplode"), + EXPLOSION_HUGE("hugeexplosion"), + FIREWORKS_SPARK("fireworksSpark"), + WATER_BUBBLE("bubble"), + WATER_SPLASH("splash"), + WATER_WAKE("wake", ServerVersion.V1_8), + SUSPENDED("suspended"), + SUSPENDED_DEPTH("depthsuspend"), + CRIT("crit"), + CRIT_MAGIC("magicCrit"), + SMOKE_NORMAL("smoke"), + SMOKE_LARGE("largesmoke"), + SPELL("spell"), + SPELL_INSTANT("instantSpell"), + SPELL_MOB("mobSpell"), + SPELL_MOB_AMBIENT("mobSpellAmbient"), + SPELL_WITCH("witchMagic"), + DRIP_WATER("dripWater"), + DRIP_LAVA("dripLava"), + VILLAGER_ANGRY("angryVillager"), + VILLAGER_HAPPY("happyVillager"), + TOWN_AURA("townaura"), + NOTE("note"), + PORTAL("portal"), + ENCHANTMENT_TABLE("enchantmenttable"), + FLAME("flame"), + LAVA("lava"), + FOOTSTEP("footstep"), + CLOUD("cloud"), + REDSTONE("reddust"), + SNOWBALL("snowballpoof"), + SNOW_SHOVEL("snowshovel"), + SLIME("slime"), + HEART("heart"), + BARRIER("barrier", ServerVersion.V1_8), + /** + * Used when a block is broken + */ + ITEM_CRACK("iconcrack_"), + BLOCK_CRACK("blockcrack_", ServerVersion.V1_8), + BLOCK_DUST("blockdust_", ServerVersion.V1_8), + WATER_DROP("droplet", ServerVersion.V1_8), + ITEM_TAKE("take", ServerVersion.V1_8), + MOB_APPEARANCE("mobappearance", ServerVersion.V1_8), + TOOL_BREAK("tilecrack_", ServerVersion.UNKNOWN, ServerVersion.V1_7); + + public final String name; + public final ServerVersion minVersion; + public final ServerVersion maxVersion; + + private Type(String name) { + this.name = name; + this.minVersion = ServerVersion.UNKNOWN; + this.maxVersion = null; + } + + private Type(String name, ServerVersion minVersion) { + this.name = name; + this.minVersion = minVersion; + this.maxVersion = null; + } + + private Type(String name, ServerVersion minVersion, ServerVersion maxVersion) { + this.name = name; + this.minVersion = minVersion; + this.maxVersion = maxVersion; + } + + public static Type getById(String id) { + for (Type t : Type.values()) { + if (t.name.equalsIgnoreCase(id) || t.name().equalsIgnoreCase(id)) { + return t; + } + } + return null; + } + } + + private static final String version = getNMSVersion(); + private static boolean enabled = true; + private static Class mc_packetPlayOutWorldParticlesClazz; + private static Class cb_craftPlayerClazz; + private static Method cb_craftPlayer_getHandle; + private static Class mc_entityPlayerClazz; + private static Class mc_playerConnectionClazz; + private static Field mc_entityPlayer_playerConnection; + private static Class mc_PacketInterface; + private static Method mc_playerConnection_sendPacket; + private static Class mc_EnumParticle; + private static Method mc_EnumParticle_valueOf; + + static { + try { + // lower versions use "Packet63WorldParticles" + if (!version.startsWith("v1_7") && !version.startsWith("v1_8")) { + mc_packetPlayOutWorldParticlesClazz = Class.forName("net.minecraft.server." + version + ".Packet63WorldParticles"); + } else { + mc_packetPlayOutWorldParticlesClazz = Class.forName("net.minecraft.server." + version + ".PacketPlayOutWorldParticles"); + } + cb_craftPlayerClazz = Class.forName("org.bukkit.craftbukkit." + version + ".entity.CraftPlayer"); + cb_craftPlayer_getHandle = cb_craftPlayerClazz.getDeclaredMethod("getHandle"); + mc_entityPlayerClazz = Class.forName("net.minecraft.server." + version + ".EntityPlayer"); + mc_entityPlayer_playerConnection = mc_entityPlayerClazz.getDeclaredField("playerConnection"); + mc_playerConnectionClazz = Class.forName("net.minecraft.server." + version + ".PlayerConnection"); + mc_PacketInterface = Class.forName("net.minecraft.server." + version + ".Packet"); + mc_playerConnection_sendPacket = mc_playerConnectionClazz.getDeclaredMethod("sendPacket", mc_PacketInterface); + if (version.startsWith("v1_8")) { + // Aren't worrying about anything after 1.8 in this class here + mc_EnumParticle = Class.forName("net.minecraft.server." + version + ".EnumParticle"); + mc_EnumParticle_valueOf = mc_EnumParticle.getDeclaredMethod("valueOf", String.class); + } + } catch (Throwable ex) { + Logger.getAnonymousLogger().log(Level.WARNING, "Problem preparing particle packets (disabling further packets)", ex); + enabled = false; + } + } + + private static String getNMSVersion() { + String ver = Bukkit.getServer().getClass().getPackage().getName(); + return ver.substring(ver.lastIndexOf('.') + 1); + } + + public static void createParticle(Location l, Type e) { + createParticle(l, e, 0F, 0F, 0F, 1, 0, null); + } + + public static void createParticle(Location l, Type e, List localOnly) { + createParticle(l, e, 0F, 0F, 0F, 1, 0, localOnly); + } + + public static void createParticle(Location l, Type e, float effectSpeed, int amountOfParticles) { + createParticle(l, e, 0F, 0F, 0F, effectSpeed, amountOfParticles, null); + } + + /** + * @param l exact location to spawn the particle + * @param e particle effect type + * @param xx for notes, this is a value 0-1 for the color ([0-24]/24), for + * redstone this is the red value 0-1 ([0-255]/255). + * Otherwise this is the distance for particles to fly on the x-axis. + * @param yy for redstone this is the green value 0-1 ([0-255]/255) + * Otherwise this is the distance for particles to fly on the y-axis. + * @param zz for redstone this is the blue value 0-1 ([0-255]/255) + * Otherwise this is the distance for particles to fly on the z-axis. + * @param effectSpeed particle effect speed + * @param amountOfParticles extra particles to spawn (client-side) + * @param localOnly list of players to send the packets to, or null for all players + */ + public static void createParticle(Location l, Type e, float xx, float yy, float zz, float effectSpeed, int amountOfParticles, List localOnly) { + if (!enabled || e == null || effectSpeed < 0 || amountOfParticles < 0 + || !ServerVersion.isServerVersionAtLeast(e.minVersion) + || (e.maxVersion != null && !ServerVersion.isServerVersionBelow(e.maxVersion))) { + return; + } + final int rangeSquared = 256; // apparently there is no way to override this (unless to make smaller, of course) + // collect a list of players to send this packet to + List sendTo = new ArrayList(); + if (localOnly == null) { + for (Player p : l.getWorld().getPlayers()) { + if (p.getLocation().distanceSquared(l) <= rangeSquared) { + sendTo.add(p); + } + } + } else { + final World w = l.getWorld(); + for (Player p : localOnly) { + if (p.getWorld() == w && p.getLocation().distanceSquared(l) <= rangeSquared) { + sendTo.add(p); + } + } + } + if (sendTo.isEmpty()) { + return; + } + try { + // Make an instance of the packet! + Object sPacket = mc_packetPlayOutWorldParticlesClazz.newInstance(); + for (Field field : sPacket.getClass().getDeclaredFields()) { + // Set those fields we need to be accessible! + field.setAccessible(true); + final String fieldName = field.getName(); + + // Set them to what we want! + if (fieldName.equals("a")) { + // we're just going to assume it's either 1.7 or 1.8 + if (version.startsWith("v1_8")) { + // 1.8 uses an Enum + field.set(sPacket, mc_EnumParticle_valueOf.invoke(null, e.name())); + } else { + field.set(sPacket, e.name); + } + } else if (fieldName.equals("b")) { + field.setFloat(sPacket, (float) l.getX()); // x + } else if (fieldName.equals("c")) { + field.setFloat(sPacket, (float) l.getY()); // y + } else if (fieldName.equals("d")) { + field.setFloat(sPacket, (float) l.getZ()); // z + } else if (fieldName.equals("e")) { + field.setFloat(sPacket, xx); // xOffset + } else if (fieldName.equals("f")) { + field.setFloat(sPacket, yy); // yOffset + } else if (fieldName.equals("g")) { + field.setFloat(sPacket, zz); // zOffset + } else if (fieldName.equals("h")) { + field.setFloat(sPacket, effectSpeed); + } else if (fieldName.equals("i")) { + field.setInt(sPacket, amountOfParticles); + } + /* + 1.8 also includes other data: + j = boolean, set if view distance is increased from 256 to 65536 + k = int[] for packet data (like block type for ITEM_CRACK) + */ + } + + // send it on its way! + for (Player p : sendTo) { + sendPacket(sPacket, p); + } + } catch (Throwable ex) { + Logger.getAnonymousLogger().log(Level.WARNING, "Problem preparing a particle packet (disabling further packets)", ex); + enabled = false; + } + } + + private static void sendPacket(Object packet, Player to) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Object cbPlayer = cb_craftPlayer_getHandle.invoke(to); + Object mcConnection = mc_entityPlayer_playerConnection.get(cbPlayer); + + mc_playerConnection_sendPacket.invoke(mcConnection, packet); + } +} diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyPotionEffects.java b/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyPotionEffects.java index fc8fc778..b96f9c8a 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyPotionEffects.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyPotionEffects.java @@ -1,50 +1,49 @@ -package com.songoda.core.compatibility; - -import org.bukkit.potion.PotionEffectType; - -import java.util.HashMap; -import java.util.Random; - -public class LegacyPotionEffects { - - private LegacyPotionEffects() { - } - - protected final static Random rand = new Random(); - - private final static HashMap potionEffectNames = new HashMap() { - { - put(PotionEffectType.SPEED.getId(), "Speed"); - put(PotionEffectType.SLOW.getId(), "Slowness"); - put(PotionEffectType.FAST_DIGGING.getId(), "Haste"); - put(PotionEffectType.SLOW_DIGGING.getId(), "Mining Fatigue"); - put(PotionEffectType.INCREASE_DAMAGE.getId(), "Strength"); - put(PotionEffectType.WEAKNESS.getId(), "Weakness"); - put(PotionEffectType.HEAL.getId(), "Instant Health"); - put(PotionEffectType.HARM.getId(), "Instant Damage"); - put(PotionEffectType.JUMP.getId(), "Jump Boost"); - put(PotionEffectType.CONFUSION.getId(), "Nausea"); - put(PotionEffectType.REGENERATION.getId(), "Regeneration"); - put(PotionEffectType.DAMAGE_RESISTANCE.getId(), "Resistance"); - put(PotionEffectType.FIRE_RESISTANCE.getId(), "Fire Resistance"); - put(PotionEffectType.WATER_BREATHING.getId(), "Water Breathing"); - put(PotionEffectType.INVISIBILITY.getId(), "Invisibility"); - put(PotionEffectType.BLINDNESS.getId(), "Blindness"); - put(PotionEffectType.NIGHT_VISION.getId(), "Night Vision"); - put(PotionEffectType.HUNGER.getId(), "Hunger"); - put(PotionEffectType.POISON.getId(), "Poison"); - put(PotionEffectType.WITHER.getId(), "Wither"); - put(PotionEffectType.HEALTH_BOOST.getId(), "Health Boost"); - put(PotionEffectType.ABSORPTION.getId(), "Absorption"); - put(PotionEffectType.SATURATION.getId(), "Saturation"); - } - }; - - public static String getEffectName(PotionEffectType e) { - if (e == null) { - return "null"; - } - final String n = potionEffectNames.get(e.getId()); - return n == null ? e.getName() : n; - } -} +package com.songoda.core.compatibility; + +import org.bukkit.potion.PotionEffectType; + +import java.util.HashMap; +import java.util.Random; + +public class LegacyPotionEffects { + private LegacyPotionEffects() { + } + + protected final static Random rand = new Random(); + + private final static HashMap potionEffectNames = new HashMap() { + { + put(PotionEffectType.SPEED.getId(), "Speed"); + put(PotionEffectType.SLOW.getId(), "Slowness"); + put(PotionEffectType.FAST_DIGGING.getId(), "Haste"); + put(PotionEffectType.SLOW_DIGGING.getId(), "Mining Fatigue"); + put(PotionEffectType.INCREASE_DAMAGE.getId(), "Strength"); + put(PotionEffectType.WEAKNESS.getId(), "Weakness"); + put(PotionEffectType.HEAL.getId(), "Instant Health"); + put(PotionEffectType.HARM.getId(), "Instant Damage"); + put(PotionEffectType.JUMP.getId(), "Jump Boost"); + put(PotionEffectType.CONFUSION.getId(), "Nausea"); + put(PotionEffectType.REGENERATION.getId(), "Regeneration"); + put(PotionEffectType.DAMAGE_RESISTANCE.getId(), "Resistance"); + put(PotionEffectType.FIRE_RESISTANCE.getId(), "Fire Resistance"); + put(PotionEffectType.WATER_BREATHING.getId(), "Water Breathing"); + put(PotionEffectType.INVISIBILITY.getId(), "Invisibility"); + put(PotionEffectType.BLINDNESS.getId(), "Blindness"); + put(PotionEffectType.NIGHT_VISION.getId(), "Night Vision"); + put(PotionEffectType.HUNGER.getId(), "Hunger"); + put(PotionEffectType.POISON.getId(), "Poison"); + put(PotionEffectType.WITHER.getId(), "Wither"); + put(PotionEffectType.HEALTH_BOOST.getId(), "Health Boost"); + put(PotionEffectType.ABSORPTION.getId(), "Absorption"); + put(PotionEffectType.SATURATION.getId(), "Saturation"); + } + }; + + public static String getEffectName(PotionEffectType e) { + if (e == null) { + return "null"; + } + final String n = potionEffectNames.get(e.getId()); + return n == null ? e.getName() : n; + } +} diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/ServerProject.java b/Compatibility/src/main/java/com/songoda/core/compatibility/ServerProject.java index da85c478..7b6fccac 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/ServerProject.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/ServerProject.java @@ -4,38 +4,43 @@ import org.apache.commons.lang.ArrayUtils; import org.bukkit.Bukkit; public enum ServerProject { - UNKNOWN, CRAFTBUKKIT, SPIGOT, PAPER, TACO, GLOWSTONE; private final static ServerProject serverProject = checkProject(); private static ServerProject checkProject() { String serverPath = Bukkit.getServer().getClass().getName(); + if (serverPath.contains("glowstone")) { return GLOWSTONE; } + // taco is pretty easy to check. it uses paper stuff, though, so should be checked first try { Class.forName("net.techcable.tacospigot.TacoSpigotConfig"); return TACO; - } catch (ClassNotFoundException ex) { + } catch (ClassNotFoundException ignore) { } + // paper used to be called "paperclip" try { Class.forName("com.destroystokyo.paperclip.Paperclip"); return PAPER; - } catch (ClassNotFoundException ex) { + } catch (ClassNotFoundException ignore) { } + try { Class.forName("com.destroystokyo.paper.PaperConfig"); return PAPER; - } catch (ClassNotFoundException ex) { + } catch (ClassNotFoundException ignore) { } + // spigot is the fork that pretty much all builds are based on anymore try { Class.forName("org.spigotmc.SpigotConfig"); return SPIGOT; - } catch (ClassNotFoundException ex) { + } catch (ClassNotFoundException ignore) { } + return serverPath.contains("craftbukkit") ? CRAFTBUKKIT : UNKNOWN; } diff --git a/Core/src/main/java/com/songoda/core/SongodaCore.java b/Core/src/main/java/com/songoda/core/SongodaCore.java index f353b8c3..f05ccea1 100644 --- a/Core/src/main/java/com/songoda/core/SongodaCore.java +++ b/Core/src/main/java/com/songoda/core/SongodaCore.java @@ -87,13 +87,14 @@ public class SongodaCore { for (Class clazz : Bukkit.getServicesManager().getKnownServices()) { if (clazz.getSimpleName().equals("SongodaCore")) { try { - // test to see if we're up to date + // test to see if we're up-to-date int otherVersion; try { otherVersion = (int) clazz.getMethod("getCoreVersion").invoke(null); } catch (Exception ignore) { otherVersion = -1; } + if (otherVersion >= getCoreVersion()) { // use the active service // assuming that the other is greater than R6 if we get here ;) @@ -104,49 +105,57 @@ public class SongodaCore { INSTANCE.shadingListener = new ShadedEventListener(); Bukkit.getPluginManager().registerEvents(INSTANCE.shadingListener, plugin); } + return; - } else { - // we are newer than the registered service: steal all of its registrations - // grab the old core's registrations - List otherPlugins = (List) clazz.getMethod("getPlugins").invoke(null); - // destroy the old core - Object oldCore = clazz.getMethod("getInstance").invoke(null); - Method destruct = clazz.getDeclaredMethod("destroy"); - destruct.setAccessible(true); - destruct.invoke(oldCore); - // register ourselves as the SongodaCore service! - INSTANCE = new SongodaCore(plugin); - INSTANCE.init(); - INSTANCE.register(plugin, pluginID, icon, coreVersion); - Bukkit.getServicesManager().register(SongodaCore.class, INSTANCE, plugin, ServicePriority.Normal); - // we need (JavaPlugin plugin, int pluginID, String icon) for our object - if (!otherPlugins.isEmpty()) { - Object testSubject = otherPlugins.get(0); - Class otherPluginInfo = testSubject.getClass(); - Method otherPluginInfo_getJavaPlugin = otherPluginInfo.getMethod("getJavaPlugin"); - Method otherPluginInfo_getSongodaId = otherPluginInfo.getMethod("getSongodaId"); - Method otherPluginInfo_getCoreIcon = otherPluginInfo.getMethod("getCoreIcon"); - Method otherPluginInfo_getCoreLibraryVersion = otherVersion >= 6 ? otherPluginInfo.getMethod("getCoreLibraryVersion") : null; - for (Object other : otherPlugins) { - INSTANCE.register( - (JavaPlugin) otherPluginInfo_getJavaPlugin.invoke(other), - (int) otherPluginInfo_getSongodaId.invoke(other), - (String) otherPluginInfo_getCoreIcon.invoke(other), - otherPluginInfo_getCoreLibraryVersion != null ? (String) otherPluginInfo_getCoreLibraryVersion.invoke(other) : "?"); - } + } + + // we are newer than the registered service: steal all of its registrations + // grab the old core's registrations + List otherPlugins = (List) clazz.getMethod("getPlugins").invoke(null); + + // destroy the old core + Object oldCore = clazz.getMethod("getInstance").invoke(null); + Method destruct = clazz.getDeclaredMethod("destroy"); + destruct.setAccessible(true); + destruct.invoke(oldCore); + + // register ourselves as the SongodaCore service! + INSTANCE = new SongodaCore(plugin); + INSTANCE.init(); + INSTANCE.register(plugin, pluginID, icon, coreVersion); + Bukkit.getServicesManager().register(SongodaCore.class, INSTANCE, plugin, ServicePriority.Normal); + + // we need (JavaPlugin plugin, int pluginID, String icon) for our object + if (!otherPlugins.isEmpty()) { + Object testSubject = otherPlugins.get(0); + Class otherPluginInfo = testSubject.getClass(); + Method otherPluginInfo_getJavaPlugin = otherPluginInfo.getMethod("getJavaPlugin"); + Method otherPluginInfo_getSongodaId = otherPluginInfo.getMethod("getSongodaId"); + Method otherPluginInfo_getCoreIcon = otherPluginInfo.getMethod("getCoreIcon"); + Method otherPluginInfo_getCoreLibraryVersion = otherVersion >= 6 ? otherPluginInfo.getMethod("getCoreLibraryVersion") : null; + + for (Object other : otherPlugins) { + INSTANCE.register( + (JavaPlugin) otherPluginInfo_getJavaPlugin.invoke(other), + (int) otherPluginInfo_getSongodaId.invoke(other), + (String) otherPluginInfo_getCoreIcon.invoke(other), + otherPluginInfo_getCoreLibraryVersion != null ? (String) otherPluginInfo_getCoreLibraryVersion.invoke(other) : "?"); } } + return; - } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ignored) { - plugin.getLogger().log(Level.WARNING, "Error registering core service", ignored); + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) { + plugin.getLogger().log(Level.WARNING, "Error registering core service", ex); } } } + // register ourselves as the SongodaCore service! INSTANCE = new SongodaCore(plugin); INSTANCE.init(); Bukkit.getServicesManager().register(SongodaCore.class, INSTANCE, plugin, ServicePriority.Normal); } + INSTANCE.register(plugin, pluginID, icon, coreVersion); } @@ -166,6 +175,7 @@ public class SongodaCore { .addSubCommand(new SongodaCoreDiagCommand()); Bukkit.getPluginManager().registerEvents(loginListener, piggybackedPlugin); Bukkit.getPluginManager().registerEvents(shadingListener, piggybackedPlugin); + // we aggressively want to own this command tasks.add(Bukkit.getScheduler().runTaskLaterAsynchronously(piggybackedPlugin, () -> { CommandManager.registerCommandDynamically(piggybackedPlugin, "songoda", commandManager, commandManager); @@ -183,12 +193,15 @@ public class SongodaCore { */ private void destroy() { Bukkit.getServicesManager().unregister(SongodaCore.class, INSTANCE); + tasks.stream().filter(Objects::nonNull) .forEach(task -> Bukkit.getScheduler().cancelTask(task.getTaskId())); + HandlerList.unregisterAll(loginListener); if (!hasShading()) { HandlerList.unregisterAll(shadingListener); } + registeredPlugins.clear(); commandManager = null; loginListener = null; @@ -199,6 +212,7 @@ public class SongodaCore { private void register(JavaPlugin plugin, int pluginID, String icon, String libraryVersion) { logger.info(getPrefix() + "Hooked " + plugin.getName() + "."); PluginInfo info = new PluginInfo(plugin, pluginID, icon, libraryVersion); + // don't forget to check for language pack updates ;) info.addModule(new LocaleModule()); registeredPlugins.add(info); @@ -238,10 +252,10 @@ public class SongodaCore { for (PluginInfoModule module : plugin.getModules()) { module.run(plugin); } - } catch (IOException e) { - final String er = e.getMessage(); + } catch (IOException ex) { + final String er = ex.getMessage(); logger.log(Level.FINE, "Connection with Songoda servers failed: " + (er.contains("URL") ? er.substring(0, er.indexOf("URL") + 3) : er)); - } catch (ParseException e) { + } catch (ParseException ex) { logger.log(Level.FINE, "Failed to parse json for " + plugin.getJavaPlugin().getName() + " update check"); } } @@ -287,9 +301,15 @@ public class SongodaCore { boolean proto = false; ShadedEventListener() { - if ((via = Bukkit.getPluginManager().isPluginEnabled("ViaVersion"))) { + via = Bukkit.getPluginManager().isPluginEnabled("ViaVersion"); + + if (via) { Bukkit.getOnlinePlayers().forEach(p -> ClientVersion.onLoginVia(p, getHijackedPlugin())); - } else if ((proto = Bukkit.getPluginManager().isPluginEnabled("ProtocolSupport"))) { + return; + } + + proto = Bukkit.getPluginManager().isPluginEnabled("ProtocolSupport"); + if (proto) { Bukkit.getOnlinePlayers().forEach(p -> ClientVersion.onLoginProtocol(p, getHijackedPlugin())); } } @@ -298,7 +318,10 @@ public class SongodaCore { void onLogin(PlayerLoginEvent event) { if (via) { ClientVersion.onLoginVia(event.getPlayer(), getHijackedPlugin()); - } else if (proto) { + return; + } + + if (proto) { ClientVersion.onLoginProtocol(event.getPlayer(), getHijackedPlugin()); } } @@ -327,13 +350,20 @@ public class SongodaCore { @EventHandler void onLogin(PlayerLoginEvent event) { final Player player = event.getPlayer(); + // don't spam players with update checks long now = System.currentTimeMillis(); Long last = lastCheck.get(player.getUniqueId()); - if (last != null && now - 10000 < last) return; + + if (last != null && now - 10000 < last) { + return; + } + lastCheck.put(player.getUniqueId(), now); + // is this player good to revieve update notices? if (!event.getPlayer().isOp() && !player.hasPermission("songoda.updatecheck")) return; + // check for updates! ;) for (PluginInfo plugin : getPlugins()) { if (plugin.getNotification() != null && plugin.getJavaPlugin().isEnabled()) @@ -346,16 +376,20 @@ public class SongodaCore { void onDisable(PluginDisableEvent event) { // don't track disabled plugins PluginInfo pi = registeredPlugins.stream().filter(p -> event.getPlugin() == p.getJavaPlugin()).findFirst().orElse(null); + if (pi != null) { registeredPlugins.remove(pi); } + if (event.getPlugin() == piggybackedPlugin) { // uh-oh! Abandon ship!! Bukkit.getServicesManager().unregisterAll(piggybackedPlugin); + // can we move somewhere else? if ((pi = registeredPlugins.stream().findFirst().orElse(null)) != null) { // move ourselves to this plugin piggybackedPlugin = pi.getJavaPlugin(); + Bukkit.getServicesManager().register(SongodaCore.class, INSTANCE, piggybackedPlugin, ServicePriority.Normal); Bukkit.getPluginManager().registerEvents(loginListener, piggybackedPlugin); Bukkit.getPluginManager().registerEvents(shadingListener, piggybackedPlugin); diff --git a/Core/src/main/java/com/songoda/core/SongodaPlugin.java b/Core/src/main/java/com/songoda/core/SongodaPlugin.java index de953492..9fa5757c 100644 --- a/Core/src/main/java/com/songoda/core/SongodaPlugin.java +++ b/Core/src/main/java/com/songoda/core/SongodaPlugin.java @@ -78,6 +78,7 @@ public abstract class SongodaPlugin extends JavaPlugin { + " v" + getDescription().getVersion() + " c" + SongodaCore.getCoreLibraryVersion() + ": Disabling plugin!", t); + emergencyStop = true; } } @@ -86,6 +87,7 @@ public abstract class SongodaPlugin extends JavaPlugin { public final void onEnable() { if (emergencyStop) { setEnabled(false); + return; } @@ -98,26 +100,33 @@ public abstract class SongodaPlugin extends JavaPlugin { try { locale = Locale.loadDefaultLocale(this, "en_US"); + // plugin setup onPluginEnable(); + // Load Data. Bukkit.getScheduler().runTaskLater(this, this::onDataLoad, dataLoadDelay); + if (emergencyStop) { console.sendMessage(ChatColor.RED + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); console.sendMessage(" "); return; } + // Start Metrics Metrics.start(this); - } catch (Throwable t) { + } catch (Throwable th) { Bukkit.getLogger().log(Level.SEVERE, "Unexpected error while loading " + getDescription().getName() + " v" + getDescription().getVersion() + " c" + SongodaCore.getCoreLibraryVersion() - + ": Disabling plugin!", t); + + ": Disabling plugin!", th); + emergencyStop(); + console.sendMessage(ChatColor.RED + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); console.sendMessage(" "); + return; } @@ -127,6 +136,7 @@ public abstract class SongodaPlugin extends JavaPlugin { protected void emergencyStop() { emergencyStop = true; + Bukkit.getPluginManager().disablePlugin(this); } @@ -135,13 +145,16 @@ public abstract class SongodaPlugin extends JavaPlugin { if (emergencyStop) { return; } + console.sendMessage(" "); // blank line to speparate chatter console.sendMessage(ChatColor.GREEN + "============================="); console.sendMessage(String.format("%s%s %s by %sSongoda <3!", ChatColor.GRAY.toString(), getDescription().getName(), getDescription().getVersion(), ChatColor.DARK_PURPLE.toString())); console.sendMessage(String.format("%sAction: %s%s%s...", ChatColor.GRAY.toString(), ChatColor.RED.toString(), "Disabling", ChatColor.GRAY.toString())); + onPluginDisable(); + console.sendMessage(ChatColor.GREEN + "============================="); console.sendMessage(" "); // blank line to speparate chatter } @@ -166,15 +179,15 @@ public abstract class SongodaPlugin extends JavaPlugin { public boolean setLocale(String localeName, boolean reload) { if (locale != null && locale.getName().equals(localeName)) { return !reload || locale.reloadMessages(); - } else { - Locale l = Locale.loadLocale(this, localeName); - if (l != null) { - locale = l; - return true; - } else { - return false; - } } + + Locale l = Locale.loadLocale(this, localeName); + if (l != null) { + locale = l; + return true; + } + + return false; } protected void shutdownDataManager(DataManagerAbstract dataManager) { diff --git a/Core/src/main/java/com/songoda/core/chat/ChatMessage.java b/Core/src/main/java/com/songoda/core/chat/ChatMessage.java index 9fb20b41..c97d52e0 100644 --- a/Core/src/main/java/com/songoda/core/chat/ChatMessage.java +++ b/Core/src/main/java/com/songoda/core/chat/ChatMessage.java @@ -23,7 +23,6 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; public class ChatMessage { - private static final Gson gson = new GsonBuilder().create(); private final List textList = new ArrayList<>(); @@ -36,7 +35,8 @@ public class ChatMessage { } public ChatMessage fromText(String text, boolean noHex) { - Pattern pattern = Pattern.compile("(.*?)(?!&([omnlk]))(?=(&([123456789abcdefr#])|$)|#([a-f]|[A-F]|[0-9]){6})", + Pattern pattern = Pattern.compile( + "(.*?)(?!&([omnlk]))(?=(&([123456789abcdefr#])|$)|#([a-f]|[A-F]|[0-9]){6})", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(text); @@ -44,12 +44,15 @@ public class ChatMessage { ColorContainer color = null; String match1 = matcher.group(1); - if (matcher.groupCount() == 0 || match1.length() == 0) continue; + if (matcher.groupCount() == 0 || match1.length() == 0) { + continue; + } char colorChar = '-'; - if (matcher.start() != 0) + if (matcher.start() != 0) { colorChar = text.substring(matcher.start() - 1, matcher.start()).charAt(0); + } if (colorChar != '-') { if (colorChar == '#') { @@ -70,15 +73,17 @@ public class ChatMessage { ColorCode code = ColorCode.getByChar(Character.toLowerCase(match2.charAt(0))); - if (code != null && code != ColorCode.RESET) + if (code != null && code != ColorCode.RESET) { stackedCodes.add(code); + } - if (color != null) + if (color != null) { match2 = match2.substring(1); + } - if (match2.length() == 0) continue; - - addMessage(match2, color, stackedCodes); + if (match2.length() != 0) { + addMessage(match2, color, stackedCodes); + } } } @@ -91,31 +96,40 @@ public class ChatMessage { public String toText(boolean noHex) { StringBuilder text = new StringBuilder(); + for (JsonObject object : textList) { if (object.has("color")) { String color = object.get("color").getAsString(); text.append("&"); + if (color.length() == 7) { text.append(new ColorContainer(color, noHex).getColor().getCode()); } else { text.append(ColorCode.valueOf(color.toUpperCase()).getCode()); } } + for (ColorCode code : ColorCode.values()) { if (code.isColor()) continue; + String c = code.name().toLowerCase(); - if (object.has(c) && object.get(c).getAsBoolean()) + if (object.has(c) && object.get(c).getAsBoolean()) { text.append("&").append(code.getCode()); + } } + text.append(object.get("text").getAsString()); } + return text.toString(); } public ChatMessage addMessage(String s) { JsonObject txt = new JsonObject(); txt.addProperty("text", s); + textList.add(txt); + return this; } @@ -127,11 +141,14 @@ public class ChatMessage { JsonObject txt = new JsonObject(); txt.addProperty("text", text); - if (color != null) + if (color != null) { txt.addProperty("color", color.getHexCode() != null ? "#" + color.getHexCode() : color.getColorCode().name().toLowerCase()); + } + for (ColorCode code : ColorCode.values()) { - if (!code.isColor()) + if (!code.isColor()) { txt.addProperty(code.name().toLowerCase(), colorCodes.contains(code)); + } } textList.add(txt); @@ -141,14 +158,17 @@ public class ChatMessage { public ChatMessage addRunCommand(String text, String hoverText, String cmd) { JsonObject txt = new JsonObject(); txt.addProperty("text", text); + JsonObject hover = new JsonObject(); hover.addProperty("action", "show_text"); hover.addProperty("value", hoverText); txt.add("hoverEvent", hover); + JsonObject click = new JsonObject(); click.addProperty("action", "run_command"); click.addProperty("value", cmd); txt.add("clickEvent", click); + textList.add(txt); return this; } @@ -156,14 +176,17 @@ public class ChatMessage { public ChatMessage addPromptCommand(String text, String hoverText, String cmd) { JsonObject txt = new JsonObject(); txt.addProperty("text", text); + JsonObject hover = new JsonObject(); hover.addProperty("action", "show_text"); hover.addProperty("value", hoverText); txt.add("hoverEvent", hover); + JsonObject click = new JsonObject(); click.addProperty("action", "suggest_command"); click.addProperty("value", cmd); txt.add("clickEvent", click); + textList.add(txt); return this; } @@ -171,14 +194,17 @@ public class ChatMessage { public ChatMessage addURL(String text, String hoverText, String url) { JsonObject txt = new JsonObject(); txt.addProperty("text", text); + JsonObject hover = new JsonObject(); hover.addProperty("action", "show_text"); hover.addProperty("value", hoverText); txt.add("hoverEvent", hover); + JsonObject click = new JsonObject(); click.addProperty("action", "open_url"); click.addProperty("value", url); txt.add("clickEvent", hover); + textList.add(txt); return this; } @@ -200,10 +226,14 @@ public class ChatMessage { Object packet; if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_16)) { - packet = mc_PacketPlayOutChat_new.newInstance(mc_IChatBaseComponent_ChatSerializer_a.invoke(null, gson.toJson(textList)), mc_chatMessageType_Chat.get(null), ((Player) sender).getUniqueId()); + packet = mc_PacketPlayOutChat_new.newInstance( + mc_IChatBaseComponent_ChatSerializer_a.invoke(null, gson.toJson(textList)), + mc_chatMessageType_Chat.get(null), + ((Player) sender).getUniqueId()); } else { packet = mc_PacketPlayOutChat_new.newInstance(mc_IChatBaseComponent_ChatSerializer_a.invoke(null, gson.toJson(textList))); } + Object cbPlayer = cb_craftPlayer_getHandle.invoke(sender); Object mcConnection = mc_entityPlayer_playerConnection.get(cbPlayer); mc_playerConnection_sendPacket.invoke(mcConnection, packet); @@ -211,9 +241,11 @@ public class ChatMessage { Bukkit.getLogger().log(Level.WARNING, "Problem preparing raw chat packets (disabling further packets)", ex); enabled = false; } - } else { - sender.sendMessage(TextUtils.formatText((prefix == null ? "" : prefix.toText(true) + " ") + toText(true))); + + return; } + + sender.sendMessage(TextUtils.formatText((prefix == null ? "" : prefix.toText(true) + " ") + toText(true))); } private static boolean enabled = ServerVersion.isServerVersionAtLeast(ServerVersion.V1_8); @@ -230,7 +262,6 @@ public class ChatMessage { static void init() { if (enabled) { try { - final String version = ServerVersion.getServerVersionString(); Class cb_craftPlayerClazz, mc_entityPlayerClazz, mc_playerConnectionClazz, mc_PacketInterface, mc_IChatBaseComponent, mc_IChatBaseComponent_ChatSerializer, mc_PacketPlayOutChat; @@ -263,11 +294,12 @@ public class ChatMessage { public ChatMessage replaceAll(String toReplace, String replaceWith) { for (JsonObject object : textList) { - String text = object.get("text").getAsString() - .replaceAll(toReplace, replaceWith); + String text = object.get("text").getAsString().replaceAll(toReplace, replaceWith); + object.remove("text"); object.addProperty("text", text); } + return this; } } diff --git a/Core/src/main/java/com/songoda/core/chat/ColorCode.java b/Core/src/main/java/com/songoda/core/chat/ColorCode.java index 43ae8da9..b6b1d299 100644 --- a/Core/src/main/java/com/songoda/core/chat/ColorCode.java +++ b/Core/src/main/java/com/songoda/core/chat/ColorCode.java @@ -6,7 +6,6 @@ import java.util.HashMap; import java.util.Map; public enum ColorCode { - BLACK('0', ChatColor.BLACK, true), DARK_BLUE('1', ChatColor.DARK_BLUE, true), DARK_GREEN('2', ChatColor.DARK_GREEN, true), diff --git a/Core/src/main/java/com/songoda/core/chat/ColorContainer.java b/Core/src/main/java/com/songoda/core/chat/ColorContainer.java index 92b77b61..634af954 100644 --- a/Core/src/main/java/com/songoda/core/chat/ColorContainer.java +++ b/Core/src/main/java/com/songoda/core/chat/ColorContainer.java @@ -3,10 +3,9 @@ package com.songoda.core.chat; import com.songoda.core.compatibility.ServerVersion; import com.songoda.core.utils.ColorUtils; -import java.awt.Color; +import java.awt.*; public class ColorContainer { - private ColorCode colorCode; private String hexCode; @@ -17,6 +16,7 @@ public class ColorContainer { public ColorContainer(String hexCode, boolean noHex) { this.hexCode = hexCode; + if (noHex || ServerVersion.isServerVersionBelow(ServerVersion.V1_16)) { this.colorCode = getColor(); this.hexCode = null; @@ -32,12 +32,19 @@ public class ColorContainer { } public ColorCode getColor() { - if (colorCode != null) return colorCode; - if (hexCode == null) return null; + if (colorCode != null) { + return colorCode; + } + + if (hexCode == null) { + return null; + } + java.awt.Color jColor = new Color( Integer.valueOf(hexCode.substring(0, 2), 16), Integer.valueOf(hexCode.substring(2, 4), 16), Integer.valueOf(hexCode.substring(4, 6), 16)); + return ColorUtils.fromRGB(jColor.getRed(), jColor.getGreen(), jColor.getBlue()); } } diff --git a/Core/src/main/java/com/songoda/core/commands/AbstractCommand.java b/Core/src/main/java/com/songoda/core/commands/AbstractCommand.java index da0fc9d2..2a2d17aa 100644 --- a/Core/src/main/java/com/songoda/core/commands/AbstractCommand.java +++ b/Core/src/main/java/com/songoda/core/commands/AbstractCommand.java @@ -8,7 +8,6 @@ import java.util.Collections; import java.util.List; public abstract class AbstractCommand { - private final CommandType _cmdType; private final boolean _hasArgs; private final List _handledCommands = new ArrayList<>(); diff --git a/Core/src/main/java/com/songoda/core/commands/CommandManager.java b/Core/src/main/java/com/songoda/core/commands/CommandManager.java index a21d1c1d..fc801c1b 100644 --- a/Core/src/main/java/com/songoda/core/commands/CommandManager.java +++ b/Core/src/main/java/com/songoda/core/commands/CommandManager.java @@ -28,7 +28,6 @@ import java.util.Set; import java.util.stream.Collectors; public class CommandManager implements CommandExecutor, TabCompleter { - private final JavaPlugin plugin; private final HashMap commands = new HashMap<>(); @@ -68,19 +67,27 @@ public class CommandManager implements CommandExecutor, TabCompleter { public List getSubCommands(String command) { SimpleNestedCommand nested = command == null ? null : commands.get(command.toLowerCase()); - return nested == null ? Collections.emptyList() : new ArrayList<>(nested.children.keySet()); + + if (nested == null) { + return Collections.emptyList(); + } + + return new ArrayList<>(nested.children.keySet()); } public Set getAllCommands() { HashSet all = new HashSet<>(); + commands.values().stream() .filter(c -> c.parent != null && !all.contains(c.parent)) .forEach(c -> { all.add(c.parent); + c.children.values().stream() .filter(s -> !all.contains(s)) .forEach(s -> all.add(s)); }); + return all; } @@ -91,10 +98,12 @@ public class CommandManager implements CommandExecutor, TabCompleter { public SimpleNestedCommand registerCommandDynamically(AbstractCommand abstractCommand) { SimpleNestedCommand nested = new SimpleNestedCommand(abstractCommand); + abstractCommand.getCommands().forEach(cmd -> { CommandManager.registerCommandDynamically(plugin, cmd, this, this); commands.put(cmd.toLowerCase(), nested); PluginCommand pcmd = plugin.getCommand(cmd); + if (pcmd != null) { pcmd.setExecutor(this); pcmd.setTabCompleter(this); @@ -102,21 +111,26 @@ public class CommandManager implements CommandExecutor, TabCompleter { plugin.getLogger().warning("Failed to register command: /" + cmd); } }); + return nested; } public SimpleNestedCommand addCommand(AbstractCommand abstractCommand) { SimpleNestedCommand nested = new SimpleNestedCommand(abstractCommand); + abstractCommand.getCommands().forEach(cmd -> { commands.put(cmd.toLowerCase(), nested); PluginCommand pcmd = plugin.getCommand(cmd); - if (pcmd != null) { - pcmd.setExecutor(this); - pcmd.setTabCompleter(this); - } else { + + if (pcmd == null) { plugin.getLogger().warning("Failed to register command: /" + cmd); + return; } + + pcmd.setExecutor(this); + pcmd.setTabCompleter(this); }); + return nested; } @@ -137,9 +151,11 @@ public class CommandManager implements CommandExecutor, TabCompleter { public MainCommand getMainCommand(String command) { SimpleNestedCommand nested = command == null ? null : commands.get(command.toLowerCase()); + if (nested != null && nested.parent instanceof MainCommand) { return (MainCommand) nested.parent; } + return null; } @@ -147,16 +163,19 @@ public class CommandManager implements CommandExecutor, TabCompleter { for (AbstractCommand abstractCommand : abstractCommands) { addCommand(abstractCommand); } + return this; } public CommandManager setExecutor(String command) { PluginCommand pcmd = command == null ? null : plugin.getCommand(command); + if (pcmd != null) { pcmd.setExecutor(this); } else { plugin.getLogger().warning("Failed to register command: /" + command); } + return this; } @@ -169,28 +188,34 @@ public class CommandManager implements CommandExecutor, TabCompleter { public boolean onCommand(CommandSender commandSender, Command command, String label, String[] args) { // grab the specific command that's being called SimpleNestedCommand nested = commands.get(command.getName().toLowerCase()); + if (nested != null) { // check to see if we're trying to call a sub-command if (args.length != 0 && !nested.children.isEmpty()) { String subCmd = getSubCommand(nested, args); + if (subCmd != null) { // we have a subcommand to use! AbstractCommand sub = nested.children.get(subCmd); + // adjust the arguments to match - BREAKING!! int i = subCmd.indexOf(' ') == -1 ? 1 : 2; String[] newArgs = new String[args.length - i]; System.arraycopy(args, i, newArgs, 0, newArgs.length); + // now process the command processRequirements(sub, commandSender, newArgs); return true; } } + // if we've gotten this far, then just use the command we have if (nested.parent != null) { processRequirements(nested.parent, commandSender, args); return true; } } + commandSender.sendMessage(msg_noCommand); return true; } @@ -227,6 +252,7 @@ public class CommandManager implements CommandExecutor, TabCompleter { } } } + return match; } @@ -235,17 +261,24 @@ public class CommandManager implements CommandExecutor, TabCompleter { sender.sendMessage(msg_noConsole); return; } + if (command.getPermissionNode() == null || sender.hasPermission(command.getPermissionNode())) { AbstractCommand.ReturnType returnType = command.runCommand(sender, args); + if (returnType == AbstractCommand.ReturnType.NEEDS_PLAYER) { sender.sendMessage(msg_noConsole); - } else if (returnType == AbstractCommand.ReturnType.SYNTAX_ERROR) { + return; + } + + if (returnType == AbstractCommand.ReturnType.SYNTAX_ERROR) { for (String s : msg_syntaxError) { sender.sendMessage(s.replace("%syntax%", command.getSyntax())); } } + return; } + sender.sendMessage(msg_noPerms); } @@ -253,10 +286,12 @@ public class CommandManager implements CommandExecutor, TabCompleter { public List onTabComplete(CommandSender sender, Command command, String alias, String[] args) { // grab the specific command that's being called SimpleNestedCommand nested = commands.get(command.getName().toLowerCase()); + if (nested != null) { if (args.length == 0 || nested.children.isEmpty()) { return nested.parent != null ? nested.parent.onTab(sender, args) : null; } + // check for each sub-command that they have access to final boolean op = sender.isOp(); final boolean console = !(sender instanceof Player); @@ -269,42 +304,47 @@ public class CommandManager implements CommandExecutor, TabCompleter { .filter(e -> op || e.getValue().getPermissionNode() == null || sender.hasPermission(e.getValue().getPermissionNode())) .map(e -> e.getKey()) .collect(Collectors.toList()); - } else { - // more than one arg, let's check to see if we have a command here - String subCmd = getSubCommand(nested, args); - AbstractCommand sub; - if (subCmd != null && (sub = nested.children.get(subCmd)) != null - && (!console || !sub.isNoConsole()) - && (op || sub.getPermissionNode() == null || sender.hasPermission(sub.getPermissionNode()))) { - // adjust the arguments to match - BREAKING!! - int i = subCmd.indexOf(' ') == -1 ? 1 : 2; - String[] newArgs = new String[args.length - i]; - System.arraycopy(args, i, newArgs, 0, newArgs.length); - // we're good to go! - return fetchList(sub, newArgs, sender); - } + } + + // more than one arg, let's check to see if we have a command here + String subCmd = getSubCommand(nested, args); + AbstractCommand sub; + if (subCmd != null && + (sub = nested.children.get(subCmd)) != null && + (!console || !sub.isNoConsole()) && + (op || sub.getPermissionNode() == null || sender.hasPermission(sub.getPermissionNode()))) { + // adjust the arguments to match - BREAKING!! + int i = subCmd.indexOf(' ') == -1 ? 1 : 2; + String[] newArgs = new String[args.length - i]; + System.arraycopy(args, i, newArgs, 0, newArgs.length); + + // we're good to go! + return fetchList(sub, newArgs, sender); } } + return Collections.emptyList(); } private List fetchList(AbstractCommand abstractCommand, String[] args, CommandSender sender) { List list = abstractCommand.onTab(sender, args); + if (args.length != 0) { String str = args[args.length - 1]; + if (list != null && str != null && str.length() >= 1) { try { list.removeIf(s -> !s.toLowerCase().startsWith(str.toLowerCase())); - } catch (UnsupportedOperationException ignored) { + } catch (UnsupportedOperationException ignore) { } } } + return list; } public static void registerCommandDynamically(Plugin plugin, String command, CommandExecutor executor, TabCompleter tabManager) { try { - // Retrieve the SimpleCommandMap from the server Class clazzCraftServer = Bukkit.getServer().getClass(); Object craftServer = clazzCraftServer.cast(Bukkit.getServer()); @@ -337,8 +377,8 @@ public class CommandManager implements CommandExecutor, TabCompleter { fieldKnownCommands.setAccessible(true); Map knownCommands = (Map) fieldKnownCommands.get(commandMap); knownCommands.put(command, commandObject); - } catch (ReflectiveOperationException e) { - e.printStackTrace(); + } catch (ReflectiveOperationException ex) { + ex.printStackTrace(); } } diff --git a/Core/src/main/java/com/songoda/core/commands/MainCommand.java b/Core/src/main/java/com/songoda/core/commands/MainCommand.java index a8bbf3f8..21aa99a4 100644 --- a/Core/src/main/java/com/songoda/core/commands/MainCommand.java +++ b/Core/src/main/java/com/songoda/core/commands/MainCommand.java @@ -12,7 +12,6 @@ import java.util.List; import java.util.stream.Collectors; public class MainCommand extends AbstractCommand { - String header = null; String description; boolean sortHelp = false; @@ -22,6 +21,7 @@ public class MainCommand extends AbstractCommand { public MainCommand(Plugin plugin, String command) { super(CommandType.CONSOLE_OK, command); + this.command = command; this.plugin = plugin; this.description = "Shows the command help page for /" + command; @@ -56,6 +56,7 @@ public class MainCommand extends AbstractCommand { @Override protected ReturnType runCommand(CommandSender sender, String... args) { sender.sendMessage(""); + if (header != null) { sender.sendMessage(header); } else { @@ -63,17 +64,21 @@ public class MainCommand extends AbstractCommand { plugin.getDescription().getName(), plugin.getDescription().getVersion()), sender instanceof ConsoleCommandSender) .sendTo(sender); } + sender.sendMessage(ChatColor.DARK_GRAY + "- " + ChatColor.YELLOW + "/songoda" + ChatColor.GRAY + " - Opens the Songoda plugin GUI"); sender.sendMessage(""); if (nestedCommands != null) { List commands = nestedCommands.children.values().stream().distinct().map(c -> c.getCommands().get(0)).collect(Collectors.toList()); + if (sortHelp) { Collections.sort(commands); } + boolean isPlayer = sender instanceof Player; // todo? pagation if commands.size is too large? (player-only) sender.sendMessage(ChatColor.DARK_GRAY + "- " + ChatColor.YELLOW + getSyntax() + ChatColor.GRAY + " - " + getDescription()); + for (String cmdStr : commands) { final AbstractCommand cmd = nestedCommands.children.get(cmdStr); if (cmd == null) continue; diff --git a/Core/src/main/java/com/songoda/core/commands/SelectorArguments.java b/Core/src/main/java/com/songoda/core/commands/SelectorArguments.java index e8d57a1e..3f201da9 100644 --- a/Core/src/main/java/com/songoda/core/commands/SelectorArguments.java +++ b/Core/src/main/java/com/songoda/core/commands/SelectorArguments.java @@ -20,7 +20,6 @@ import java.util.stream.Collectors; import java.util.stream.Stream; public class SelectorArguments { - static Pattern selectorPattern = Pattern.compile("^(@[apers])(\\[(.*?)\\])?$"); static Pattern selectorRangePattern = Pattern.compile("^([0-9]{1,9}(\\.[0-9]{1,9})?)?(\\.\\.)?([0-9]{1,9}(\\.[0-9]{1,9})?)?$"); @@ -38,14 +37,17 @@ public class SelectorArguments { if (!(sender instanceof BlockCommandSender || sender instanceof Player)) { return null; } + Matcher m = selectorPattern.matcher(argument); if (!m.find()) { return null; } + SelectorType type = SelectorType.getType(m.group(1)); if (type == null) { return null; } + SelectorArguments selector = new SelectorArguments(sender, type); if (m.group(3) != null) { @@ -67,9 +69,11 @@ public class SelectorArguments { private void parseArguments(String selectorArgs) { String[] args = selectorArgs.split(","); + for (String s : args) { if (s.contains("=")) { String[] v = s.split("="); + if (v[0].equals("distance")) { // 10 = d == 10 // 10..12 = d > 10 && d <= 12 @@ -80,6 +84,7 @@ public class SelectorArguments { if (distGroup.group(1) != null) { rangeMin = Double.parseDouble(distGroup.group(1)); } + if (distGroup.group(3) == null) { rangeMax = rangeMin; } else if (distGroup.group(4) != null) { @@ -89,9 +94,11 @@ public class SelectorArguments { } else if (v[0].equals("type")) { entityType = EntityNamespace.minecraftToBukkit(v[1]); } + // more arguments can be parsed here (TODO) } } + /* advancements Advancement earned by entity. distance Distance to entity. @@ -121,13 +128,17 @@ public class SelectorArguments { public Collection getSelection() { final Location location = sender instanceof Player ? ((Player) sender).getLocation() : ((BlockCommandSender) sender).getBlock().getLocation(); Collection list = preSelect(location); + if (list.isEmpty()) { return list; } + List list2 = filter(location, list); + if (list2.isEmpty()) { return list2; } + switch (selector) { case PLAYER: Collections.sort(list2, (o1, o2) -> (int) (o1.getLocation().distanceSquared(location) - o2.getLocation().distanceSquared(location))); @@ -140,6 +151,7 @@ public class SelectorArguments { case SELF: return list2; } + return list2; } @@ -152,13 +164,16 @@ public class SelectorArguments { ? location.getWorld().getEntitiesByClasses(Player.class) : location.getWorld().getNearbyEntities(location, rangeMax * 2, rangeMax * 2, rangeMax * 2).stream() .filter(e -> e instanceof Player).collect(Collectors.toSet()); + case ALL_ENTITIES: return rangeMax == Double.POSITIVE_INFINITY ? location.getWorld().getEntities() : location.getWorld().getNearbyEntities(location, rangeMax * 2, rangeMax * 2, rangeMax * 2); + case SELF: return sender instanceof Entity ? Arrays.asList((Entity) sender) : Collections.EMPTY_LIST; } + return Collections.EMPTY_LIST; } @@ -166,11 +181,11 @@ public class SelectorArguments { Stream stream = list.stream() .filter(p -> rangeMin == 0 || p.getLocation().distance(location) > rangeMin) .filter(e -> entityType == null || e.getType() == entityType); + return stream.collect(Collectors.toList()); } public static enum SelectorType { - PLAYER, RANDOM_PLAYER, ALL_PLAYER, ALL_ENTITIES, SELF; public static SelectorType getType(String str) { @@ -188,6 +203,7 @@ public class SelectorArguments { return SELF; } } + return null; } } diff --git a/Core/src/main/java/com/songoda/core/commands/SimpleNestedCommand.java b/Core/src/main/java/com/songoda/core/commands/SimpleNestedCommand.java index ce1a4149..daeb9771 100644 --- a/Core/src/main/java/com/songoda/core/commands/SimpleNestedCommand.java +++ b/Core/src/main/java/com/songoda/core/commands/SimpleNestedCommand.java @@ -4,7 +4,6 @@ import java.util.LinkedHashMap; import java.util.stream.Stream; public class SimpleNestedCommand { - final AbstractCommand parent; final LinkedHashMap children = new LinkedHashMap<>(); diff --git a/Core/src/main/java/com/songoda/core/configuration/Comment.java b/Core/src/main/java/com/songoda/core/configuration/Comment.java index 0f235564..7f1304ba 100644 --- a/Core/src/main/java/com/songoda/core/configuration/Comment.java +++ b/Core/src/main/java/com/songoda/core/configuration/Comment.java @@ -1,108 +1,116 @@ -package com.songoda.core.configuration; - -import com.songoda.core.configuration.ConfigFormattingRules.CommentStyle; - -import java.io.IOException; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -/** - * A comment for a configuration key - * - * @author jascotty2 - * @since 2019-08-28 - */ -public class Comment { - - final List lines = new ArrayList(); - CommentStyle commentStyle = null; - - public Comment() { - } - - public Comment(String... lines) { - this(null, Arrays.asList(lines)); - } - - public Comment(List lines) { - this(null, lines); - } - - public Comment(CommentStyle commentStyle, String... lines) { - this(commentStyle, Arrays.asList(lines)); - } - - public Comment(CommentStyle commentStyle, List lines) { - this.commentStyle = commentStyle; - if (lines != null) { - lines.forEach(s -> this.lines.addAll(Arrays.asList(s.split("\n")))); - } - } - - public CommentStyle getCommentStyle() { - return commentStyle; - } - - public void setCommentStyle(CommentStyle commentStyle) { - this.commentStyle = commentStyle; - } - - public List getLines() { - return lines; - } - - @Override - public String toString() { - return lines.isEmpty() ? "" : lines.stream().collect(Collectors.joining("\n")); - } - - public static Comment loadComment(List lines) { - CommentStyle style = ConfigFormattingRules.parseStyle(lines); - int linePad = (style.drawBorder ? 1 : 0) + (style.drawSpace ? 1 : 0); - int prefix = style.commentPrefix.length(); - int suffix = style.commentSuffix.length(); - return new Comment(style, lines.subList(linePad, lines.size() - linePad).stream().map(s -> s.substring(prefix, s.length() - suffix).trim()).collect(Collectors.toList())); - } - - public void writeComment(Writer output, int offset, CommentStyle defaultStyle) throws IOException { - CommentStyle style = commentStyle != null ? commentStyle : defaultStyle; - int minSpacing = 0, borderSpacing = 0; - // first draw the top of the comment - if (style.drawBorder) { - // grab the longest line in the list of lines - minSpacing = lines.stream().max((s1, s2) -> s1.length() - s2.length()).get().length(); - borderSpacing = minSpacing + style.commentPrefix.length() + style.commentSuffix.length(); - // draw the first line - output.write((new String(new char[offset])).replace('\0', ' ') + (new String(new char[borderSpacing + 2])).replace('\0', '#') + "\n"); - if (style.drawSpace) { - output.write((new String(new char[offset])).replace('\0', ' ') - + "#" + style.spacePrefixTop - + (new String(new char[borderSpacing - style.spacePrefixTop.length() - style.spaceSuffixTop.length()])).replace('\0', style.spaceCharTop) - + style.spaceSuffixTop + "#\n"); - } - } else if (style.drawSpace) { - output.write((new String(new char[offset])).replace('\0', ' ') + "#\n"); - } - // then the actual comment lines - for (String line : lines) { - // todo? should we auto-wrap comment lines that are longer than 80 characters? - output.write((new String(new char[offset])).replace('\0', ' ') + "#" + style.commentPrefix - + (minSpacing == 0 ? line : line + (new String(new char[minSpacing - line.length()])).replace('\0', ' ')) + style.commentSuffix + (style.drawBorder ? "#\n" : "\n")); - } - // now draw the bottom of the comment border - if (style.drawBorder) { - if (style.drawSpace) { - output.write((new String(new char[offset])).replace('\0', ' ') - + "#" + style.spacePrefixBottom - + (new String(new char[borderSpacing - style.spacePrefixBottom.length() - style.spaceSuffixBottom.length()])).replace('\0', style.spaceCharBottom) - + style.spaceSuffixBottom + "#\n"); - } - output.write((new String(new char[offset])).replace('\0', ' ') + (new String(new char[borderSpacing + 2])).replace('\0', '#') + "\n"); - } else if (style.drawSpace) { - output.write((new String(new char[offset])).replace('\0', ' ') + "#\n"); - } - } -} +package com.songoda.core.configuration; + +import com.songoda.core.configuration.ConfigFormattingRules.CommentStyle; + +import java.io.IOException; +import java.io.Writer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +/** + * A comment for a configuration key + * + * @author jascotty2 + * @since 2019-08-28 + */ +public class Comment { + final List lines = new ArrayList(); + CommentStyle commentStyle = null; + + public Comment() { + } + + public Comment(String... lines) { + this(null, Arrays.asList(lines)); + } + + public Comment(List lines) { + this(null, lines); + } + + public Comment(CommentStyle commentStyle, String... lines) { + this(commentStyle, Arrays.asList(lines)); + } + + public Comment(CommentStyle commentStyle, List lines) { + this.commentStyle = commentStyle; + + if (lines != null) { + lines.forEach(s -> this.lines.addAll(Arrays.asList(s.split("\n")))); + } + } + + public CommentStyle getCommentStyle() { + return commentStyle; + } + + public void setCommentStyle(CommentStyle commentStyle) { + this.commentStyle = commentStyle; + } + + public List getLines() { + return lines; + } + + @Override + public String toString() { + return lines.isEmpty() ? "" : lines.stream().collect(Collectors.joining("\n")); + } + + public static Comment loadComment(List lines) { + CommentStyle style = ConfigFormattingRules.parseStyle(lines); + + int linePad = (style.drawBorder ? 1 : 0) + (style.drawSpace ? 1 : 0); + int prefix = style.commentPrefix.length(); + int suffix = style.commentSuffix.length(); + + return new Comment(style, lines.subList(linePad, lines.size() - linePad).stream().map(s -> s.substring(prefix, s.length() - suffix).trim()).collect(Collectors.toList())); + } + + public void writeComment(Writer output, int offset, CommentStyle defaultStyle) throws IOException { + CommentStyle style = commentStyle != null ? commentStyle : defaultStyle; + int minSpacing = 0, borderSpacing = 0; + + // first draw the top of the comment + if (style.drawBorder) { + // grab the longest line in the list of lines + minSpacing = lines.stream().max((s1, s2) -> s1.length() - s2.length()).get().length(); + borderSpacing = minSpacing + style.commentPrefix.length() + style.commentSuffix.length(); + + // draw the first line + output.write((new String(new char[offset])).replace('\0', ' ') + (new String(new char[borderSpacing + 2])).replace('\0', '#') + "\n"); + + if (style.drawSpace) { + output.write((new String(new char[offset])).replace('\0', ' ') + + "#" + style.spacePrefixTop + + (new String(new char[borderSpacing - style.spacePrefixTop.length() - style.spaceSuffixTop.length()])).replace('\0', style.spaceCharTop) + + style.spaceSuffixTop + "#\n"); + } + } else if (style.drawSpace) { + output.write((new String(new char[offset])).replace('\0', ' ') + "#\n"); + } + + // then the actual comment lines + for (String line : lines) { + // todo? should we auto-wrap comment lines that are longer than 80 characters? + output.write((new String(new char[offset])).replace('\0', ' ') + "#" + style.commentPrefix + + (minSpacing == 0 ? line : line + (new String(new char[minSpacing - line.length()])).replace('\0', ' ')) + style.commentSuffix + (style.drawBorder ? "#\n" : "\n")); + } + + // now draw the bottom of the comment border + if (style.drawBorder) { + if (style.drawSpace) { + output.write((new String(new char[offset])).replace('\0', ' ') + + "#" + style.spacePrefixBottom + + (new String(new char[borderSpacing - style.spacePrefixBottom.length() - style.spaceSuffixBottom.length()])).replace('\0', style.spaceCharBottom) + + style.spaceSuffixBottom + "#\n"); + } + + output.write((new String(new char[offset])).replace('\0', ' ') + (new String(new char[borderSpacing + 2])).replace('\0', '#') + "\n"); + } else if (style.drawSpace) { + output.write((new String(new char[offset])).replace('\0', ' ') + "#\n"); + } + } +} diff --git a/Core/src/main/java/com/songoda/core/configuration/Config.java b/Core/src/main/java/com/songoda/core/configuration/Config.java index 9d51f6e6..8439cda5 100644 --- a/Core/src/main/java/com/songoda/core/configuration/Config.java +++ b/Core/src/main/java/com/songoda/core/configuration/Config.java @@ -50,7 +50,6 @@ import java.util.stream.Collectors; * @since 2019-08-28 */ public class Config extends ConfigSection { - /* Serialization notes: // implements ConfigurationSerializable: @@ -75,35 +74,43 @@ public class Config extends ConfigSection { Charset defaultCharset = StandardCharsets.UTF_8; SaveTask saveTask; Timer autosaveTimer; + ////////////// Config settings //////////////// /** * save file whenever a change is made */ boolean autosave = false; + /** * time in seconds to start a save after a change is made */ int autosaveInterval = 60; + /** * remove nodes not defined in defaults */ boolean autoremove = false; + /** * load comments when loading the file */ boolean loadComments = true; + /** * Default comment applied to config nodes */ ConfigFormattingRules.CommentStyle defaultNodeCommentFormat = ConfigFormattingRules.CommentStyle.SIMPLE; + /** * Default comment applied to section nodes */ ConfigFormattingRules.CommentStyle defaultSectionCommentFormat = ConfigFormattingRules.CommentStyle.SPACED; + /** * Extra lines to put between root nodes */ int rootNodeSpacing = 1; + /** * Extra lines to put in front of comments.
* This is separate from rootNodeSpacing, if applicable. @@ -113,6 +120,7 @@ public class Config extends ConfigSection { public Config() { this.plugin = null; this.file = null; + dirName = null; fileName = null; } @@ -120,24 +128,28 @@ public class Config extends ConfigSection { public Config(@NotNull File file) { this.plugin = null; this.file = file.getAbsoluteFile(); + dirName = null; fileName = null; } public Config(@NotNull Plugin plugin) { this.plugin = plugin; + dirName = null; fileName = null; } public Config(@NotNull Plugin plugin, @NotNull String file) { this.plugin = plugin; + dirName = null; fileName = file; } public Config(@NotNull Plugin plugin, @Nullable String directory, @NotNull String file) { this.plugin = plugin; + dirName = directory; fileName = file; } @@ -156,6 +168,7 @@ public class Config extends ConfigSection { this.file = new File(plugin.getDataFolder(), fileName != null ? fileName : "config.yml"); } } + return file; } @@ -337,6 +350,7 @@ public class Config extends ConfigSection { } else { headerComment = new Comment(description); } + return this; } @@ -347,6 +361,7 @@ public class Config extends ConfigSection { } else { headerComment = new Comment(commentStyle, description); } + return this; } @@ -357,6 +372,7 @@ public class Config extends ConfigSection { } else { headerComment = new Comment(description); } + return this; } @@ -367,6 +383,7 @@ public class Config extends ConfigSection { } else { headerComment = new Comment(commentStyle, description); } + return this; } @@ -374,24 +391,27 @@ public class Config extends ConfigSection { public List getHeader() { if (headerComment != null) { return headerComment.getLines(); - } else { - return Collections.EMPTY_LIST; } + + return Collections.EMPTY_LIST; } public Config clearConfig(boolean clearDefaults) { root.values.clear(); root.configComments.clear(); + if (clearDefaults) { root.defaultComments.clear(); root.defaults.clear(); } + return this; } public Config clearDefaults() { root.defaultComments.clear(); root.defaults.clear(); + return this; } @@ -404,17 +424,22 @@ public class Config extends ConfigSection { if (file.exists()) { try (BufferedInputStream stream = new BufferedInputStream(new FileInputStream(file))) { Charset charset = TextUtils.detectCharset(stream, StandardCharsets.UTF_8); + // upgrade charset if file was saved in a more complex format if (charset == StandardCharsets.UTF_16BE || charset == StandardCharsets.UTF_16LE) { defaultCharset = StandardCharsets.UTF_16; } + this.load(new InputStreamReader(stream, charset)); + return true; } catch (IOException | InvalidConfigurationException ex) { (plugin != null ? plugin.getLogger() : Bukkit.getLogger()).log(Level.SEVERE, "Failed to load config file: " + file.getName(), ex); } + return false; } + return true; } @@ -432,11 +457,13 @@ public class Config extends ConfigSection { builder.append(line).append('\n'); } } + this.loadFromString(builder.toString()); } public void loadFromString(@NotNull String contents) throws InvalidConfigurationException { Map input; + try { input = (Map) this.yaml.load(contents); } catch (YAMLException e2) { @@ -444,10 +471,12 @@ public class Config extends ConfigSection { } catch (ClassCastException e3) { throw new InvalidConfigurationException("Top level is not a Map."); } + if (input != null) { if (loadComments) { this.parseComments(contents, input); } + this.convertMapsToSections(input, this); } } @@ -457,10 +486,12 @@ public class Config extends ConfigSection { for (Map.Entry entry : input.entrySet()) { String key = entry.getKey().toString(); Object value = entry.getValue(); + if (value instanceof Map) { this.convertMapsToSections((Map) value, section.createSection(key)); continue; } + section.set(key, value); } } @@ -477,6 +508,7 @@ public class Config extends ConfigSection { int index = 0; LinkedList currentPath = new LinkedList(); ArrayList commentBlock = new ArrayList(); + try { while ((line = in.readLine()) != null) { if (line.isEmpty()) { @@ -523,6 +555,7 @@ public class Config extends ConfigSection { } } } + if (!commentBlock.isEmpty()) { footerComment = Comment.loadComment(commentBlock); commentBlock.clear(); @@ -534,6 +567,7 @@ public class Config extends ConfigSection { public void deleteNonDefaultSettings() { // Delete old config values (thread-safe) List defaultKeys = Arrays.asList(defaults.keySet().toArray(new String[0])); + for (String key : values.keySet().toArray(new String[0])) { if (!defaultKeys.contains(key)) { values.remove(key); @@ -558,9 +592,11 @@ public class Config extends ConfigSection { public boolean saveChanges() { boolean saved = true; + if (changed || hasNewDefaults()) { saved = save(); } + if (saveTask != null) { //Close Threads saveTask.cancel(); @@ -568,14 +604,19 @@ public class Config extends ConfigSection { saveTask = null; autosaveTimer = null; } + return saved; } boolean hasNewDefaults() { if (file != null && !file.exists()) return true; + for (String def : defaults.keySet()) { - if (!values.containsKey(def)) return true; + if (!values.containsKey(def)) { + return true; + } } + return false; } @@ -587,6 +628,7 @@ public class Config extends ConfigSection { saveTask = null; autosaveTimer = null; } + return save(getFile()); } @@ -597,15 +639,18 @@ public class Config extends ConfigSection { public boolean save(@NotNull File file) { Validate.notNull(file, "File cannot be null"); + if (file.getParentFile() != null && !file.getParentFile().exists()) { file.getParentFile().mkdirs(); } + String data = this.saveToString(); - try (OutputStreamWriter writer = new OutputStreamWriter((OutputStream) new FileOutputStream(file), defaultCharset);) { + try (OutputStreamWriter writer = new OutputStreamWriter((OutputStream) new FileOutputStream(file), defaultCharset)) { writer.write(data); } catch (IOException e) { return false; } + return true; } @@ -615,28 +660,35 @@ public class Config extends ConfigSection { if (autoremove) { deleteNonDefaultSettings(); } + yamlOptions.setIndent(indentation); yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); yamlOptions.setSplitLines(false); yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + StringWriter str = new StringWriter(); + if (headerComment != null) { headerComment.writeComment(str, 0, ConfigFormattingRules.CommentStyle.BLOCKED); str.write("\n"); // add one space after the header } + String dump = yaml.dump(this.getValues(false)); if (!dump.equals(BLANK_CONFIG)) { writeComments(dump, str); } + if (footerComment != null) { str.write("\n"); footerComment.writeComment(str, 0, ConfigFormattingRules.CommentStyle.BLOCKED); } + return str.toString(); } catch (Throwable ex) { Logger.getLogger(Config.class.getName()).log(Level.SEVERE, "Error saving config", ex); delaySave(); } + return ""; } @@ -645,10 +697,12 @@ public class Config extends ConfigSection { protected void writeComments(String data, Writer out) throws IOException { // line-by-line apply line spacing formatting and comments per-node BufferedReader in = new BufferedReader(new StringReader(data)); + String line; boolean insideScalar = false; boolean firstNode = true; int index = 0; + LinkedList currentPath = new LinkedList(); while ((line = in.readLine()) != null) { // ignore comments and empty lines (there shouldn't be any, but just in case) @@ -667,6 +721,7 @@ public class Config extends ConfigSection { while (depth < currentPath.size()) { currentPath.removeLast(); } + currentPath.add(m.group(2)); String path = currentPath.stream().collect(Collectors.joining(String.valueOf(pathChar))); @@ -708,6 +763,7 @@ public class Config extends ConfigSection { // write it down! comment.writeComment(out, lineOffset, style); } + // ignore scalars index = lineOffset; if (m.group(3).trim().equals("|") || m.group(3).trim().equals(">")) { @@ -727,11 +783,11 @@ public class Config extends ConfigSection { return i; } } + return -1; } class SaveTask extends TimerTask { - @Override public void run() { saveChanges(); diff --git a/Core/src/main/java/com/songoda/core/configuration/ConfigFileConfigurationAdapter.java b/Core/src/main/java/com/songoda/core/configuration/ConfigFileConfigurationAdapter.java index 6a39c136..89141df5 100644 --- a/Core/src/main/java/com/songoda/core/configuration/ConfigFileConfigurationAdapter.java +++ b/Core/src/main/java/com/songoda/core/configuration/ConfigFileConfigurationAdapter.java @@ -1,273 +1,273 @@ -package com.songoda.core.configuration; - -import com.songoda.core.compatibility.CompatibleMaterial; -import org.bukkit.configuration.Configuration; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.configuration.file.FileConfiguration; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - -public class ConfigFileConfigurationAdapter extends FileConfiguration { - - final Config config; - - public ConfigFileConfigurationAdapter(Config config) { - super(config); - this.config = config; - } - - public Config getCoreConfig() { - return config; - } - - @Override - public String saveToString() { - return config.saveToString(); - } - - @Override - public void loadFromString(String string) throws InvalidConfigurationException { - config.loadFromString(string); - } - - @Override - protected String buildHeader() { - return "#" + config.getHeader().stream().collect(Collectors.joining("\n#")); - } - - @Override - public ConfigOptionsAdapter options() { - return new ConfigOptionsAdapter(config); - } - - @Override - public Set getKeys(boolean deep) { - return config.getKeys(deep); - } - - @Override - public Map getValues(boolean deep) { - return config.getValues(deep); - } - - @Override - public boolean contains(String path) { - return config.contains(path); - } - - @Override - public boolean isSet(String path) { - return config.isSet(path); - } - - @Override - public String getCurrentPath() { - return config.getCurrentPath(); - } - - @Override - public String getName() { - return config.getName(); - } - - @Override - public Configuration getRoot() { - return config; - } - - @Override - public ConfigurationSection getParent() { - return null; - } - - @Override - public void addDefault(String path, Object value) { - config.addDefault(path, value); - } - - @Override - public ConfigurationSection getDefaultSection() { - return config.getDefaultSection(); - } - - @Override - public void set(String path, Object value) { - config.set(path, value); - } - - @Override - public Object get(String path) { - return config.get(path); - } - - @Override - public Object get(String path, Object def) { - return config.get(path, def); - } - - @Override - public ConfigurationSection createSection(String path) { - return config.createSection(path); - } - - @Override - public ConfigurationSection createSection(String path, Map map) { - return config.createSection(path, map); - } - - // Other non-FileConfiguration methods - - @NotNull - public ConfigSection createDefaultSection(@NotNull String path) { - return config.createDefaultSection(path); - } - - @NotNull - public ConfigSection createDefaultSection(@NotNull String path, String... comment) { - return config.createDefaultSection(path, comment); - } - - @NotNull - public ConfigSection createDefaultSection(@NotNull String path, ConfigFormattingRules.CommentStyle commentStyle, String... comment) { - return config.createDefaultSection(path, commentStyle, comment); - } - - @NotNull - public ConfigSection setComment(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, String... lines) { - return config.setComment(path, commentStyle, lines); - } - - @NotNull - public ConfigSection setComment(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, @Nullable List lines) { - return config.setComment(path, commentStyle, lines); - } - - @NotNull - public ConfigSection setDefaultComment(@NotNull String path, String... lines) { - return config.setDefaultComment(path, lines); - } - - @NotNull - public ConfigSection setDefaultComment(@NotNull String path, @Nullable List lines) { - return config.setDefaultComment(path, lines); - } - - @NotNull - public ConfigSection setDefaultComment(@NotNull String path, ConfigFormattingRules.CommentStyle commentStyle, String... lines) { - return config.setDefaultComment(path, commentStyle, lines); - } - - @NotNull - public ConfigSection setDefaultComment(@NotNull String path, ConfigFormattingRules.CommentStyle commentStyle, @Nullable List lines) { - return config.setDefaultComment(path, commentStyle, lines); - } - - @Nullable - public Comment getComment(@NotNull String path) { - return config.getComment(path); - } - - @Nullable - public String getCommentString(@NotNull String path) { - return config.getCommentString(path); - } - - @NotNull - public List getSections(String path) { - return config.getSections(path); - } - - @NotNull - public ConfigSection set(@NotNull String path, @Nullable Object value, String... comment) { - return config.set(path, value, comment); - } - - @NotNull - public ConfigSection set(@NotNull String path, @Nullable Object value, List comment) { - return config.set(path, value, comment); - } - - @NotNull - public ConfigSection set(@NotNull String path, @Nullable Object value, @Nullable ConfigFormattingRules.CommentStyle commentStyle, String... comment) { - return config.set(path, value, commentStyle, comment); - } - - @NotNull - public ConfigSection set(@NotNull String path, @Nullable Object value, @Nullable ConfigFormattingRules.CommentStyle commentStyle, List comment) { - return config.set(path, value, commentStyle, comment); - } - - @NotNull - public ConfigSection setDefault(@NotNull String path, @Nullable Object value) { - return config.setDefault(path, value); - } - - @NotNull - public ConfigSection setDefault(@NotNull String path, @Nullable Object value, String... comment) { - return config.setDefault(path, value, comment); - } - - @NotNull - public ConfigSection setDefault(@NotNull String path, @Nullable Object value, List comment) { - return config.setDefault(path, value, comment); - } - - @NotNull - public ConfigSection setDefault(@NotNull String path, @Nullable Object value, ConfigFormattingRules.CommentStyle commentStyle, String... comment) { - return config.setDefault(path, value, commentStyle, comment); - } - - @NotNull - public ConfigSection setDefault(@NotNull String path, @Nullable Object value, ConfigFormattingRules.CommentStyle commentStyle, List comment) { - return config.setDefault(path, value, commentStyle, comment); - } - - @NotNull - public ConfigSection createSection(@NotNull String path, String... comment) { - return config.createSection(path, comment); - } - - @NotNull - public ConfigSection createSection(@NotNull String path, @Nullable List comment) { - return config.createSection(path, comment); - } - - @NotNull - public ConfigSection createSection(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, String... comment) { - return config.createSection(path, commentStyle, comment); - } - - @NotNull - public ConfigSection createSection(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, @Nullable List comment) { - return config.createSection(path, commentStyle, comment); - } - - public char getChar(@NotNull String path) { - return config.getChar(path); - } - - public char getChar(@NotNull String path, char def) { - return config.getChar(path, def); - } - - @Nullable - public CompatibleMaterial getMaterial(@NotNull String path) { - return config.getMaterial(path); - } - - @Nullable - public CompatibleMaterial getMaterial(@NotNull String path, @Nullable CompatibleMaterial def) { - return config.getMaterial(path, def); - } - - @NotNull - public ConfigSection getOrCreateConfigurationSection(@NotNull String path) { - return config.getOrCreateConfigurationSection(path); - } -} +package com.songoda.core.configuration; + +import com.songoda.core.compatibility.CompatibleMaterial; +import org.bukkit.configuration.Configuration; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +public class ConfigFileConfigurationAdapter extends FileConfiguration { + final Config config; + + public ConfigFileConfigurationAdapter(Config config) { + super(config); + + this.config = config; + } + + public Config getCoreConfig() { + return config; + } + + @Override + public String saveToString() { + return config.saveToString(); + } + + @Override + public void loadFromString(String string) throws InvalidConfigurationException { + config.loadFromString(string); + } + + @Override + protected String buildHeader() { + return "#" + config.getHeader().stream().collect(Collectors.joining("\n#")); + } + + @Override + public ConfigOptionsAdapter options() { + return new ConfigOptionsAdapter(config); + } + + @Override + public Set getKeys(boolean deep) { + return config.getKeys(deep); + } + + @Override + public Map getValues(boolean deep) { + return config.getValues(deep); + } + + @Override + public boolean contains(String path) { + return config.contains(path); + } + + @Override + public boolean isSet(String path) { + return config.isSet(path); + } + + @Override + public String getCurrentPath() { + return config.getCurrentPath(); + } + + @Override + public String getName() { + return config.getName(); + } + + @Override + public Configuration getRoot() { + return config; + } + + @Override + public ConfigurationSection getParent() { + return null; + } + + @Override + public void addDefault(String path, Object value) { + config.addDefault(path, value); + } + + @Override + public ConfigurationSection getDefaultSection() { + return config.getDefaultSection(); + } + + @Override + public void set(String path, Object value) { + config.set(path, value); + } + + @Override + public Object get(String path) { + return config.get(path); + } + + @Override + public Object get(String path, Object def) { + return config.get(path, def); + } + + @Override + public ConfigurationSection createSection(String path) { + return config.createSection(path); + } + + @Override + public ConfigurationSection createSection(String path, Map map) { + return config.createSection(path, map); + } + + // Other non-FileConfiguration methods + + @NotNull + public ConfigSection createDefaultSection(@NotNull String path) { + return config.createDefaultSection(path); + } + + @NotNull + public ConfigSection createDefaultSection(@NotNull String path, String... comment) { + return config.createDefaultSection(path, comment); + } + + @NotNull + public ConfigSection createDefaultSection(@NotNull String path, ConfigFormattingRules.CommentStyle commentStyle, String... comment) { + return config.createDefaultSection(path, commentStyle, comment); + } + + @NotNull + public ConfigSection setComment(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, String... lines) { + return config.setComment(path, commentStyle, lines); + } + + @NotNull + public ConfigSection setComment(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, @Nullable List lines) { + return config.setComment(path, commentStyle, lines); + } + + @NotNull + public ConfigSection setDefaultComment(@NotNull String path, String... lines) { + return config.setDefaultComment(path, lines); + } + + @NotNull + public ConfigSection setDefaultComment(@NotNull String path, @Nullable List lines) { + return config.setDefaultComment(path, lines); + } + + @NotNull + public ConfigSection setDefaultComment(@NotNull String path, ConfigFormattingRules.CommentStyle commentStyle, String... lines) { + return config.setDefaultComment(path, commentStyle, lines); + } + + @NotNull + public ConfigSection setDefaultComment(@NotNull String path, ConfigFormattingRules.CommentStyle commentStyle, @Nullable List lines) { + return config.setDefaultComment(path, commentStyle, lines); + } + + @Nullable + public Comment getComment(@NotNull String path) { + return config.getComment(path); + } + + @Nullable + public String getCommentString(@NotNull String path) { + return config.getCommentString(path); + } + + @NotNull + public List getSections(String path) { + return config.getSections(path); + } + + @NotNull + public ConfigSection set(@NotNull String path, @Nullable Object value, String... comment) { + return config.set(path, value, comment); + } + + @NotNull + public ConfigSection set(@NotNull String path, @Nullable Object value, List comment) { + return config.set(path, value, comment); + } + + @NotNull + public ConfigSection set(@NotNull String path, @Nullable Object value, @Nullable ConfigFormattingRules.CommentStyle commentStyle, String... comment) { + return config.set(path, value, commentStyle, comment); + } + + @NotNull + public ConfigSection set(@NotNull String path, @Nullable Object value, @Nullable ConfigFormattingRules.CommentStyle commentStyle, List comment) { + return config.set(path, value, commentStyle, comment); + } + + @NotNull + public ConfigSection setDefault(@NotNull String path, @Nullable Object value) { + return config.setDefault(path, value); + } + + @NotNull + public ConfigSection setDefault(@NotNull String path, @Nullable Object value, String... comment) { + return config.setDefault(path, value, comment); + } + + @NotNull + public ConfigSection setDefault(@NotNull String path, @Nullable Object value, List comment) { + return config.setDefault(path, value, comment); + } + + @NotNull + public ConfigSection setDefault(@NotNull String path, @Nullable Object value, ConfigFormattingRules.CommentStyle commentStyle, String... comment) { + return config.setDefault(path, value, commentStyle, comment); + } + + @NotNull + public ConfigSection setDefault(@NotNull String path, @Nullable Object value, ConfigFormattingRules.CommentStyle commentStyle, List comment) { + return config.setDefault(path, value, commentStyle, comment); + } + + @NotNull + public ConfigSection createSection(@NotNull String path, String... comment) { + return config.createSection(path, comment); + } + + @NotNull + public ConfigSection createSection(@NotNull String path, @Nullable List comment) { + return config.createSection(path, comment); + } + + @NotNull + public ConfigSection createSection(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, String... comment) { + return config.createSection(path, commentStyle, comment); + } + + @NotNull + public ConfigSection createSection(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, @Nullable List comment) { + return config.createSection(path, commentStyle, comment); + } + + public char getChar(@NotNull String path) { + return config.getChar(path); + } + + public char getChar(@NotNull String path, char def) { + return config.getChar(path, def); + } + + @Nullable + public CompatibleMaterial getMaterial(@NotNull String path) { + return config.getMaterial(path); + } + + @Nullable + public CompatibleMaterial getMaterial(@NotNull String path, @Nullable CompatibleMaterial def) { + return config.getMaterial(path, def); + } + + @NotNull + public ConfigSection getOrCreateConfigurationSection(@NotNull String path) { + return config.getOrCreateConfigurationSection(path); + } +} diff --git a/Core/src/main/java/com/songoda/core/configuration/ConfigFormattingRules.java b/Core/src/main/java/com/songoda/core/configuration/ConfigFormattingRules.java index 7a16791b..b6cf06cd 100644 --- a/Core/src/main/java/com/songoda/core/configuration/ConfigFormattingRules.java +++ b/Core/src/main/java/com/songoda/core/configuration/ConfigFormattingRules.java @@ -3,14 +3,12 @@ package com.songoda.core.configuration; import java.util.List; public class ConfigFormattingRules { - int spacesBetweenMainCategories; int spacesBetweenValues; CommentStyle rootCommentStyle = CommentStyle.BLOCKSPACED; CommentStyle mainCategoryCommentStyle = CommentStyle.SPACED; public static enum CommentStyle { - /** * # Comment */ @@ -71,14 +69,18 @@ public class ConfigFormattingRules { public static CommentStyle parseStyle(List lines) { if (lines == null || lines.size() <= 2) { return CommentStyle.SIMPLE; - } else if (lines.size() > 2 && lines.get(0).trim().equals("#") && lines.get(lines.size() - 1).trim().equals("#")) { + } + + if (lines.size() > 2 && lines.get(0).trim().equals("#") && lines.get(lines.size() - 1).trim().equals("#")) { return CommentStyle.SPACED; } + boolean hasBorders = lines.size() > 2 && lines.get(0).trim().matches("^##+$") && lines.get(lines.size() - 1).trim().matches("^##+$"); if (!hasBorders) { // default return return CommentStyle.SIMPLE; } + // now need to figure out if this is blocked or not if (lines.size() > 4 && lines.get(1).trim().matches(("^#" + CommentStyle.BLOCKSPACED.spacePrefixTop + CommentStyle.BLOCKSPACED.spaceCharTop + "+" @@ -88,6 +90,7 @@ public class ConfigFormattingRules { + CommentStyle.BLOCKSPACED.spaceSuffixTop + "#$").replace("|", "\\|"))) { return CommentStyle.BLOCKSPACED; } + return CommentStyle.BLOCKED; } } diff --git a/Core/src/main/java/com/songoda/core/configuration/ConfigOptionsAdapter.java b/Core/src/main/java/com/songoda/core/configuration/ConfigOptionsAdapter.java index 3a80354d..63e5d83f 100644 --- a/Core/src/main/java/com/songoda/core/configuration/ConfigOptionsAdapter.java +++ b/Core/src/main/java/com/songoda/core/configuration/ConfigOptionsAdapter.java @@ -1,71 +1,72 @@ -package com.songoda.core.configuration; - -import org.bukkit.configuration.file.FileConfigurationOptions; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.List; - -public class ConfigOptionsAdapter extends FileConfigurationOptions { - - final ConfigSection config; - - public ConfigOptionsAdapter(ConfigSection config) { - super(config); - this.config = config; - } - - public Config getConfig() { - return (Config) config.root; - } - - @NotNull - @Override - public ConfigFileConfigurationAdapter configuration() { - return new ConfigFileConfigurationAdapter((Config) config.root); - } - - @NotNull - @Override - public ConfigOptionsAdapter copyDefaults(boolean value) { - // we always copy new values - return this; - } - - @NotNull - @Override - public ConfigOptionsAdapter pathSeparator(char value) { - ((Config) config.root).setPathSeparator(value); - return this; - } - - @NotNull - @Override - public ConfigOptionsAdapter header(@Nullable String value) { - if (value == null) { - ((Config) config.root).setHeader((List) null); - } else { - ((Config) config.root).setHeader(value.split("\n")); - } - return this; - } - - @NotNull - @Override - public ConfigOptionsAdapter copyHeader(boolean value) { - if (!value) { - ((Config) config.root).setHeader((List) null); - } - return this; - } - - public int indent() { - return ((Config) config.root).getIndent(); - } - - @NotNull - public ConfigOptionsAdapter indent(int value) { - ((Config) config.root).setIndent(value); - return this; - } -} +package com.songoda.core.configuration; + +import org.bukkit.configuration.file.FileConfigurationOptions; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; + +public class ConfigOptionsAdapter extends FileConfigurationOptions { + final ConfigSection config; + + public ConfigOptionsAdapter(ConfigSection config) { + super(config); + this.config = config; + } + + public Config getConfig() { + return (Config) config.root; + } + + @NotNull + @Override + public ConfigFileConfigurationAdapter configuration() { + return new ConfigFileConfigurationAdapter((Config) config.root); + } + + @NotNull + @Override + public ConfigOptionsAdapter copyDefaults(boolean value) { + // we always copy new values + return this; + } + + @NotNull + @Override + public ConfigOptionsAdapter pathSeparator(char value) { + ((Config) config.root).setPathSeparator(value); + return this; + } + + @NotNull + @Override + public ConfigOptionsAdapter header(@Nullable String value) { + if (value == null) { + ((Config) config.root).setHeader((List) null); + } else { + ((Config) config.root).setHeader(value.split("\n")); + } + + return this; + } + + @NotNull + @Override + public ConfigOptionsAdapter copyHeader(boolean value) { + if (!value) { + ((Config) config.root).setHeader((List) null); + } + + return this; + } + + public int indent() { + return ((Config) config.root).getIndent(); + } + + @NotNull + public ConfigOptionsAdapter indent(int value) { + ((Config) config.root).setIndent(value); + return this; + } +} diff --git a/Core/src/main/java/com/songoda/core/configuration/ConfigSection.java b/Core/src/main/java/com/songoda/core/configuration/ConfigSection.java index 0d622be2..82438ede 100644 --- a/Core/src/main/java/com/songoda/core/configuration/ConfigSection.java +++ b/Core/src/main/java/com/songoda/core/configuration/ConfigSection.java @@ -1,694 +1,764 @@ -package com.songoda.core.configuration; - -import com.songoda.core.compatibility.CompatibleMaterial; -import org.bukkit.configuration.Configuration; -import org.bukkit.configuration.MemoryConfiguration; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - -/** - * Configuration for a specific node - * - * @author jascotty2 - * @since 2019-08-28 - */ -public class ConfigSection extends MemoryConfiguration { - - final String fullPath, nodeKey; - final ConfigSection root; - final ConfigSection parent; - protected int indentation = 2; // between 2 and 9 (inclusive) - protected char pathChar = '.'; - final HashMap configComments; - final HashMap defaultComments; - final LinkedHashMap defaults; - final LinkedHashMap values; - /** - * Internal root state: if any configuration value has changed from file state - */ - boolean changed = false; - final boolean isDefault; - final Object lock = new Object(); - - ConfigSection() { - this.root = this; - this.parent = null; - isDefault = false; - nodeKey = fullPath = ""; - configComments = new HashMap(); - defaultComments = new HashMap(); - defaults = new LinkedHashMap(); - values = new LinkedHashMap(); - } - - ConfigSection(ConfigSection root, ConfigSection parent, String nodeKey, boolean isDefault) { - this.root = root; - this.parent = parent; - this.nodeKey = nodeKey; - this.fullPath = nodeKey != null ? parent.fullPath + nodeKey + root.pathChar : parent.fullPath; - this.isDefault = isDefault; - configComments = defaultComments = null; - defaults = null; - values = null; - } - - public int getIndent() { - return root.indentation; - } - - public void setIndent(int indentation) { - root.indentation = indentation; - } - - protected void onChange() { - if (parent != null) { - root.onChange(); - } - } - - /** - * Sets the character used to separate configuration nodes.
- * IMPORTANT: Do not change this after loading or adding ConfigurationSections! - * - * @param pathChar character to use - */ - public void setPathSeparator(char pathChar) { - if (!root.values.isEmpty() || !root.defaults.isEmpty()) - throw new RuntimeException("Path change after config initialization"); - root.pathChar = pathChar; - } - - public char getPathSeparator() { - return root.pathChar; - } - - /** - * @return The full key for this section node - */ - public String getKey() { - return !fullPath.endsWith(String.valueOf(root.pathChar)) ? fullPath : fullPath.substring(0, fullPath.length() - 1); - } - - /** - * @return The specific key that was used from the last node to get to this node - */ - public String getNodeKey() { - return nodeKey; - } - - /** - * Create the path required for this node to exist.
- * DO NOT USE THIS IN A SYNCHRONIZED LOCK - * - * @param path full path of the node required. Eg, for foo.bar.node, this will create sections for foo and foo.bar - * @param useDefault set to true if this is a default value - */ - protected void createNodePath(@NotNull String path, boolean useDefault) { - if (path.indexOf(root.pathChar) != -1) { - // if any intermediate nodes don't exist, create them - String[] pathParts = path.split(Pattern.quote(String.valueOf(root.pathChar))); - StringBuilder nodePath = new StringBuilder(fullPath); - LinkedHashMap writeTo = useDefault ? root.defaults : root.values; - ConfigSection travelNode = this; - synchronized (root.lock) { - for (int i = 0; i < pathParts.length - 1; ++i) { - final String node = (i != 0 ? nodePath.append(root.pathChar) : nodePath).append(pathParts[i]).toString(); - if (!(writeTo.get(node) instanceof ConfigSection)) { - writeTo.put(node, travelNode = new ConfigSection(root, travelNode, pathParts[i], useDefault)); - } else { - travelNode = (ConfigSection) writeTo.get(node); - } - } - } - } - } - - @NotNull - public ConfigSection createDefaultSection(@NotNull String path) { - createNodePath(path, true); - ConfigSection section = new ConfigSection(root, this, path, true); - synchronized (root.lock) { - root.defaults.put(fullPath + path, section); - } - return section; - } - - @NotNull - public ConfigSection createDefaultSection(@NotNull String path, String... comment) { - createNodePath(path, true); - ConfigSection section = new ConfigSection(root, this, path, true); - synchronized (root.lock) { - root.defaults.put(fullPath + path, section); - root.defaultComments.put(fullPath + path, new Comment(comment)); - } - return section; - } - - @NotNull - public ConfigSection createDefaultSection(@NotNull String path, ConfigFormattingRules.CommentStyle commentStyle, String... comment) { - createNodePath(path, true); - ConfigSection section = new ConfigSection(root, this, path, true); - synchronized (root.lock) { - root.defaults.put(fullPath + path, section); - root.defaultComments.put(fullPath + path, new Comment(commentStyle, comment)); - } - return section; - } - - @NotNull - public ConfigSection setComment(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, String... lines) { - return setComment(path, lines != null ? new Comment(commentStyle, lines) : null); - } - - @NotNull - public ConfigSection setComment(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, @Nullable List lines) { - return setComment(path, lines != null ? new Comment(commentStyle, lines) : null); - } - - @NotNull - public ConfigSection setComment(@NotNull String path, @Nullable Comment comment) { - synchronized (root.lock) { - if (isDefault) { - root.defaultComments.put(fullPath + path, comment); - } else { - root.configComments.put(fullPath + path, comment); - } - } - return this; - } - - @NotNull - public ConfigSection setDefaultComment(@NotNull String path, String... lines) { - return setDefaultComment(path, lines.length == 0 ? (List) null : Arrays.asList(lines)); - } - - @NotNull - public ConfigSection setDefaultComment(@NotNull String path, @Nullable List lines) { - synchronized (root.lock) { - root.defaultComments.put(fullPath + path, new Comment(lines)); - } - return this; - } - - @NotNull - public ConfigSection setDefaultComment(@NotNull String path, ConfigFormattingRules.CommentStyle commentStyle, String... lines) { - return setDefaultComment(path, commentStyle, lines.length == 0 ? (List) null : Arrays.asList(lines)); - } - - @NotNull - public ConfigSection setDefaultComment(@NotNull String path, ConfigFormattingRules.CommentStyle commentStyle, @Nullable List lines) { - synchronized (root.lock) { - root.defaultComments.put(fullPath + path, new Comment(commentStyle, lines)); - } - return this; - } - - @NotNull - public ConfigSection setDefaultComment(@NotNull String path, @Nullable Comment comment) { - synchronized (root.lock) { - root.defaultComments.put(fullPath + path, comment); - } - return this; - } - - @Nullable - public Comment getComment(@NotNull String path) { - Comment result = root.configComments.get(fullPath + path); - if (result == null) { - result = root.defaultComments.get(fullPath + path); - } - return result; - } - - @Nullable - public String getCommentString(@NotNull String path) { - Comment result = root.configComments.get(fullPath + path); - if (result == null) { - result = root.defaultComments.get(fullPath + path); - } - return result != null ? result.toString() : null; - } - - @Override - public void addDefault(@NotNull String path, @Nullable Object value) { - createNodePath(path, true); - synchronized (root.lock) { - root.defaults.put(fullPath + path, value); - } - } - - @Override - public void addDefaults(@NotNull Map defaults) { - //defaults.entrySet().stream().forEach(m -> root.defaults.put(fullPath + m.getKey(), m.getValue())); - defaults.entrySet().stream().forEach(m -> addDefault(m.getKey(), m.getValue())); - } - - @Override - public void setDefaults(Configuration c) { - if (fullPath.isEmpty()) { - root.defaults.clear(); - } else { - root.defaults.keySet().stream() - .filter(k -> k.startsWith(fullPath)) - .forEach(k -> root.defaults.remove(k)); - } - addDefaults(c); - } - - @Override - public ConfigSection getDefaults() { - return new ConfigSection(root, this, null, true); - } - - @Override - public ConfigSection getDefaultSection() { - return new ConfigSection(root, this, null, true); - } - - @Override - public ConfigOptionsAdapter options() { - return new ConfigOptionsAdapter(root); - } - - @NotNull - @Override - public Set getKeys(boolean deep) { - LinkedHashSet result = new LinkedHashSet(); - int pathIndex = fullPath.lastIndexOf(root.pathChar); - if (deep) { - result.addAll(root.defaults.keySet().stream() - .filter(k -> k.startsWith(fullPath)) - .map(k -> !k.endsWith(String.valueOf(root.pathChar)) ? k.substring(pathIndex + 1) : k.substring(pathIndex + 1, k.length() - 1)) - .collect(Collectors.toCollection(LinkedHashSet::new))); - result.addAll(root.values.keySet().stream() - .filter(k -> k.startsWith(fullPath)) - .map(k -> !k.endsWith(String.valueOf(root.pathChar)) ? k.substring(pathIndex + 1) : k.substring(pathIndex + 1, k.length() - 1)) - .collect(Collectors.toCollection(LinkedHashSet::new))); - } else { - result.addAll(root.defaults.keySet().stream() - .filter(k -> k.startsWith(fullPath) && k.lastIndexOf(root.pathChar) == pathIndex) - .map(k -> !k.endsWith(String.valueOf(root.pathChar)) ? k.substring(pathIndex + 1) : k.substring(pathIndex + 1, k.length() - 1)) - .collect(Collectors.toCollection(LinkedHashSet::new))); - result.addAll(root.values.keySet().stream() - .filter(k -> k.startsWith(fullPath) && k.lastIndexOf(root.pathChar) == pathIndex) - .map(k -> !k.endsWith(String.valueOf(root.pathChar)) ? k.substring(pathIndex + 1) : k.substring(pathIndex + 1, k.length() - 1)) - .collect(Collectors.toCollection(LinkedHashSet::new))); - } - return result; - } - - @NotNull - @Override - public Map getValues(boolean deep) { - LinkedHashMap result = new LinkedHashMap(); - int pathIndex = fullPath.lastIndexOf(root.pathChar); - if (deep) { - result.putAll((Map) root.defaults.entrySet().stream() - .filter(k -> k.getKey().startsWith(fullPath)) - .collect(Collectors.toMap( - e -> !e.getKey().endsWith(String.valueOf(root.pathChar)) ? e.getKey().substring(pathIndex + 1) : e.getKey().substring(pathIndex + 1, e.getKey().length() - 1), - e -> e.getValue(), - (v1, v2) -> { - throw new IllegalStateException(); - }, // never going to be merging keys - LinkedHashMap::new))); - result.putAll((Map) root.values.entrySet().stream() - .filter(k -> k.getKey().startsWith(fullPath)) - .collect(Collectors.toMap( - e -> !e.getKey().endsWith(String.valueOf(root.pathChar)) ? e.getKey().substring(pathIndex + 1) : e.getKey().substring(pathIndex + 1, e.getKey().length() - 1), - e -> e.getValue(), - (v1, v2) -> { - throw new IllegalStateException(); - }, // never going to be merging keys - LinkedHashMap::new))); - } else { - result.putAll((Map) root.defaults.entrySet().stream() - .filter(k -> k.getKey().startsWith(fullPath) && k.getKey().lastIndexOf(root.pathChar) == pathIndex) - .collect(Collectors.toMap( - e -> !e.getKey().endsWith(String.valueOf(root.pathChar)) ? e.getKey().substring(pathIndex + 1) : e.getKey().substring(pathIndex + 1, e.getKey().length() - 1), - e -> e.getValue(), - (v1, v2) -> { - throw new IllegalStateException(); - }, // never going to be merging keys - LinkedHashMap::new))); - result.putAll((Map) root.values.entrySet().stream() - .filter(k -> k.getKey().startsWith(fullPath) && k.getKey().lastIndexOf(root.pathChar) == pathIndex) - .collect(Collectors.toMap( - e -> !e.getKey().endsWith(String.valueOf(root.pathChar)) ? e.getKey().substring(pathIndex + 1) : e.getKey().substring(pathIndex + 1, e.getKey().length() - 1), - e -> e.getValue(), - (v1, v2) -> { - throw new IllegalStateException(); - }, // never going to be merging keys - LinkedHashMap::new))); - } - return result; - } - - @NotNull - public List getSections(String path) { - ConfigSection rootSection = getConfigurationSection(path); - if (rootSection == null) { - return Collections.EMPTY_LIST; - } - ArrayList result = new ArrayList(); - rootSection.getKeys(false).stream() - .map(key -> rootSection.get(key)) - .filter(object -> object != null && object instanceof ConfigSection) - .forEachOrdered(object -> result.add((ConfigSection) object)); - return result; - } - - @Override - public boolean contains(@NotNull String path) { - return root.defaults.containsKey(fullPath + path) || root.values.containsKey(fullPath + path); - } - - @Override - public boolean contains(@NotNull String path, boolean ignoreDefault) { - return (!ignoreDefault && root.defaults.containsKey(fullPath + path)) || root.values.containsKey(fullPath + path); - } - - @Override - public boolean isSet(@NotNull String path) { - return root.defaults.get(fullPath + path) != null || root.values.get(fullPath + path) != null; - } - - @Override - public String getCurrentPath() { - return fullPath.isEmpty() ? "" : fullPath.substring(0, fullPath.length() - 1); - } - - @Override - public String getName() { - if (fullPath.isEmpty()) - return ""; - String[] parts = fullPath.split(Pattern.quote(String.valueOf(root.pathChar))); - return parts[parts.length - 1]; - } - - @Override - public ConfigSection getRoot() { - return root; - } - - @Override - public ConfigSection getParent() { - return parent; - } - - @Nullable - @Override - public Object get(@NotNull String path) { - Object result = root.values.get(fullPath + path); - if (result == null) { - result = root.defaults.get(fullPath + path); - } - return result; - } - - @Nullable - @Override - public Object get(@NotNull String path, @Nullable Object def) { - Object result = root.values.get(fullPath + path); - return result != null ? result : def; - } - - @Override - public void set(@NotNull String path, @Nullable Object value) { - if (isDefault) { - addDefault(path, value); - } else { - createNodePath(path, false); - Object last = null; - synchronized (root.lock) { - if (value != null) { - root.changed |= (last = root.values.put(fullPath + path, value)) != value; - } else { - root.changed |= (last = root.values.remove(fullPath + path)) != null; - } - } - if (last != value && last != null && last instanceof ConfigSection) { - // clean up orphaned nodes - final String trim = fullPath + path + root.pathChar; - synchronized (root.lock) { - root.values.keySet().stream().filter(k -> k.startsWith(trim)).collect(Collectors.toSet()).stream() - .forEach(k -> root.values.remove(k)); - } - } - onChange(); - } - } - - @NotNull - public ConfigSection set(@NotNull String path, @Nullable Object value, String... comment) { - set(path, value); - return setComment(path, null, comment); - } - - @NotNull - public ConfigSection set(@NotNull String path, @Nullable Object value, List comment) { - set(path, value); - return setComment(path, null, comment); - } - - @NotNull - public ConfigSection set(@NotNull String path, @Nullable Object value, @Nullable ConfigFormattingRules.CommentStyle commentStyle, String... comment) { - set(path, value); - return setComment(path, commentStyle, comment); - } - - @NotNull - public ConfigSection set(@NotNull String path, @Nullable Object value, @Nullable ConfigFormattingRules.CommentStyle commentStyle, List comment) { - set(path, value); - return setComment(path, commentStyle, comment); - } - - @NotNull - public ConfigSection setDefault(@NotNull String path, @Nullable Object value) { - addDefault(path, value); - return this; - } - - @NotNull - public ConfigSection setDefault(@NotNull String path, @Nullable Object value, String... comment) { - addDefault(path, value); - return setDefaultComment(path, comment); - } - - @NotNull - public ConfigSection setDefault(@NotNull String path, @Nullable Object value, List comment) { - addDefault(path, value); - return setDefaultComment(path, comment); - } - - @NotNull - public ConfigSection setDefault(@NotNull String path, @Nullable Object value, ConfigFormattingRules.CommentStyle commentStyle, String... comment) { - addDefault(path, value); - return setDefaultComment(path, commentStyle, comment); - } - - @NotNull - public ConfigSection setDefault(@NotNull String path, @Nullable Object value, ConfigFormattingRules.CommentStyle commentStyle, List comment) { - addDefault(path, value); - return setDefaultComment(path, commentStyle, comment); - } - - @NotNull - @Override - public ConfigSection createSection(@NotNull String path) { - createNodePath(path, false); - ConfigSection section = new ConfigSection(root, this, path, false); - synchronized (root.lock) { - root.values.put(fullPath + path, section); - } - root.changed = true; - onChange(); - return section; - } - - @NotNull - public ConfigSection createSection(@NotNull String path, String... comment) { - return createSection(path, null, comment.length == 0 ? (List) null : Arrays.asList(comment)); - } - - @NotNull - public ConfigSection createSection(@NotNull String path, @Nullable List comment) { - return createSection(path, null, comment); - } - - @NotNull - public ConfigSection createSection(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, String... comment) { - return createSection(path, commentStyle, comment.length == 0 ? (List) null : Arrays.asList(comment)); - } - - @NotNull - public ConfigSection createSection(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, @Nullable List comment) { - createNodePath(path, false); - ConfigSection section = new ConfigSection(root, this, path, false); - synchronized (root.lock) { - root.values.put(fullPath + path, section); - } - setComment(path, commentStyle, comment); - root.changed = true; - onChange(); - return section; - } - - @NotNull - @Override - public ConfigSection createSection(@NotNull String path, Map map) { - createNodePath(path, false); - ConfigSection section = new ConfigSection(root, this, path, false); - synchronized (root.lock) { - root.values.put(fullPath + path, section); - } - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() instanceof Map) { - section.createSection(entry.getKey().toString(), (Map) entry.getValue()); - continue; - } - section.set(entry.getKey().toString(), entry.getValue()); - } - root.changed = true; - onChange(); - return section; - } - - @Nullable - @Override - public String getString(@NotNull String path) { - Object result = get(path); - return result != null ? result.toString() : null; - } - - @Nullable - @Override - public String getString(@NotNull String path, @Nullable String def) { - Object result = get(path); - return result != null ? result.toString() : def; - } - - public char getChar(@NotNull String path) { - Object result = get(path); - return result != null && !result.toString().isEmpty() ? result.toString().charAt(0) : '\0'; - } - - public char getChar(@NotNull String path, char def) { - Object result = get(path); - return result != null && !result.toString().isEmpty() ? result.toString().charAt(0) : def; - } - - @Override - public int getInt(@NotNull String path) { - Object result = get(path); - return result instanceof Number ? ((Number) result).intValue() : 0; - } - - @Override - public int getInt(@NotNull String path, int def) { - Object result = get(path); - return result instanceof Number ? ((Number) result).intValue() : def; - } - - @Override - public boolean getBoolean(@NotNull String path) { - Object result = get(path); - return result instanceof Boolean ? (Boolean) result : false; - } - - @Override - public boolean getBoolean(@NotNull String path, boolean def) { - Object result = get(path); - return result instanceof Boolean ? (Boolean) result : def; - } - - @Override - public double getDouble(@NotNull String path) { - Object result = get(path); - return result instanceof Number ? ((Number) result).doubleValue() : 0; - } - - @Override - public double getDouble(@NotNull String path, double def) { - Object result = get(path); - return result instanceof Number ? ((Number) result).doubleValue() : def; - } - - @Override - public long getLong(@NotNull String path) { - Object result = get(path); - return result instanceof Number ? ((Number) result).longValue() : 0; - } - - @Override - public long getLong(@NotNull String path, long def) { - Object result = get(path); - return result instanceof Number ? ((Number) result).longValue() : def; - } - - @Nullable - @Override - public List getList(@NotNull String path) { - Object result = get(path); - return result instanceof List ? (List) result : null; - } - - @Nullable - @Override - public List getList(@NotNull String path, @Nullable List def) { - Object result = get(path); - return result instanceof List ? (List) result : def; - } - - @Nullable - public CompatibleMaterial getMaterial(@NotNull String path) { - String val = getString(path); - CompatibleMaterial mat = val != null ? CompatibleMaterial.getMaterial(val) : null; - return mat; - } - - @Nullable - public CompatibleMaterial getMaterial(@NotNull String path, @Nullable CompatibleMaterial def) { - String val = getString(path); - CompatibleMaterial mat = val != null ? CompatibleMaterial.getMaterial(val) : null; - return mat != null ? mat : def; - } - - @Nullable - @Override - public T getObject(@NotNull String path, @NotNull Class clazz) { - Object result = get(path); - return result != null && clazz.isInstance(result) ? clazz.cast(result) : null; - } - - @Nullable - @Override - public T getObject(@NotNull String path, @NotNull Class clazz, @Nullable T def) { - Object result = get(path); - return result != null && clazz.isInstance(result) ? clazz.cast(result) : def; - } - - @Override - public ConfigSection getConfigurationSection(@NotNull String path) { - Object result = get(path); - return result instanceof ConfigSection ? (ConfigSection) result : null; - } - - @NotNull - public ConfigSection getOrCreateConfigurationSection(@NotNull String path) { - Object result = get(path); - return result instanceof ConfigSection ? (ConfigSection) result : createSection(path); - } -} +package com.songoda.core.configuration; + +import com.songoda.core.compatibility.CompatibleMaterial; +import org.bukkit.configuration.Configuration; +import org.bukkit.configuration.MemoryConfiguration; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +/** + * Configuration for a specific node + * + * @author jascotty2 + * @since 2019-08-28 + */ +public class ConfigSection extends MemoryConfiguration { + final String fullPath, nodeKey; + final ConfigSection root; + final ConfigSection parent; + protected int indentation = 2; // between 2 and 9 (inclusive) + protected char pathChar = '.'; + final HashMap configComments; + final HashMap defaultComments; + final LinkedHashMap defaults; + final LinkedHashMap values; + /** + * Internal root state: if any configuration value has changed from file state + */ + boolean changed = false; + final boolean isDefault; + final Object lock = new Object(); + + ConfigSection() { + this.root = this; + this.parent = null; + isDefault = false; + nodeKey = fullPath = ""; + + configComments = new HashMap(); + defaultComments = new HashMap(); + defaults = new LinkedHashMap(); + values = new LinkedHashMap(); + } + + ConfigSection(ConfigSection root, ConfigSection parent, String nodeKey, boolean isDefault) { + this.root = root; + this.parent = parent; + this.nodeKey = nodeKey; + this.fullPath = nodeKey != null ? parent.fullPath + nodeKey + root.pathChar : parent.fullPath; + this.isDefault = isDefault; + configComments = defaultComments = null; + defaults = null; + values = null; + } + + public int getIndent() { + return root.indentation; + } + + public void setIndent(int indentation) { + root.indentation = indentation; + } + + protected void onChange() { + if (parent != null) { + root.onChange(); + } + } + + /** + * Sets the character used to separate configuration nodes.
+ * IMPORTANT: Do not change this after loading or adding ConfigurationSections! + * + * @param pathChar character to use + */ + public void setPathSeparator(char pathChar) { + if (!root.values.isEmpty() || !root.defaults.isEmpty()) { + throw new RuntimeException("Path change after config initialization"); + } + + root.pathChar = pathChar; + } + + public char getPathSeparator() { + return root.pathChar; + } + + /** + * @return The full key for this section node + */ + public String getKey() { + return !fullPath.endsWith(String.valueOf(root.pathChar)) ? fullPath : fullPath.substring(0, fullPath.length() - 1); + } + + /** + * @return The specific key that was used from the last node to get to this node + */ + public String getNodeKey() { + return nodeKey; + } + + /** + * Create the path required for this node to exist.
+ * DO NOT USE THIS IN A SYNCHRONIZED LOCK + * + * @param path full path of the node required. Eg, for foo.bar.node, this will create sections for foo and foo.bar + * @param useDefault set to true if this is a default value + */ + protected void createNodePath(@NotNull String path, boolean useDefault) { + if (path.indexOf(root.pathChar) != -1) { + // if any intermediate nodes don't exist, create them + String[] pathParts = path.split(Pattern.quote(String.valueOf(root.pathChar))); + StringBuilder nodePath = new StringBuilder(fullPath); + LinkedHashMap writeTo = useDefault ? root.defaults : root.values; + ConfigSection travelNode = this; + + synchronized (root.lock) { + for (int i = 0; i < pathParts.length - 1; ++i) { + final String node = (i != 0 ? nodePath.append(root.pathChar) : nodePath).append(pathParts[i]).toString(); + + if (!(writeTo.get(node) instanceof ConfigSection)) { + writeTo.put(node, travelNode = new ConfigSection(root, travelNode, pathParts[i], useDefault)); + } else { + travelNode = (ConfigSection) writeTo.get(node); + } + } + } + } + } + + @NotNull + public ConfigSection createDefaultSection(@NotNull String path) { + createNodePath(path, true); + ConfigSection section = new ConfigSection(root, this, path, true); + + synchronized (root.lock) { + root.defaults.put(fullPath + path, section); + } + + return section; + } + + @NotNull + public ConfigSection createDefaultSection(@NotNull String path, String... comment) { + createNodePath(path, true); + ConfigSection section = new ConfigSection(root, this, path, true); + + synchronized (root.lock) { + root.defaults.put(fullPath + path, section); + root.defaultComments.put(fullPath + path, new Comment(comment)); + } + + return section; + } + + @NotNull + public ConfigSection createDefaultSection(@NotNull String path, ConfigFormattingRules.CommentStyle commentStyle, String... comment) { + createNodePath(path, true); + ConfigSection section = new ConfigSection(root, this, path, true); + + synchronized (root.lock) { + root.defaults.put(fullPath + path, section); + root.defaultComments.put(fullPath + path, new Comment(commentStyle, comment)); + } + + return section; + } + + @NotNull + public ConfigSection setComment(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, String... lines) { + return setComment(path, lines != null ? new Comment(commentStyle, lines) : null); + } + + @NotNull + public ConfigSection setComment(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, @Nullable List lines) { + return setComment(path, lines != null ? new Comment(commentStyle, lines) : null); + } + + @NotNull + public ConfigSection setComment(@NotNull String path, @Nullable Comment comment) { + synchronized (root.lock) { + if (isDefault) { + root.defaultComments.put(fullPath + path, comment); + } else { + root.configComments.put(fullPath + path, comment); + } + } + + return this; + } + + @NotNull + public ConfigSection setDefaultComment(@NotNull String path, String... lines) { + return setDefaultComment(path, lines.length == 0 ? (List) null : Arrays.asList(lines)); + } + + @NotNull + public ConfigSection setDefaultComment(@NotNull String path, @Nullable List lines) { + synchronized (root.lock) { + root.defaultComments.put(fullPath + path, new Comment(lines)); + } + + return this; + } + + @NotNull + public ConfigSection setDefaultComment(@NotNull String path, ConfigFormattingRules.CommentStyle commentStyle, String... lines) { + return setDefaultComment(path, commentStyle, lines.length == 0 ? (List) null : Arrays.asList(lines)); + } + + @NotNull + public ConfigSection setDefaultComment(@NotNull String path, ConfigFormattingRules.CommentStyle commentStyle, @Nullable List lines) { + synchronized (root.lock) { + root.defaultComments.put(fullPath + path, new Comment(commentStyle, lines)); + } + + return this; + } + + @NotNull + public ConfigSection setDefaultComment(@NotNull String path, @Nullable Comment comment) { + synchronized (root.lock) { + root.defaultComments.put(fullPath + path, comment); + } + + return this; + } + + @Nullable + public Comment getComment(@NotNull String path) { + Comment result = root.configComments.get(fullPath + path); + + if (result == null) { + result = root.defaultComments.get(fullPath + path); + } + + return result; + } + + @Nullable + public String getCommentString(@NotNull String path) { + Comment result = root.configComments.get(fullPath + path); + + if (result == null) { + result = root.defaultComments.get(fullPath + path); + } + + return result != null ? result.toString() : null; + } + + @Override + public void addDefault(@NotNull String path, @Nullable Object value) { + createNodePath(path, true); + + synchronized (root.lock) { + root.defaults.put(fullPath + path, value); + } + } + + @Override + public void addDefaults(@NotNull Map defaults) { + //defaults.entrySet().stream().forEach(m -> root.defaults.put(fullPath + m.getKey(), m.getValue())); + defaults.entrySet().stream().forEach(m -> addDefault(m.getKey(), m.getValue())); + } + + @Override + public void setDefaults(Configuration c) { + if (fullPath.isEmpty()) { + root.defaults.clear(); + } else { + root.defaults.keySet().stream() + .filter(k -> k.startsWith(fullPath)) + .forEach(k -> root.defaults.remove(k)); + } + + addDefaults(c); + } + + @Override + public ConfigSection getDefaults() { + return new ConfigSection(root, this, null, true); + } + + @Override + public ConfigSection getDefaultSection() { + return new ConfigSection(root, this, null, true); + } + + @Override + public ConfigOptionsAdapter options() { + return new ConfigOptionsAdapter(root); + } + + @NotNull + @Override + public Set getKeys(boolean deep) { + LinkedHashSet result = new LinkedHashSet(); + int pathIndex = fullPath.lastIndexOf(root.pathChar); + + if (deep) { + result.addAll(root.defaults.keySet().stream() + .filter(k -> k.startsWith(fullPath)) + .map(k -> !k.endsWith(String.valueOf(root.pathChar)) ? k.substring(pathIndex + 1) : k.substring(pathIndex + 1, k.length() - 1)) + .collect(Collectors.toCollection(LinkedHashSet::new))); + result.addAll(root.values.keySet().stream() + .filter(k -> k.startsWith(fullPath)) + .map(k -> !k.endsWith(String.valueOf(root.pathChar)) ? k.substring(pathIndex + 1) : k.substring(pathIndex + 1, k.length() - 1)) + .collect(Collectors.toCollection(LinkedHashSet::new))); + } else { + result.addAll(root.defaults.keySet().stream() + .filter(k -> k.startsWith(fullPath) && k.lastIndexOf(root.pathChar) == pathIndex) + .map(k -> !k.endsWith(String.valueOf(root.pathChar)) ? k.substring(pathIndex + 1) : k.substring(pathIndex + 1, k.length() - 1)) + .collect(Collectors.toCollection(LinkedHashSet::new))); + result.addAll(root.values.keySet().stream() + .filter(k -> k.startsWith(fullPath) && k.lastIndexOf(root.pathChar) == pathIndex) + .map(k -> !k.endsWith(String.valueOf(root.pathChar)) ? k.substring(pathIndex + 1) : k.substring(pathIndex + 1, k.length() - 1)) + .collect(Collectors.toCollection(LinkedHashSet::new))); + } + + return result; + } + + @NotNull + @Override + public Map getValues(boolean deep) { + LinkedHashMap result = new LinkedHashMap(); + int pathIndex = fullPath.lastIndexOf(root.pathChar); + + if (deep) { + result.putAll((Map) root.defaults.entrySet().stream() + .filter(k -> k.getKey().startsWith(fullPath)) + .collect(Collectors.toMap( + e -> !e.getKey().endsWith(String.valueOf(root.pathChar)) ? e.getKey().substring(pathIndex + 1) : e.getKey().substring(pathIndex + 1, e.getKey().length() - 1), + e -> e.getValue(), + (v1, v2) -> { + throw new IllegalStateException(); + }, // never going to be merging keys + LinkedHashMap::new))); + + result.putAll((Map) root.values.entrySet().stream() + .filter(k -> k.getKey().startsWith(fullPath)) + .collect(Collectors.toMap( + e -> !e.getKey().endsWith(String.valueOf(root.pathChar)) ? e.getKey().substring(pathIndex + 1) : e.getKey().substring(pathIndex + 1, e.getKey().length() - 1), + e -> e.getValue(), + (v1, v2) -> { + throw new IllegalStateException(); + }, // never going to be merging keys + LinkedHashMap::new))); + } else { + result.putAll((Map) root.defaults.entrySet().stream() + .filter(k -> k.getKey().startsWith(fullPath) && k.getKey().lastIndexOf(root.pathChar) == pathIndex) + .collect(Collectors.toMap( + e -> !e.getKey().endsWith(String.valueOf(root.pathChar)) ? e.getKey().substring(pathIndex + 1) : e.getKey().substring(pathIndex + 1, e.getKey().length() - 1), + e -> e.getValue(), + (v1, v2) -> { + throw new IllegalStateException(); + }, // never going to be merging keys + LinkedHashMap::new))); + + result.putAll((Map) root.values.entrySet().stream() + .filter(k -> k.getKey().startsWith(fullPath) && k.getKey().lastIndexOf(root.pathChar) == pathIndex) + .collect(Collectors.toMap( + e -> !e.getKey().endsWith(String.valueOf(root.pathChar)) ? e.getKey().substring(pathIndex + 1) : e.getKey().substring(pathIndex + 1, e.getKey().length() - 1), + e -> e.getValue(), + (v1, v2) -> { + throw new IllegalStateException(); + }, // never going to be merging keys + LinkedHashMap::new))); + } + + return result; + } + + @NotNull + public List getSections(String path) { + ConfigSection rootSection = getConfigurationSection(path); + + if (rootSection == null) { + return Collections.EMPTY_LIST; + } + + ArrayList result = new ArrayList(); + rootSection.getKeys(false).stream() + .map(key -> rootSection.get(key)) + .filter(object -> object != null && object instanceof ConfigSection) + .forEachOrdered(object -> result.add((ConfigSection) object)); + + return result; + } + + @Override + public boolean contains(@NotNull String path) { + return root.defaults.containsKey(fullPath + path) || root.values.containsKey(fullPath + path); + } + + @Override + public boolean contains(@NotNull String path, boolean ignoreDefault) { + return (!ignoreDefault && root.defaults.containsKey(fullPath + path)) || root.values.containsKey(fullPath + path); + } + + @Override + public boolean isSet(@NotNull String path) { + return root.defaults.get(fullPath + path) != null || root.values.get(fullPath + path) != null; + } + + @Override + public String getCurrentPath() { + return fullPath.isEmpty() ? "" : fullPath.substring(0, fullPath.length() - 1); + } + + @Override + public String getName() { + if (fullPath.isEmpty()) { + return ""; + } + + String[] parts = fullPath.split(Pattern.quote(String.valueOf(root.pathChar))); + return parts[parts.length - 1]; + } + + @Override + public ConfigSection getRoot() { + return root; + } + + @Override + public ConfigSection getParent() { + return parent; + } + + @Nullable + @Override + public Object get(@NotNull String path) { + Object result = root.values.get(fullPath + path); + + if (result == null) { + result = root.defaults.get(fullPath + path); + } + + return result; + } + + @Nullable + @Override + public Object get(@NotNull String path, @Nullable Object def) { + Object result = root.values.get(fullPath + path); + + return result != null ? result : def; + } + + @Override + public void set(@NotNull String path, @Nullable Object value) { + if (isDefault) { + addDefault(path, value); + return; + } + + createNodePath(path, false); + Object last = null; + synchronized (root.lock) { + if (value != null) { + root.changed |= (last = root.values.put(fullPath + path, value)) != value; + } else { + root.changed |= (last = root.values.remove(fullPath + path)) != null; + } + } + + if (last != value && last != null && last instanceof ConfigSection) { + // clean up orphaned nodes + final String trim = fullPath + path + root.pathChar; + synchronized (root.lock) { + root.values.keySet().stream().filter(k -> k.startsWith(trim)).collect(Collectors.toSet()).stream() + .forEach(k -> root.values.remove(k)); + } + } + + onChange(); + } + + @NotNull + public ConfigSection set(@NotNull String path, @Nullable Object value, String... comment) { + set(path, value); + return setComment(path, null, comment); + } + + @NotNull + public ConfigSection set(@NotNull String path, @Nullable Object value, List comment) { + set(path, value); + return setComment(path, null, comment); + } + + @NotNull + public ConfigSection set(@NotNull String path, @Nullable Object value, @Nullable ConfigFormattingRules.CommentStyle commentStyle, String... comment) { + set(path, value); + return setComment(path, commentStyle, comment); + } + + @NotNull + public ConfigSection set(@NotNull String path, @Nullable Object value, @Nullable ConfigFormattingRules.CommentStyle commentStyle, List comment) { + set(path, value); + return setComment(path, commentStyle, comment); + } + + @NotNull + public ConfigSection setDefault(@NotNull String path, @Nullable Object value) { + addDefault(path, value); + return this; + } + + @NotNull + public ConfigSection setDefault(@NotNull String path, @Nullable Object value, String... comment) { + addDefault(path, value); + return setDefaultComment(path, comment); + } + + @NotNull + public ConfigSection setDefault(@NotNull String path, @Nullable Object value, List comment) { + addDefault(path, value); + return setDefaultComment(path, comment); + } + + @NotNull + public ConfigSection setDefault(@NotNull String path, @Nullable Object value, ConfigFormattingRules.CommentStyle commentStyle, String... comment) { + addDefault(path, value); + return setDefaultComment(path, commentStyle, comment); + } + + @NotNull + public ConfigSection setDefault(@NotNull String path, @Nullable Object value, ConfigFormattingRules.CommentStyle commentStyle, List comment) { + addDefault(path, value); + return setDefaultComment(path, commentStyle, comment); + } + + @NotNull + @Override + public ConfigSection createSection(@NotNull String path) { + createNodePath(path, false); + ConfigSection section = new ConfigSection(root, this, path, false); + + synchronized (root.lock) { + root.values.put(fullPath + path, section); + } + + root.changed = true; + onChange(); + + return section; + } + + @NotNull + public ConfigSection createSection(@NotNull String path, String... comment) { + return createSection(path, null, comment.length == 0 ? (List) null : Arrays.asList(comment)); + } + + @NotNull + public ConfigSection createSection(@NotNull String path, @Nullable List comment) { + return createSection(path, null, comment); + } + + @NotNull + public ConfigSection createSection(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, String... comment) { + return createSection(path, commentStyle, comment.length == 0 ? (List) null : Arrays.asList(comment)); + } + + @NotNull + public ConfigSection createSection(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, @Nullable List comment) { + createNodePath(path, false); + ConfigSection section = new ConfigSection(root, this, path, false); + + synchronized (root.lock) { + root.values.put(fullPath + path, section); + } + + setComment(path, commentStyle, comment); + root.changed = true; + onChange(); + + return section; + } + + @NotNull + @Override + public ConfigSection createSection(@NotNull String path, Map map) { + createNodePath(path, false); + ConfigSection section = new ConfigSection(root, this, path, false); + + synchronized (root.lock) { + root.values.put(fullPath + path, section); + } + + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() instanceof Map) { + section.createSection(entry.getKey().toString(), (Map) entry.getValue()); + continue; + } + + section.set(entry.getKey().toString(), entry.getValue()); + } + + root.changed = true; + onChange(); + + return section; + } + + @Nullable + @Override + public String getString(@NotNull String path) { + Object result = get(path); + + return result != null ? result.toString() : null; + } + + @Nullable + @Override + public String getString(@NotNull String path, @Nullable String def) { + Object result = get(path); + + return result != null ? result.toString() : def; + } + + public char getChar(@NotNull String path) { + Object result = get(path); + + return result != null && !result.toString().isEmpty() ? result.toString().charAt(0) : '\0'; + } + + public char getChar(@NotNull String path, char def) { + Object result = get(path); + + return result != null && !result.toString().isEmpty() ? result.toString().charAt(0) : def; + } + + @Override + public int getInt(@NotNull String path) { + Object result = get(path); + + return result instanceof Number ? ((Number) result).intValue() : 0; + } + + @Override + public int getInt(@NotNull String path, int def) { + Object result = get(path); + + return result instanceof Number ? ((Number) result).intValue() : def; + } + + @Override + public boolean getBoolean(@NotNull String path) { + Object result = get(path); + + return result instanceof Boolean ? (Boolean) result : false; + } + + @Override + public boolean getBoolean(@NotNull String path, boolean def) { + Object result = get(path); + + return result instanceof Boolean ? (Boolean) result : def; + } + + @Override + public double getDouble(@NotNull String path) { + Object result = get(path); + + return result instanceof Number ? ((Number) result).doubleValue() : 0; + } + + @Override + public double getDouble(@NotNull String path, double def) { + Object result = get(path); + + return result instanceof Number ? ((Number) result).doubleValue() : def; + } + + @Override + public long getLong(@NotNull String path) { + Object result = get(path); + + return result instanceof Number ? ((Number) result).longValue() : 0; + } + + @Override + public long getLong(@NotNull String path, long def) { + Object result = get(path); + + return result instanceof Number ? ((Number) result).longValue() : def; + } + + @Nullable + @Override + public List getList(@NotNull String path) { + Object result = get(path); + + return result instanceof List ? (List) result : null; + } + + @Nullable + @Override + public List getList(@NotNull String path, @Nullable List def) { + Object result = get(path); + + return result instanceof List ? (List) result : def; + } + + @Nullable + public CompatibleMaterial getMaterial(@NotNull String path) { + String val = getString(path); + + CompatibleMaterial mat = val != null ? CompatibleMaterial.getMaterial(val) : null; + + return mat; + } + + @Nullable + public CompatibleMaterial getMaterial(@NotNull String path, @Nullable CompatibleMaterial def) { + String val = getString(path); + + CompatibleMaterial mat = val != null ? CompatibleMaterial.getMaterial(val) : null; + + return mat != null ? mat : def; + } + + @Nullable + @Override + public T getObject(@NotNull String path, @NotNull Class clazz) { + Object result = get(path); + + return result != null && clazz.isInstance(result) ? clazz.cast(result) : null; + } + + @Nullable + @Override + public T getObject(@NotNull String path, @NotNull Class clazz, @Nullable T def) { + Object result = get(path); + + return result != null && clazz.isInstance(result) ? clazz.cast(result) : def; + } + + @Override + public ConfigSection getConfigurationSection(@NotNull String path) { + Object result = get(path); + + return result instanceof ConfigSection ? (ConfigSection) result : null; + } + + @NotNull + public ConfigSection getOrCreateConfigurationSection(@NotNull String path) { + Object result = get(path); + + return result instanceof ConfigSection ? (ConfigSection) result : createSection(path); + } +} diff --git a/Core/src/main/java/com/songoda/core/configuration/ConfigSetting.java b/Core/src/main/java/com/songoda/core/configuration/ConfigSetting.java index 239e0e2e..62d4bdcc 100644 --- a/Core/src/main/java/com/songoda/core/configuration/ConfigSetting.java +++ b/Core/src/main/java/com/songoda/core/configuration/ConfigSetting.java @@ -9,7 +9,6 @@ import java.util.List; import java.util.logging.Level; public class ConfigSetting { - final Config config; final String key; @@ -21,12 +20,14 @@ public class ConfigSetting { public ConfigSetting(@NotNull Config config, @NotNull String key, @NotNull Object defaultValue, String... comment) { this.config = config; this.key = key; + config.setDefault(key, defaultValue, comment); } public ConfigSetting(@NotNull Config config, @NotNull String key, @NotNull Object defaultValue, ConfigFormattingRules.CommentStyle commentStyle, String... comment) { this.config = config; this.key = key; + config.setDefault(key, defaultValue, commentStyle, comment); } diff --git a/Core/src/main/java/com/songoda/core/configuration/DataStoreObject.java b/Core/src/main/java/com/songoda/core/configuration/DataStoreObject.java index 5c1c573b..8c08d33a 100644 --- a/Core/src/main/java/com/songoda/core/configuration/DataStoreObject.java +++ b/Core/src/main/java/com/songoda/core/configuration/DataStoreObject.java @@ -1,35 +1,30 @@ -package com.songoda.core.configuration; - -import org.bukkit.configuration.ConfigurationSection; - -public interface DataStoreObject { - - /** - * @return a unique hashable instance of T to store this value under - */ - public abstract T getKey(); - - /** - * @return a unique identifier for saving this value with - */ - public abstract String getConfigKey(); - - /** - * Save this data to a ConfigurationSection - * - * @param sec - */ - public abstract void saveToSection(ConfigurationSection sec); - - /** - * @return true if this data has changed from the state saved to file - */ - public boolean hasChanged(); - - /** - * Mark this data as needing a save or not - * - * @param isChanged - */ - public void setChanged(boolean isChanged); -} +package com.songoda.core.configuration; + +import org.bukkit.configuration.ConfigurationSection; + +public interface DataStoreObject { + /** + * @return a unique hashable instance of T to store this value under + */ + public abstract T getKey(); + + /** + * @return a unique identifier for saving this value with + */ + public abstract String getConfigKey(); + + /** + * Save this data to a ConfigurationSection + */ + public abstract void saveToSection(ConfigurationSection sec); + + /** + * @return true if this data has changed from the state saved to file + */ + public boolean hasChanged(); + + /** + * Mark this data as needing a save or not + */ + public void setChanged(boolean isChanged); +} diff --git a/Core/src/main/java/com/songoda/core/configuration/SimpleDataStore.java b/Core/src/main/java/com/songoda/core/configuration/SimpleDataStore.java index c1947ccc..99a736ab 100644 --- a/Core/src/main/java/com/songoda/core/configuration/SimpleDataStore.java +++ b/Core/src/main/java/com/songoda/core/configuration/SimpleDataStore.java @@ -26,7 +26,6 @@ import java.util.logging.Level; * @since 2019-09-06 */ public class SimpleDataStore { - protected final Plugin plugin; protected final String filename, dirName; private final Function getFromSection; @@ -63,6 +62,7 @@ public class SimpleDataStore { this.file = new File(plugin.getDataFolder(), filename != null ? filename : "data.yml"); } } + return file; } @@ -99,10 +99,13 @@ public class SimpleDataStore { @Nullable public T remove(@NotNull Object key) { T temp; + synchronized (lock) { temp = data.remove(key); } + save(); + return temp; } @@ -119,11 +122,15 @@ public class SimpleDataStore { if (value == null) { return null; } + T temp; + synchronized (lock) { temp = data.remove(value.getKey()); } + save(); + return temp; } @@ -141,11 +148,15 @@ public class SimpleDataStore { if (value == null) { return null; } + T temp; + synchronized (lock) { temp = data.put(value.getKey(), value); } + save(); + return temp; } @@ -160,6 +171,7 @@ public class SimpleDataStore { if (value == null) { return; } + synchronized (lock) { for (int i = 0; i < value.length; ++i) { if (value[i] != null) { @@ -167,6 +179,7 @@ public class SimpleDataStore { } } } + save(); } @@ -181,6 +194,7 @@ public class SimpleDataStore { if (value == null) { return; } + synchronized (lock) { for (T v : value) { if (v != null) { @@ -188,6 +202,7 @@ public class SimpleDataStore { } } } + save(); } @@ -198,6 +213,7 @@ public class SimpleDataStore { if (!getFile().exists()) { return; } + try { YamlConfiguration f = new YamlConfiguration(); f.options().pathSeparator('\0'); @@ -205,6 +221,7 @@ public class SimpleDataStore { synchronized (lock) { data.clear(); + f.getValues(false).entrySet().stream() .filter(d -> d.getValue() instanceof ConfigurationSection) .map(Map.Entry::getValue) @@ -248,10 +265,13 @@ public class SimpleDataStore { saveTask = null; autosaveTimer = null; } + YamlConfiguration f = new YamlConfiguration(); + synchronized (lock) { data.values().stream().forEach(e -> e.saveToSection(f.createSection(e.getConfigKey()))); } + try { f.save(getFile()); data.values().stream().forEach(e -> e.setChanged(false)); @@ -261,7 +281,6 @@ public class SimpleDataStore { } class SaveTask extends TimerTask { - @Override public void run() { flushSave(); diff --git a/Core/src/main/java/com/songoda/core/configuration/editor/ConfigEditorGui.java b/Core/src/main/java/com/songoda/core/configuration/editor/ConfigEditorGui.java index 4d9e6b39..ffa947cf 100644 --- a/Core/src/main/java/com/songoda/core/configuration/editor/ConfigEditorGui.java +++ b/Core/src/main/java/com/songoda/core/configuration/editor/ConfigEditorGui.java @@ -32,7 +32,6 @@ import java.util.logging.Level; * @since 2019-08-31 */ public class ConfigEditorGui extends SimplePagedGui { - final JavaPlugin plugin; final String file; final MemoryConfiguration config; @@ -49,6 +48,7 @@ public class ConfigEditorGui extends SimplePagedGui { protected ConfigEditorGui(Player player, JavaPlugin plugin, Gui parent, String file, MemoryConfiguration config, ConfigurationSection node) { super(parent); + this.player = player; this.plugin = plugin; this.file = file; @@ -65,7 +65,7 @@ public class ConfigEditorGui extends SimplePagedGui { // if we have a ConfigSection, we can also grab comments try { configSection_getCommentString = node.getClass().getDeclaredMethod("getCommentString", String.class); - } catch (Exception ex) { + } catch (Exception ignore) { } // decorate header @@ -80,9 +80,10 @@ public class ConfigEditorGui extends SimplePagedGui { for (String key : node.getKeys(false)) { if (node.isConfigurationSection(key)) { sections.add(key); - } else { - settings.add(key); + continue; } + + settings.add(key); } // next we need to display the config settings @@ -95,11 +96,15 @@ public class ConfigEditorGui extends SimplePagedGui { // now display individual settings for (final String settingKey : settings) { final Object val = node.get(settingKey); - if (val == null) continue; - else if (val instanceof Boolean) { + if (val == null) { + continue; + } + + if (val instanceof Boolean) { // toggle switch setButton(index, configItem(CompatibleMaterial.LEVER, ChatColor.YELLOW + settingKey, node, settingKey, String.valueOf((Boolean) val), "Click to toggle this setting"), (event) -> this.toggle(event.slot, settingKey)); + if ((Boolean) val) { highlightItem(index); } @@ -159,9 +164,9 @@ public class ConfigEditorGui extends SimplePagedGui { } })); }); - } else { + } /* else { // idk. should we display uneditable values? - } + } */ ++index; } @@ -173,9 +178,14 @@ public class ConfigEditorGui extends SimplePagedGui { protected void updateValue(int clickCell, String path) { ItemStack item = inventory.getItem(clickCell); - if (item == null || item == AIR) return; + + if (item == null || item == AIR) { + return; + } + ItemMeta meta = item.getItemMeta(); Object val = node.get(path); + if (meta != null && val != null) { String valStr; if (val instanceof List) { @@ -183,6 +193,7 @@ public class ConfigEditorGui extends SimplePagedGui { } else { valStr = val.toString(); } + List lore = meta.getLore(); if (lore == null || lore.isEmpty()) { meta.setLore(Arrays.asList(valStr)); @@ -190,20 +201,24 @@ public class ConfigEditorGui extends SimplePagedGui { lore.set(0, valStr); meta.setLore(lore); } + item.setItemMeta(meta); setItem(clickCell, item); } + edits = true; } void toggle(int clickCell, String path) { boolean val = !node.getBoolean(path); node.set(path, val); + if (val) { setItem(clickCell, ItemUtils.addGlow(inventory.getItem(clickCell))); } else { setItem(clickCell, ItemUtils.removeGlow(inventory.getItem(clickCell))); } + updateValue(clickCell, path); } @@ -216,20 +231,24 @@ public class ConfigEditorGui extends SimplePagedGui { } else if (node.isLong(path)) { node.set(path, Long.parseLong(input)); } + updateValue(clickCell, path); - } catch (NumberFormatException e) { + } catch (NumberFormatException ex) { return false; } + return true; } void setMaterial(int clickCell, String path, ItemStack item) { CompatibleMaterial mat = CompatibleMaterial.getMaterial(item); + if (mat == null) { node.set(path, CompatibleMaterial.STONE.name()); } else { node.set(path, mat.name()); } + updateValue(clickCell, path); } @@ -242,6 +261,7 @@ public class ConfigEditorGui extends SimplePagedGui { if (!edits) { return; } + // could also check and call saveChanges() if (config instanceof FileConfiguration) { try { @@ -257,50 +277,59 @@ public class ConfigEditorGui extends SimplePagedGui { plugin.getLogger().log(Level.WARNING, "Unknown configuration type '" + config.getClass().getName() + "' - Please report this error!"); return; } + plugin.reloadConfig(); player.sendMessage(ChatColor.GREEN + "Config " + file + " saved!"); } private boolean isNumber(Object value) { - return value != null && ( - value instanceof Long - || value instanceof Integer - || value instanceof Float - || value instanceof Double); + return value != null && (value instanceof Long + || value instanceof Integer + || value instanceof Float + || value instanceof Double); } private boolean isMaterial(Object value) { CompatibleMaterial m; + return value instanceof String && value.toString().equals(value.toString().toUpperCase()) && (m = CompatibleMaterial.getMaterial(value.toString())) != null && m.isValidItem(); } protected ItemStack configItem(CompatibleMaterial type, String name, ConfigurationSection node, String path, String def) { String[] info = null; + if (configSection_getCommentString != null) { try { Object comment = configSection_getCommentString.invoke(node, path); + if (comment != null) { info = comment.toString().split("\n"); } - } catch (Exception ex) { + } catch (Exception ignore) { } } + return GuiUtils.createButtonItem(type, name, info != null ? info : (def != null ? def.split("\n") : null)); } protected ItemStack configItem(CompatibleMaterial type, String name, ConfigurationSection node, String path, String value, String def) { - if (value == null) value = ""; + if (value == null) { + value = ""; + } + String[] info = null; + if (configSection_getCommentString != null) { try { Object comment = configSection_getCommentString.invoke(node, path); if (comment != null) { info = (value + "\n" + comment.toString()).split("\n"); } - } catch (Exception ex) { + } catch (Exception ignore) { } } + return GuiUtils.createButtonItem(type, name, info != null ? info : (def != null ? (value + "\n" + def).split("\n") : null)); } } diff --git a/Core/src/main/java/com/songoda/core/configuration/editor/ConfigEditorListEditorGui.java b/Core/src/main/java/com/songoda/core/configuration/editor/ConfigEditorListEditorGui.java index 2fb6d418..79b5c2dc 100644 --- a/Core/src/main/java/com/songoda/core/configuration/editor/ConfigEditorListEditorGui.java +++ b/Core/src/main/java/com/songoda/core/configuration/editor/ConfigEditorListEditorGui.java @@ -17,7 +17,6 @@ import java.util.List; * @since 2019-08-31 */ public class ConfigEditorListEditorGui extends SimplePagedGui { - final ConfigEditorGui current; public boolean saveChanges = false; @@ -25,6 +24,7 @@ public class ConfigEditorListEditorGui extends SimplePagedGui { public ConfigEditorListEditorGui(ConfigEditorGui current, String key, List val) { super(current); + this.current = current; this.blankItem = current.getDefaultItem(); headerBackItem = footerBackItem = current.getHeaderBackItem(); @@ -59,6 +59,7 @@ public class ConfigEditorListEditorGui extends SimplePagedGui { void redraw() { page = 1; + // clear old display if (inventory != null) { for (Integer i : cellItems.keySet().toArray(new Integer[0])) { @@ -78,6 +79,7 @@ public class ConfigEditorListEditorGui extends SimplePagedGui { redraw(); }); } + // update display update(); } diff --git a/Core/src/main/java/com/songoda/core/configuration/editor/PluginConfigGui.java b/Core/src/main/java/com/songoda/core/configuration/editor/PluginConfigGui.java index 8d857920..60880bb0 100644 --- a/Core/src/main/java/com/songoda/core/configuration/editor/PluginConfigGui.java +++ b/Core/src/main/java/com/songoda/core/configuration/editor/PluginConfigGui.java @@ -24,7 +24,6 @@ import java.util.Map; * @since 2019-08-31 */ public class PluginConfigGui extends SimplePagedGui { - final JavaPlugin plugin; LinkedHashMap configs = new LinkedHashMap(); @@ -34,6 +33,7 @@ public class PluginConfigGui extends SimplePagedGui { public PluginConfigGui(SongodaPlugin plugin, Gui parent) { super(parent); + this.plugin = plugin; // collect list of plugins @@ -44,6 +44,7 @@ public class PluginConfigGui extends SimplePagedGui { configs.put(cfg.getFile().getName(), cfg); } } + init(); } @@ -76,6 +77,7 @@ public class PluginConfigGui extends SimplePagedGui { } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { // I guess not! } + init(); } diff --git a/Core/src/main/java/com/songoda/core/core/LocaleModule.java b/Core/src/main/java/com/songoda/core/core/LocaleModule.java index 4ea7bce7..3619434e 100644 --- a/Core/src/main/java/com/songoda/core/core/LocaleModule.java +++ b/Core/src/main/java/com/songoda/core/core/LocaleModule.java @@ -12,13 +12,16 @@ import java.util.logging.Level; import java.util.logging.Logger; public class LocaleModule implements PluginInfoModule { - @Override public void run(PluginInfo plugin) { - if (plugin.getJavaPlugin() == null || plugin.getSongodaId() <= 0) return; - JSONObject json = plugin.getJson(); + if (plugin.getJavaPlugin() == null || plugin.getSongodaId() <= 0) { + return; + } + try { + JSONObject json = plugin.getJson(); JSONArray files = (JSONArray) json.get("neededFiles"); + for (Object o : files) { JSONObject file = (JSONObject) o; @@ -33,6 +36,7 @@ public class LocaleModule implements PluginInfoModule { void downloadLocale(PluginInfo plugin, String link, String fileName) throws MalformedURLException, IOException { URL url = new URL(link); + HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11"); urlConnection.setRequestProperty("Accept", "*/*"); diff --git a/Core/src/main/java/com/songoda/core/core/PluginInfo.java b/Core/src/main/java/com/songoda/core/core/PluginInfo.java index 96a5f950..5469551f 100644 --- a/Core/src/main/java/com/songoda/core/core/PluginInfo.java +++ b/Core/src/main/java/com/songoda/core/core/PluginInfo.java @@ -9,7 +9,6 @@ import java.util.Collections; import java.util.List; public final class PluginInfo { - protected final JavaPlugin javaPlugin; protected final int songodaId; protected final String coreIcon; @@ -37,6 +36,7 @@ public final class PluginInfo { public void setLatestVersion(String latestVersion) { this.latestVersion = latestVersion; + hasUpdate = latestVersion != null && !latestVersion.isEmpty() && !javaPlugin.getDescription().getVersion().equalsIgnoreCase(latestVersion); } @@ -82,6 +82,7 @@ public final class PluginInfo { public PluginInfoModule addModule(PluginInfoModule module) { modules.add(module); + return module; } diff --git a/Core/src/main/java/com/songoda/core/core/PluginInfoModule.java b/Core/src/main/java/com/songoda/core/core/PluginInfoModule.java index f6c32293..237fd82e 100644 --- a/Core/src/main/java/com/songoda/core/core/PluginInfoModule.java +++ b/Core/src/main/java/com/songoda/core/core/PluginInfoModule.java @@ -1,6 +1,5 @@ package com.songoda.core.core; public interface PluginInfoModule { - void run(PluginInfo plugin); } diff --git a/Core/src/main/java/com/songoda/core/core/SongodaCoreCommand.java b/Core/src/main/java/com/songoda/core/core/SongodaCoreCommand.java index d0463959..945c594f 100644 --- a/Core/src/main/java/com/songoda/core/core/SongodaCoreCommand.java +++ b/Core/src/main/java/com/songoda/core/core/SongodaCoreCommand.java @@ -9,7 +9,6 @@ import org.bukkit.entity.Player; import java.util.List; public class SongodaCoreCommand extends AbstractCommand { - protected GuiManager guiManager; public SongodaCoreCommand() { @@ -22,10 +21,12 @@ public class SongodaCoreCommand extends AbstractCommand { if (guiManager == null || guiManager.isClosed()) { guiManager = new GuiManager(SongodaCore.getHijackedPlugin()); } + guiManager.showGUI((Player) sender, new SongodaCoreOverviewGUI()); } else { sender.sendMessage("/songoda diag"); } + return ReturnType.SUCCESS; } diff --git a/Core/src/main/java/com/songoda/core/core/SongodaCoreDiagCommand.java b/Core/src/main/java/com/songoda/core/core/SongodaCoreDiagCommand.java index 3fbbe741..28ed2644 100644 --- a/Core/src/main/java/com/songoda/core/core/SongodaCoreDiagCommand.java +++ b/Core/src/main/java/com/songoda/core/core/SongodaCoreDiagCommand.java @@ -14,7 +14,6 @@ import java.text.DecimalFormat; import java.util.List; public class SongodaCoreDiagCommand extends AbstractCommand { - private final DecimalFormat format = new DecimalFormat("##.##"); private Object serverInstance; @@ -27,36 +26,38 @@ public class SongodaCoreDiagCommand extends AbstractCommand { serverInstance = ClassMapping.MINECRAFT_SERVER.getClazz().getMethod("getServer").invoke(null); tpsField = serverInstance.getClass().getField("recentTps"); } catch (NoSuchFieldException | SecurityException | IllegalAccessException | IllegalArgumentException - | InvocationTargetException | NoSuchMethodException e) { - e.printStackTrace(); + | InvocationTargetException | NoSuchMethodException ex) { + ex.printStackTrace(); } } @Override protected ReturnType runCommand(CommandSender sender, String... args) { - sender.sendMessage(""); sender.sendMessage("Songoda Diagnostics Information"); sender.sendMessage(""); sender.sendMessage("Plugins:"); + for (PluginInfo plugin : SongodaCore.getPlugins()) { sender.sendMessage(plugin.getJavaPlugin().getName() + " (" + plugin.getJavaPlugin().getDescription().getVersion() + " Core " + plugin.getCoreLibraryVersion() + ")"); } + sender.sendMessage(""); sender.sendMessage("Server Version: " + Bukkit.getVersion()); sender.sendMessage("NMS: " + ServerProject.getServerVersion() + " " + ServerVersion.getServerVersionString()); sender.sendMessage("Operating System: " + System.getProperty("os.name")); sender.sendMessage("Allocated Memory: " + format.format(Runtime.getRuntime().maxMemory() / (1024 * 1024)) + "Mb"); sender.sendMessage("Online Players: " + Bukkit.getOnlinePlayers().size()); + if (tpsField != null) { try { double[] tps = ((double[]) tpsField.get(serverInstance)); sender.sendMessage("TPS from last 1m, 5m, 15m: " + format.format(tps[0]) + ", " + format.format(tps[1]) + ", " + format.format(tps[2])); - } catch (IllegalAccessException e) { - e.printStackTrace(); + } catch (IllegalAccessException ex) { + ex.printStackTrace(); } } diff --git a/Core/src/main/java/com/songoda/core/core/SongodaCoreOverviewGUI.java b/Core/src/main/java/com/songoda/core/core/SongodaCoreOverviewGUI.java index 48c9cde0..c5b743f3 100644 --- a/Core/src/main/java/com/songoda/core/core/SongodaCoreOverviewGUI.java +++ b/Core/src/main/java/com/songoda/core/core/SongodaCoreOverviewGUI.java @@ -11,7 +11,6 @@ import org.bukkit.event.inventory.ClickType; import java.util.List; final class SongodaCoreOverviewGUI extends Gui { - protected SongodaCoreOverviewGUI() { List plugins = SongodaCore.getPlugins(); // could do pages, too, but don't think we'll have that many at a time for a while @@ -23,6 +22,7 @@ final class SongodaCoreOverviewGUI extends Gui { for (int i = 0; i < plugins.size(); i++) { final PluginInfo plugin = plugins.get(i); + if (plugin.hasUpdate()) { setButton(i, GuiUtils.createButtonItem(plugin.icon != null ? plugin.icon : CompatibleMaterial.STONE, ChatColor.GOLD + plugin.getJavaPlugin().getName(), @@ -38,17 +38,19 @@ final class SongodaCoreOverviewGUI extends Gui { ClickType.LEFT, (event) -> event.player.sendMessage(plugin.getMarketplaceLink())); setAction(i, ClickType.RIGHT, (event) -> event.manager.showGUI(event.player, new PluginConfigGui(plugin.getJavaPlugin(), event.gui))); highlightItem(i); - } else { - setButton(i, GuiUtils.createButtonItem(plugin.icon != null ? plugin.icon : CompatibleMaterial.STONE, - ChatColor.GOLD + plugin.getJavaPlugin().getName(), - ChatColor.GRAY + "Installed Version: " + plugin.getJavaPlugin().getDescription().getVersion(), - "", - ChatColor.GOLD + "Click for the marketplace page link.", - ChatColor.GOLD + "Right Click to edit plugin settings." - ), - ClickType.LEFT, (event) -> event.player.sendMessage(plugin.getMarketplaceLink())); - setAction(i, ClickType.RIGHT, (event) -> event.manager.showGUI(event.player, new PluginConfigGui(plugin.getJavaPlugin(), event.gui))); + + continue; } + + setButton(i, GuiUtils.createButtonItem(plugin.icon != null ? plugin.icon : CompatibleMaterial.STONE, + ChatColor.GOLD + plugin.getJavaPlugin().getName(), + ChatColor.GRAY + "Installed Version: " + plugin.getJavaPlugin().getDescription().getVersion(), + "", + ChatColor.GOLD + "Click for the marketplace page link.", + ChatColor.GOLD + "Right Click to edit plugin settings." + ), + ClickType.LEFT, (event) -> event.player.sendMessage(plugin.getMarketplaceLink())); + setAction(i, ClickType.RIGHT, (event) -> event.manager.showGUI(event.player, new PluginConfigGui(plugin.getJavaPlugin(), event.gui))); } } } diff --git a/Core/src/main/java/com/songoda/core/database/DataManagerAbstract.java b/Core/src/main/java/com/songoda/core/database/DataManagerAbstract.java index d0b3b7a8..d8264150 100644 --- a/Core/src/main/java/com/songoda/core/database/DataManagerAbstract.java +++ b/Core/src/main/java/com/songoda/core/database/DataManagerAbstract.java @@ -64,9 +64,10 @@ public class DataManagerAbstract { ResultSet result = statement.executeQuery(query); result.next(); id = result.getInt(1); - } catch (SQLException e) { - e.printStackTrace(); + } catch (SQLException ex) { + ex.printStackTrace(); } + return id; } @@ -150,17 +151,24 @@ public class DataManagerAbstract { */ @Deprecated public void queueAsync(Runnable runnable, String queueKey) { - if (queueKey == null) return; + if (queueKey == null) { + return; + } + List queue = queues.computeIfAbsent(queueKey, t -> new LinkedList<>()); queue.add(runnable); - if (queue.size() == 1) runQueue(queueKey); + + if (queue.size() == 1) { + runQueue(queueKey); + } } @Deprecated private void runQueue(String queueKey) { doQueue(queueKey, (s) -> { - if (!queues.get(queueKey).isEmpty()) + if (!queues.get(queueKey).isEmpty()) { runQueue(queueKey); + } }); } diff --git a/Core/src/main/java/com/songoda/core/database/DataMigration.java b/Core/src/main/java/com/songoda/core/database/DataMigration.java index 7b8dfb03..922d3c83 100644 --- a/Core/src/main/java/com/songoda/core/database/DataMigration.java +++ b/Core/src/main/java/com/songoda/core/database/DataMigration.java @@ -4,7 +4,6 @@ import java.sql.Connection; import java.sql.SQLException; public abstract class DataMigration { - private final int revision; public DataMigration(int revision) { diff --git a/Core/src/main/java/com/songoda/core/database/DataMigrationManager.java b/Core/src/main/java/com/songoda/core/database/DataMigrationManager.java index b285b82c..2dded47a 100644 --- a/Core/src/main/java/com/songoda/core/database/DataMigrationManager.java +++ b/Core/src/main/java/com/songoda/core/database/DataMigrationManager.java @@ -8,7 +8,6 @@ import java.util.List; import java.util.stream.Collectors; public class DataMigrationManager { - private final List migrations; private final DatabaseConnector databaseConnector; private final DataManagerAbstract dataManagerAbstract; @@ -65,23 +64,23 @@ public class DataMigrationManager { // Grab required migrations int finalCurrentMigration = currentMigration; - List requiredMigrations = this.migrations - .stream() + List requiredMigrations = this.migrations.stream() .filter(x -> x.getRevision() > finalCurrentMigration) .sorted(Comparator.comparingInt(DataMigration::getRevision)) .collect(Collectors.toList()); // Nothing to migrate, abort - if (requiredMigrations.isEmpty()) + if (requiredMigrations.isEmpty()) { return; + } // Migrate the data - for (DataMigration dataMigration : requiredMigrations) + for (DataMigration dataMigration : requiredMigrations) { dataMigration.migrate(connection, this.dataManagerAbstract.getTablePrefix()); + } // Set the new current migration to be the highest migrated to - currentMigration = requiredMigrations - .stream() + currentMigration = requiredMigrations.stream() .map(DataMigration::getRevision) .max(Integer::compareTo) .orElse(-1); diff --git a/Core/src/main/java/com/songoda/core/database/DatabaseConnector.java b/Core/src/main/java/com/songoda/core/database/DatabaseConnector.java index 894df693..2ca3220c 100644 --- a/Core/src/main/java/com/songoda/core/database/DatabaseConnector.java +++ b/Core/src/main/java/com/songoda/core/database/DatabaseConnector.java @@ -4,7 +4,6 @@ import java.sql.Connection; import java.sql.SQLException; public interface DatabaseConnector { - /** * Checks if the connection to the database has been created * diff --git a/Core/src/main/java/com/songoda/core/database/MySQLConnector.java b/Core/src/main/java/com/songoda/core/database/MySQLConnector.java index b99cf93a..e0a4cbc8 100644 --- a/Core/src/main/java/com/songoda/core/database/MySQLConnector.java +++ b/Core/src/main/java/com/songoda/core/database/MySQLConnector.java @@ -1,6 +1,5 @@ package com.songoda.core.database; -import com.songoda.core.SongodaCore; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import org.bukkit.plugin.Plugin; @@ -9,7 +8,6 @@ import java.sql.Connection; import java.sql.SQLException; public class MySQLConnector implements DatabaseConnector { - private final Plugin plugin; private HikariDataSource hikari; private boolean initializedSuccessfully; diff --git a/Core/src/main/java/com/songoda/core/database/SQLiteConnector.java b/Core/src/main/java/com/songoda/core/database/SQLiteConnector.java index af8b0bf6..e5878286 100644 --- a/Core/src/main/java/com/songoda/core/database/SQLiteConnector.java +++ b/Core/src/main/java/com/songoda/core/database/SQLiteConnector.java @@ -8,7 +8,6 @@ import java.sql.DriverManager; import java.sql.SQLException; public class SQLiteConnector implements DatabaseConnector { - private final Plugin plugin; private final String connectionString; private Connection connection; @@ -19,8 +18,8 @@ public class SQLiteConnector implements DatabaseConnector { try { Class.forName("org.sqlite.JDBC"); // This is required to put here for Spigot 1.10 and below to force class load - } catch (ClassNotFoundException e) { - e.printStackTrace(); + } catch (ClassNotFoundException ex) { + ex.printStackTrace(); } } diff --git a/Core/src/main/java/com/songoda/core/gui/AnvilGui.java b/Core/src/main/java/com/songoda/core/gui/AnvilGui.java index a52a2c0c..6483a775 100644 --- a/Core/src/main/java/com/songoda/core/gui/AnvilGui.java +++ b/Core/src/main/java/com/songoda/core/gui/AnvilGui.java @@ -1,128 +1,131 @@ -package com.songoda.core.gui; - -import com.songoda.core.compatibility.CompatibleMaterial; -import com.songoda.core.gui.methods.Clickable; -import com.songoda.core.nms.NmsManager; -import com.songoda.core.nms.anvil.AnvilCore; -import com.songoda.core.nms.anvil.CustomAnvil; -import org.bukkit.entity.Player; -import org.bukkit.event.inventory.ClickType; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.Arrays; -import java.util.List; - -/** - * Anvil GUI for text prompts - * - * @author jascotty2 - * @since 2019-09-15 - */ -public class AnvilGui extends Gui { - - final Player player; - CustomAnvil anvil; - List endPrompt = null; - - public AnvilGui(Player player) { - this.player = player; - } - - public AnvilGui(Player player, Gui parent) { - super(parent); - this.player = player; - } - - @NotNull - public AnvilGui setAction(@Nullable Clickable action) { - return (AnvilGui) setAction(2, action); - } - - @NotNull - public AnvilGui setAction(@Nullable ClickType type, @Nullable Clickable action) { - return (AnvilGui) setAction(2, type, action); - } - - protected void open() { - anvil.open(); - } - - public AnvilGui setInput(ItemStack item) { - return (AnvilGui) this.setItem(0, item); - } - - public ItemStack getInput() { - return this.getItem(0); - } - - public AnvilGui setOutput(ItemStack item) { - return (AnvilGui) this.setItem(2, item); - } - - public AnvilGui setOutputPrompt(String str) { - endPrompt = Arrays.asList(str); - return this; - } - - public AnvilGui setOutputPrompt(String... str) { - endPrompt = Arrays.asList(str); - return this; - } - - public AnvilGui setOutputPrompt(List str) { - endPrompt = str; - return this; - } - - void updateOutputPrompt() { - final ItemStack in; - if (endPrompt != null && (in = cellItems.get(0)) != null) { - setItem(2, GuiUtils.createButtonItem(in, endPrompt)); - } - } - - public ItemStack getOutput() { - return this.getItem(2); - } - - public String getInputText() { - return anvil != null ? anvil.getRenameText() : null; - } - - @NotNull - @Override - protected Inventory generateInventory(@NotNull GuiManager manager) { - this.guiManager = manager; - - createInventory(); - ItemStack item; - if ((item = cellItems.get(0)) != null) { - inventory.setItem(0, item); - } else if ((item = cellItems.get(1)) != null) { - inventory.setItem(1, item); - } else if (!acceptsItems) { - cellItems.put(0, item = GuiUtils.createButtonItem(CompatibleMaterial.PAPER, " ", " ")); - inventory.setItem(0, item); - } - if ((item = cellItems.get(2)) != null) { - inventory.setItem(2, item); - } - - return inventory; - } - - @Override - protected void createInventory() { - AnvilCore nms = NmsManager.getAnvil(); - if (nms != null) { - anvil = nms.createAnvil(player, new GuiHolder(guiManager, this)); - anvil.setCustomTitle(title); - anvil.setLevelCost(0); - inventory = anvil.getInventory(); - anvil.setOnChange(this::updateOutputPrompt); - } - } -} +package com.songoda.core.gui; + +import com.songoda.core.compatibility.CompatibleMaterial; +import com.songoda.core.gui.methods.Clickable; +import com.songoda.core.nms.NmsManager; +import com.songoda.core.nms.anvil.AnvilCore; +import com.songoda.core.nms.anvil.CustomAnvil; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Arrays; +import java.util.List; + +/** + * Anvil GUI for text prompts + * + * @author jascotty2 + * @since 2019-09-15 + */ +public class AnvilGui extends Gui { + final Player player; + CustomAnvil anvil; + List endPrompt = null; + + public AnvilGui(Player player) { + this.player = player; + } + + public AnvilGui(Player player, Gui parent) { + super(parent); + + this.player = player; + } + + @NotNull + public AnvilGui setAction(@Nullable Clickable action) { + return (AnvilGui) setAction(2, action); + } + + @NotNull + public AnvilGui setAction(@Nullable ClickType type, @Nullable Clickable action) { + return (AnvilGui) setAction(2, type, action); + } + + protected void open() { + anvil.open(); + } + + public AnvilGui setInput(ItemStack item) { + return (AnvilGui) this.setItem(0, item); + } + + public ItemStack getInput() { + return this.getItem(0); + } + + public AnvilGui setOutput(ItemStack item) { + return (AnvilGui) this.setItem(2, item); + } + + public AnvilGui setOutputPrompt(String str) { + endPrompt = Arrays.asList(str); + return this; + } + + public AnvilGui setOutputPrompt(String... str) { + endPrompt = Arrays.asList(str); + return this; + } + + public AnvilGui setOutputPrompt(List str) { + endPrompt = str; + return this; + } + + void updateOutputPrompt() { + final ItemStack in; + if (endPrompt != null && (in = cellItems.get(0)) != null) { + setItem(2, GuiUtils.createButtonItem(in, endPrompt)); + } + } + + public ItemStack getOutput() { + return this.getItem(2); + } + + public String getInputText() { + return anvil != null ? anvil.getRenameText() : null; + } + + @NotNull + @Override + protected Inventory generateInventory(@NotNull GuiManager manager) { + this.guiManager = manager; + + createInventory(); + ItemStack item; + if ((item = cellItems.get(0)) != null) { + inventory.setItem(0, item); + } else if ((item = cellItems.get(1)) != null) { + inventory.setItem(1, item); + } else if (!acceptsItems) { + cellItems.put(0, item = GuiUtils.createButtonItem(CompatibleMaterial.PAPER, " ", " ")); + inventory.setItem(0, item); + } + if ((item = cellItems.get(2)) != null) { + inventory.setItem(2, item); + } + + return inventory; + } + + @Override + protected void createInventory() { + AnvilCore nms = NmsManager.getAnvil(); + + if (nms != null) { + anvil = nms.createAnvil(player, new GuiHolder(guiManager, this)); + anvil.setCustomTitle(title); + anvil.setLevelCost(0); + + inventory = anvil.getInventory(); + + anvil.setOnChange(this::updateOutputPrompt); + } + } +} diff --git a/Core/src/main/java/com/songoda/core/gui/CustomizableGui.java b/Core/src/main/java/com/songoda/core/gui/CustomizableGui.java index 13cf9f22..b68e757b 100644 --- a/Core/src/main/java/com/songoda/core/gui/CustomizableGui.java +++ b/Core/src/main/java/com/songoda/core/gui/CustomizableGui.java @@ -25,7 +25,6 @@ import java.util.Map; import java.util.stream.Collectors; public class CustomizableGui extends Gui { - private static boolean showGuiKeys = false; private int activationCount = 0; @@ -41,7 +40,10 @@ public class CustomizableGui extends Gui { if (!loadedGuis.containsKey(guiKey) || showGuiKeys) { File localeFolder = new File(plugin.getDataFolder(), "gui/"); - if (!localeFolder.exists()) localeFolder.mkdir(); + + if (!localeFolder.exists()) { + localeFolder.mkdir(); + } Config config = new Config(plugin, "gui/" + guiKey + ".yml"); config.load(); @@ -59,6 +61,7 @@ public class CustomizableGui extends Gui { .setDefaultComment("overrides", "For information on how to apply overrides please visit", "https://wiki.songoda.com/Gui"); + config.saveChanges(); } @@ -66,6 +69,7 @@ public class CustomizableGui extends Gui { config.setDefault("disabled", Arrays.asList("example3", "example4", "example5"), "All keys on this list will be disabled. You can add any items key here", "if you no longer want that item in the GUI."); + config.saveChanges(); } @@ -74,24 +78,28 @@ public class CustomizableGui extends Gui { this.customContent = customContent; int rows = config.getInt("overrides.__ROWS__", -1); - if (rows != -1) + if (rows != -1) { customContent.setRows(rows); + } for (ConfigSection section : config.getSections("overrides")) { - if (section.contains("row") || section.contains("col") - || section.contains("mirrorrow") || section.contains("mirrorcol")) { - if (section.contains("mirrorrow") || section.contains("mirrorcol")) + if (section.contains("row") || + section.contains("col") || + section.contains("mirrorrow") || + section.contains("mirrorcol")) { + if (section.contains("mirrorrow") || section.contains("mirrorcol")) { customContent.addButton(section.getNodeKey(), section.getInt("row", -1), section.getInt("col", -1), section.getBoolean("mirrorrow", false), section.getBoolean("mirrorcol", false), section.isSet("item") ? CompatibleMaterial.getMaterial(section.getString("item")) : null); - else + } else { customContent.addButton(section.getNodeKey(), section.getInt("row", -1), section.getInt("col", -1), section.getString("title", null), section.isSet("lore") ? section.getStringList("lore") : null, section.isSet("item") ? CompatibleMaterial.getMaterial(section.getString("item")) : null); + } } else { customContent.addButton(section.getNodeKey(), section.getString("position", "-1"), section.getString("title", null), @@ -100,34 +108,42 @@ public class CustomizableGui extends Gui { } } - for (String disabled : config.getStringList("disabled")) + for (String disabled : config.getStringList("disabled")) { customContent.disableButton(disabled); + } } else { customContent = loadedGuis.get(guiKey); } + setPrivateDefaultAction(event -> { - if (event.clickType == ClickType.SHIFT_RIGHT) + if (event.clickType == ClickType.SHIFT_RIGHT) { activationCount++; + } + if (activationCount >= 8 && event.player.hasPermission("songoda.admin")) { showGuiKeys = !showGuiKeys; activationCount = 0; + event.player.sendMessage("Gui keys " + (showGuiKeys ? "enabled" : "disabled") + "."); } }); - if (customContent.isButtonCustomized("__DEFAULT__")) + if (customContent.isButtonCustomized("__DEFAULT__")) { blankItem = GuiUtils.getBorderItem(customContent.getCustomizedButton("__DEFAULT__").item); + } } @NotNull public Gui setRows(int rows) { int customRows = customContent.getRows(); + return super.setRows(customRows != -1 ? customRows : rows); } @NotNull protected Inventory generateInventory(@NotNull GuiManager manager) { applyCustomItems(); + return super.generateInventory(manager); } @@ -137,322 +153,493 @@ public class CustomizableGui extends Gui { } private void applyCustomItems() { - for (CustomButton customButton : customContent.getCustomButtons().values()) - if (customButton instanceof MirrorFill) + for (CustomButton customButton : customContent.getCustomButtons().values()) { + if (customButton instanceof MirrorFill) { applyCustomItem(customButton); - for (CustomButton customButton : customContent.getCustomButtons().values()) - if (!(customButton instanceof MirrorFill)) + } + } + + for (CustomButton customButton : customContent.getCustomButtons().values()) { + if (!(customButton instanceof MirrorFill)) { applyCustomItem(customButton); + } + } } private void applyCustomItem(CustomButton customButton) { - if (customButton.row != -1 && customButton.col != -1) - if (customButton instanceof MirrorFill) + if (customButton.row != -1 && customButton.col != -1) { + if (customButton instanceof MirrorFill) { mirrorFill(customButton.key, customButton.row, customButton.col, ((MirrorFill) customButton).mirrorRow, ((MirrorFill) customButton).mirrorCol, customButton.createItem()); - else + } else { setItem(customButton.key, customButton.row, customButton.col, customButton.createItem()); - else - for (Integer position : customButton.positions) + } + } else { + for (Integer position : customButton.positions) { setItem(customButton.key, position, customButton.createItem()); + } + } } @NotNull public Gui setDefaultItem(@Nullable ItemStack item) { - if (item == null) return this; - applyShowGuiKeys("__DEFAULT__", item); - if (customContent.isButtonCustomized("__DEFAULT__")) + if (item == null) { return this; + } + + applyShowGuiKeys("__DEFAULT__", item); + + if (customContent.isButtonCustomized("__DEFAULT__")) { + return this; + } + return super.setDefaultItem(item); } @NotNull public Gui setItem(@NotNull String key, int cell, @Nullable ItemStack item) { List cells = Collections.singletonList(cell); - if (customContent.isButtonDisabled(key)) return this; + + if (customContent.isButtonDisabled(key)) { + return this; + } + applyShowGuiKeys(key, item); + if (customContent.isButtonCustomized(key)) { CustomButton btn = customContent.getCustomizedButton(key); cells = btn.applyPosition(cell); btn.applyItem(item); } - for (int c : cells) + + for (int c : cells) { setItem(c, item); + } + return this; } @NotNull public Gui setItem(@NotNull String key, int row, int col, @Nullable ItemStack item) { final int cell = col + row * inventoryType.columns; + return setItem(key, cell, item); } public Gui mirrorFill(@NotNull String key, int row, int col, boolean mirrorRow, boolean mirrorCol, @NotNull ItemStack item) { - if (customContent.isButtonDisabled(key)) return this; + if (customContent.isButtonDisabled(key)) { + return this; + } + ItemStack newItem = item.clone(); boolean isShow = applyShowGuiKeys(key, newItem); + if (customContent.isButtonCustomized(key)) { CustomButton btn = customContent.getCustomizedButton(key); row = btn.applyPositionRow(row); col = btn.applyPositionCol(col); - if (btn.applyItem(newItem)) + + if (btn.applyItem(newItem)) { isShow = true; + } + if (btn instanceof MirrorFill) { MirrorFill mf = (MirrorFill) btn; mirrorRow = mf.mirrorRow; mirrorCol = mf.mirrorCol; } } + return mirrorFill(row, col, mirrorRow, mirrorCol, isShow ? newItem : item); } @NotNull public Gui highlightItem(@NotNull String key, int cell) { List cells = Collections.singletonList(cell); - if (customContent.isButtonDisabled(key)) return this; - if (customContent.isButtonCustomized(key)) - cells = customContent.getCustomizedButton(key).applyPosition(cell); - for (int c : cells) + if (customContent.isButtonDisabled(key)) { + return this; + } + + if (customContent.isButtonCustomized(key)) { + cells = customContent.getCustomizedButton(key).applyPosition(cell); + } + + for (int c : cells) { highlightItem(c); + } + return this; } @NotNull public Gui highlightItem(@NotNull String key, int row, int col) { - if (customContent.isButtonDisabled(key)) return this; + if (customContent.isButtonDisabled(key)) { + return this; + } + final int cell = col + row * inventoryType.columns; + return highlightItem(key, cell); } @NotNull public Gui removeHighlight(@NotNull String key, int cell) { List cells = Collections.singletonList(cell); - if (customContent.isButtonDisabled(key)) return this; - if (customContent.isButtonCustomized(key)) - cells = customContent.getCustomizedButton(key).applyPosition(cell); - for (int c : cells) + if (customContent.isButtonDisabled(key)) { + return this; + } + + if (customContent.isButtonCustomized(key)) { + cells = customContent.getCustomizedButton(key).applyPosition(cell); + } + + for (int c : cells) { removeHighlight(c); + } + return this; } @NotNull public Gui removeHighlight(@NotNull String key, int row, int col) { - if (customContent.isButtonDisabled(key)) return this; + if (customContent.isButtonDisabled(key)) { + return this; + } + final int cell = col + row * inventoryType.columns; + return removeHighlight(key, cell); } @NotNull public Gui updateItemLore(@NotNull String key, int row, int col, @NotNull String... lore) { - if (customContent.isButtonDisabled(key)) return this; + if (customContent.isButtonDisabled(key)) { + return this; + } + return updateItemLore(key, col + row * inventoryType.columns, lore); } @NotNull public Gui updateItemLore(@NotNull String key, int cell, @NotNull String... lore) { List cells = Collections.singletonList(cell); - if (customContent.isButtonDisabled(key)) return this; - if (customContent.isButtonCustomized(key)) - cells = customContent.getCustomizedButton(key).applyPosition(cell); - for (int c : cells) + if (customContent.isButtonDisabled(key)) { + return this; + } + + if (customContent.isButtonCustomized(key)) { + cells = customContent.getCustomizedButton(key).applyPosition(cell); + } + + for (int c : cells) { updateItemLore(c, lore); + } + return this; } @NotNull public Gui updateItemLore(@NotNull String key, int row, int col, @Nullable List lore) { - if (customContent.isButtonDisabled(key)) return this; + if (customContent.isButtonDisabled(key)) { + return this; + } + return updateItemLore(key, col + row * inventoryType.columns, lore); } @NotNull public Gui updateItemLore(@NotNull String key, int cell, @Nullable List lore) { List cells = Collections.singletonList(cell); - if (customContent.isButtonDisabled(key)) return this; - if (customContent.isButtonCustomized(key)) - cells = customContent.getCustomizedButton(key).applyPosition(cell); - for (int c : cells) + if (customContent.isButtonDisabled(key)) { + return this; + } + + if (customContent.isButtonCustomized(key)) { + cells = customContent.getCustomizedButton(key).applyPosition(cell); + } + + for (int c : cells) { updateItemLore(c, lore); + } + return this; } @NotNull public Gui updateItemName(@NotNull String key, int row, int col, @Nullable String name) { - if (customContent.isButtonDisabled(key)) return this; + if (customContent.isButtonDisabled(key)) { + return this; + } + return updateItemName(key, col + row * inventoryType.columns, name); } @NotNull public Gui updateItemName(@NotNull String key, int cell, @Nullable String name) { List cells = Collections.singletonList(cell); - if (customContent.isButtonDisabled(key)) return this; - if (customContent.isButtonCustomized(key)) - cells = customContent.getCustomizedButton(key).applyPosition(cell); - for (int c : cells) + if (customContent.isButtonDisabled(key)) { + return this; + } + + if (customContent.isButtonCustomized(key)) { + cells = customContent.getCustomizedButton(key).applyPosition(cell); + } + + for (int c : cells) { updateItemName(c, name); + } + return this; } @NotNull public Gui updateItem(@NotNull String key, int row, int col, @Nullable String name, @NotNull String... lore) { - if (customContent.isButtonDisabled(key)) return this; + if (customContent.isButtonDisabled(key)) { + return this; + } + return updateItem(key, col + row * inventoryType.columns, name, lore); } @NotNull public Gui updateItem(@NotNull String key, int cell, @Nullable String name, @NotNull String... lore) { - if (customContent.isButtonDisabled(key)) return this; + if (customContent.isButtonDisabled(key)) { + return this; + } + return updateItem(key, cell, name, Arrays.asList(lore)); } @NotNull public Gui updateItem(@NotNull String key, int row, int col, @Nullable String name, @Nullable List lore) { - if (customContent.isButtonDisabled(key)) return this; + if (customContent.isButtonDisabled(key)) { + return this; + } + return updateItem(key, col + row * inventoryType.columns, name, lore); } @NotNull public Gui updateItem(@NotNull String key, int cell, @NotNull String name, @Nullable List lore) { List cells = Collections.singletonList(cell); - if (customContent.isButtonDisabled(key)) return this; - lore = applyShowGuiKeys(key, lore); - if (customContent.isButtonCustomized(key)) - cells = customContent.getCustomizedButton(key).applyPosition(cell); - for (int c : cells) + if (customContent.isButtonDisabled(key)) { + return this; + } + + lore = applyShowGuiKeys(key, lore); + + if (customContent.isButtonCustomized(key)) { + cells = customContent.getCustomizedButton(key).applyPosition(cell); + } + + for (int c : cells) { updateItem(c, name, lore); + } + return this; } @NotNull public Gui updateItem(@NotNull String key, int row, int col, @NotNull ItemStack itemTo, @Nullable String title, @NotNull String... lore) { - if (customContent.isButtonDisabled(key)) return this; + if (customContent.isButtonDisabled(key)) { + return this; + } + return updateItem(key, col + row * inventoryType.columns, itemTo, title, lore); } @NotNull public Gui updateItem(@NotNull String key, int cell, @NotNull ItemStack itemTo, @Nullable String title, @NotNull String... lore) { List cells = Collections.singletonList(cell); - if (customContent.isButtonDisabled(key)) return this; - if (customContent.isButtonCustomized(key)) - cells = customContent.getCustomizedButton(key).applyPosition(cell); - for (int c : cells) + if (customContent.isButtonDisabled(key)) { + return this; + } + + if (customContent.isButtonCustomized(key)) { + cells = customContent.getCustomizedButton(key).applyPosition(cell); + } + + for (int c : cells) { updateItem(c, itemTo, title, lore); + } + return this; } @NotNull public Gui updateItem(@NotNull String key, int row, int col, @NotNull CompatibleMaterial itemTo, @Nullable String title, @NotNull String... lore) { - if (customContent.isButtonDisabled(key)) return this; + if (customContent.isButtonDisabled(key)) { + return this; + } + return updateItem(key, col + row * inventoryType.columns, itemTo, title, lore); } @NotNull public Gui updateItem(@NotNull String key, int cell, @NotNull CompatibleMaterial itemTo, @Nullable String title, @Nullable String... lore) { List cells = Collections.singletonList(cell); - if (customContent.isButtonDisabled(key)) return this; - if (customContent.isButtonCustomized(key)) - cells = customContent.getCustomizedButton(key).applyPosition(cell); - for (int c : cells) + if (customContent.isButtonDisabled(key)) { + return this; + } + + if (customContent.isButtonCustomized(key)) { + cells = customContent.getCustomizedButton(key).applyPosition(cell); + } + + for (int c : cells) { updateItem(key, c, itemTo, title, lore); + } + return this; } @NotNull public Gui updateItem(@NotNull String key, int row, int col, @NotNull ItemStack itemTo, @Nullable String title, @Nullable List lore) { - if (customContent.isButtonDisabled(key)) return this; + if (customContent.isButtonDisabled(key)) { + return this; + } + return updateItem(key, col + row * inventoryType.columns, itemTo, title, lore); } @NotNull public Gui updateItem(@NotNull String key, int cell, @NotNull ItemStack itemTo, @Nullable String title, @Nullable List lore) { List cells = Collections.singletonList(cell); - if (customContent.isButtonDisabled(key)) return this; - if (customContent.isButtonCustomized(key)) - cells = customContent.getCustomizedButton(key).applyPosition(cell); - for (int c : cells) + if (customContent.isButtonDisabled(key)) { + return this; + } + + if (customContent.isButtonCustomized(key)) { + cells = customContent.getCustomizedButton(key).applyPosition(cell); + } + + for (int c : cells) { updateItem(key, c, itemTo, title, lore); + } + return this; } @NotNull public Gui updateItem(@NotNull String key, int row, int col, @NotNull CompatibleMaterial itemTo, @Nullable String title, @Nullable List lore) { - if (customContent.isButtonDisabled(key)) return this; + if (customContent.isButtonDisabled(key)) { + return this; + } + return updateItem(key, col + row * inventoryType.columns, itemTo, title, lore); } @NotNull public Gui updateItem(@NotNull String key, int cell, @NotNull CompatibleMaterial itemTo, @Nullable String title, @Nullable List lore) { List cells = Collections.singletonList(cell); - if (customContent.isButtonDisabled(key)) return this; - if (customContent.isButtonCustomized(key)) - cells = customContent.getCustomizedButton(key).applyPosition(cell); - for (int c : cells) + if (customContent.isButtonDisabled(key)) { + return this; + } + + if (customContent.isButtonCustomized(key)) { + cells = customContent.getCustomizedButton(key).applyPosition(cell); + } + + for (int c : cells) { updateItem(key, c, itemTo, title, lore); + } + return this; } @NotNull public Gui setAction(@NotNull String key, int cell, @Nullable Clickable action) { - if (customContent.isButtonDisabled(key)) return this; + if (customContent.isButtonDisabled(key)) { + return this; + } + setConditional(key, cell, null, action); + return this; } @NotNull public Gui setAction(@NotNull String key, int row, int col, @Nullable Clickable action) { - if (customContent.isButtonDisabled(key)) return this; + if (customContent.isButtonDisabled(key)) { + return this; + } + setConditional(key, col + row * inventoryType.columns, null, action); + return this; } @NotNull public Gui setAction(@NotNull String key, int cell, @Nullable ClickType type, @Nullable Clickable action) { - if (customContent.isButtonDisabled(key)) return this; + if (customContent.isButtonDisabled(key)) { + return this; + } + setConditional(key, cell, type, action); + return this; } @NotNull public Gui setAction(@NotNull String key, int row, int col, @Nullable ClickType type, @Nullable Clickable action) { - if (customContent.isButtonDisabled(key)) return this; + if (customContent.isButtonDisabled(key)) { + return this; + } + setConditional(key, col + row * inventoryType.columns, type, action); + return this; } @NotNull public Gui clearActions(@NotNull String key, int cell) { List cells = Collections.singletonList(cell); - if (customContent.isButtonDisabled(key)) return this; - if (customContent.isButtonCustomized(key)) - cells = customContent.getCustomizedButton(key).applyPosition(cell); - for (int c : cells) + if (customContent.isButtonDisabled(key)) { + return this; + } + + if (customContent.isButtonCustomized(key)) { + cells = customContent.getCustomizedButton(key).applyPosition(cell); + } + + for (int c : cells) { clearActions(c); + } + return this; } @NotNull public Gui clearActions(@NotNull String key, int row, int col) { - if (customContent.isButtonDisabled(key)) return this; + if (customContent.isButtonDisabled(key)) { + return this; + } + return clearActions(key, col + row * inventoryType.columns); } @NotNull public Gui setButton(@NotNull String key, int cell, ItemStack item, @Nullable Clickable action) { List cells = Collections.singletonList(cell); - if (customContent.isButtonDisabled(key)) return this; + + if (customContent.isButtonDisabled(key)) { + return this; + } + applyShowGuiKeys(key, item); + if (customContent.isButtonCustomized(key)) { CustomButton btn = customContent.getCustomizedButton(key); cells = btn.applyPosition(cell); @@ -463,59 +650,83 @@ public class CustomizableGui extends Gui { setItem(c, item); setConditional(c, null, action); } + return this; } @NotNull public Gui setButton(@NotNull String key, int row, int col, @Nullable ItemStack item, @Nullable Clickable action) { - if (customContent.isButtonDisabled(key)) return this; + if (customContent.isButtonDisabled(key)) { + return this; + } + return setButton(key, col + row * inventoryType.columns, item, action); } @NotNull public Gui setButton(@NotNull String key, int cell, @Nullable ItemStack item, @Nullable ClickType type, @Nullable Clickable action) { List cells = Collections.singletonList(cell); - if (customContent.isButtonDisabled(key)) return this; + + if (customContent.isButtonDisabled(key)) { + return this; + } + applyShowGuiKeys(key, item); + if (customContent.isButtonCustomized(key)) { CustomButton btn = customContent.getCustomizedButton(key); cells = btn.applyPosition(cell); btn.applyItem(item); } - for (int c : cells) + for (int c : cells) { setButton(c, item, type, action); + } + return this; } @NotNull public Gui setButton(@NotNull String key, int row, int col, @Nullable ItemStack item, @Nullable ClickType type, @Nullable Clickable action) { - if (customContent.isButtonDisabled(key)) return this; + if (customContent.isButtonDisabled(key)) { + return this; + } + return setButton(key, col + row + inventoryType.columns, item, type, action); } protected void setConditional(@NotNull String key, int cell, @Nullable ClickType type, @Nullable Clickable action) { List cells = Collections.singletonList(cell); - if (customContent.isButtonDisabled(key)) return; - if (customContent.isButtonCustomized(key)) - cells = customContent.getCustomizedButton(key).applyPosition(cell); - for (int c : cells) + if (customContent.isButtonDisabled(key)) { + return; + } + + if (customContent.isButtonCustomized(key)) { + cells = customContent.getCustomizedButton(key).applyPosition(cell); + } + + for (int c : cells) { setConditional(c, type, action); + } } public Gui setNextPage(ItemStack item) { applyShowGuiKeys("__NEXT__", item); - if (customContent.isButtonCustomized("__NEXT__")) + + if (customContent.isButtonCustomized("__NEXT__")) { customContent.getCustomizedButton("__NEXT__").applyItem(item); + } return super.setNextPage(item); } public Gui setPrevPage(ItemStack item) { applyShowGuiKeys("__PREV__", item); - if (customContent.isButtonCustomized("__PREV__")) + + if (customContent.isButtonCustomized("__PREV__")) { customContent.getCustomizedButton("__PREV__").applyItem(item); + } return super.setPrevPage(item); } @@ -523,66 +734,89 @@ public class CustomizableGui extends Gui { @NotNull public Gui setNextPage(int cell, @NotNull ItemStack item) { List cells = Collections.singletonList(cell); + applyShowGuiKeys("__NEXT__", item); + if (customContent.isButtonCustomized("__NEXT__")) { CustomButton btn = customContent.getCustomizedButton("__NEXT__"); cells = btn.applyPosition(cell); btn.applyItem(item); } - for (int c : cells) + for (int c : cells) { return super.setNextPage(c, item); + } + return this; } @NotNull public Gui setNextPage(int row, int col, @NotNull ItemStack item) { applyShowGuiKeys("__NEXT__", item); + return setNextPage(col + row * inventoryType.columns, item); } @NotNull public Gui setPrevPage(int cell, @NotNull ItemStack item) { List cells = Collections.singletonList(cell); + applyShowGuiKeys("__PREV__", item); + if (customContent.isButtonCustomized("__PREV__")) { CustomButton btn = customContent.getCustomizedButton("__PREV__"); cells = btn.applyPosition(cell); btn.applyItem(item); } - for (int c : cells) + for (int c : cells) { super.setPrevPage(c, item); + } + return this; } @NotNull public Gui setPrevPage(int row, int col, @NotNull ItemStack item) { applyShowGuiKeys("__PREV__", item); + return setPrevPage(col + row * inventoryType.columns, item); } private boolean applyShowGuiKeys(String key, ItemStack item) { - if (!showGuiKeys) return false; + if (!showGuiKeys) { + return false; + } + ItemMeta meta = item.getItemMeta(); - if (meta == null) meta = Bukkit.getItemFactory().getItemMeta(item.getType()); + if (meta == null) { + meta = Bukkit.getItemFactory().getItemMeta(item.getType()); + } + List lore = new ArrayList<>(Collections.singletonList("Key: " + key)); - if (meta.hasLore()) + + if (meta.hasLore()) { lore.addAll(meta.getLore()); + } + meta.setLore(lore); item.setItemMeta(meta); + return true; } private List applyShowGuiKeys(String key, List lore) { - if (!showGuiKeys) return lore; + if (!showGuiKeys) { + return lore; + } + List newLore = new ArrayList<>(Collections.singletonList("Key: " + key)); newLore.addAll(lore); + return newLore; } private class CustomButton { - private final String key; private final List positions; @@ -619,32 +853,47 @@ public class CustomizableGui extends Gui { } public boolean applyItem(ItemStack item) { - if (item == null) return false; + if (item == null) { + return false; + } + item.setType(this.item.getMaterial()); - if (ServerVersion.isServerVersionAtOrBelow(ServerVersion.V1_13)) + + if (ServerVersion.isServerVersionAtOrBelow(ServerVersion.V1_13)) { item.setDurability(this.item.getData()); + } + applyMeta(item); + return true; } public ItemStack createItem() { ItemStack item = this.item.getItem(); applyMeta(item); + return item; } private void applyMeta(ItemStack item) { ItemMeta meta = item.getItemMeta(); - if (title != null) + + if (title != null) { meta.setDisplayName(TextUtils.formatText(title)); - if (lore != null) + } + + if (lore != null) { meta.setLore(TextUtils.formatText(lore)); + } + item.setItemMeta(meta); } public List applyPosition(int cell) { - if (row != -1 && col != -1) + if (row != -1 && col != -1) { return Collections.singletonList(col + row * inventoryType.columns); + } + return positions == null ? Collections.singletonList(cell) : positions; } @@ -658,12 +907,12 @@ public class CustomizableGui extends Gui { } private class MirrorFill extends CustomButton { - private final boolean mirrorRow; private final boolean mirrorCol; public MirrorFill(String key, int row, int col, boolean mirrorRow, boolean mirrorCol, CompatibleMaterial item) { super(key, row, col, null, null, item); + this.mirrorRow = mirrorRow; this.mirrorCol = mirrorCol; } @@ -678,7 +927,6 @@ public class CustomizableGui extends Gui { } private class CustomContent { - private final String guiKey; private final Map customizedButtons = new HashMap<>(); private final Map customButtons = new HashMap<>(); @@ -708,29 +956,39 @@ public class CustomizableGui extends Gui { public void addButton(String key, String position, String title, List lore, CompatibleMaterial item) { List positions = Arrays.stream(position.split(",")) - .map(Integer::parseInt).collect(Collectors.toList()); + .map(Integer::parseInt) + .collect(Collectors.toList()); CustomButton customButton = new CustomButton(key, positions, title, lore, item); - if (key.startsWith("custom_")) + + if (key.startsWith("custom_")) { customButtons.put(key, customButton); - else - customizedButtons.put(key, customButton); + return; + } + + customizedButtons.put(key, customButton); } public void addButton(String key, int row, int col, String title, List lore, CompatibleMaterial item) { CustomButton customButton = new CustomButton(key, row, col, title, lore, item); - if (key.startsWith("custom_")) + + if (key.startsWith("custom_")) { customButtons.put(key, customButton); - else - customizedButtons.put(key, customButton); + return; + } + + customizedButtons.put(key, customButton); } public void addButton(String key, int row, int col, boolean mirrorRow, boolean mirrorCol, CompatibleMaterial item) { MirrorFill mirrorFill = new MirrorFill(key, row, col, mirrorRow, mirrorCol, item); - if (key.startsWith("custom_")) + + if (key.startsWith("custom_")) { customButtons.put(key, mirrorFill); - else - customizedButtons.put(key, mirrorFill); + return; + } + + customizedButtons.put(key, mirrorFill); } public boolean isButtonCustomized(String key) { diff --git a/Core/src/main/java/com/songoda/core/gui/DoubleGui.java b/Core/src/main/java/com/songoda/core/gui/DoubleGui.java index bfaa4dee..81729873 100644 --- a/Core/src/main/java/com/songoda/core/gui/DoubleGui.java +++ b/Core/src/main/java/com/songoda/core/gui/DoubleGui.java @@ -1,562 +1,595 @@ -package com.songoda.core.gui; - -import com.songoda.core.compatibility.CompatibleMaterial; -import com.songoda.core.gui.events.GuiClickEvent; -import com.songoda.core.gui.events.GuiDropItemEvent; -import com.songoda.core.gui.methods.Clickable; -import com.songoda.core.gui.methods.Closable; -import com.songoda.core.gui.methods.Droppable; -import com.songoda.core.gui.methods.Openable; -import com.songoda.core.gui.methods.Pagable; -import com.songoda.core.utils.ItemUtils; -import org.bukkit.entity.HumanEntity; -import org.bukkit.entity.Player; -import org.bukkit.event.inventory.ClickType; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * TODO: does not restore inventory if server crashes while player inventory is open - * Method to fix: save inv + ender slot to file, store paper in ender inv with name of cache file, check for paper item in slot when loading - * Or just manually manage all inventories in a file and remove when restored - * - * @author jascotty2 - * @since 2019-08-25 - */ -public class DoubleGui extends Gui { - - protected boolean startStashed = true; - protected int playerRows = 4; - protected Map stash = new HashMap(); - - public DoubleGui() { - super(GuiType.STANDARD); - allowDropItems = false; - } - - public DoubleGui(GuiType type) { - super(type); - allowDropItems = false; - } - - public DoubleGui(int rows) { - super(rows); - allowDropItems = false; - } - - public DoubleGui(int rows, Gui parent) { - super(rows, parent); - allowDropItems = false; - } - - public DoubleGui(Gui parent) { - super(parent); - allowDropItems = false; - } - - public int getPlayerRows() { - return playerRows; - } - - // 9 -> 0 -> 54 - // 18 -> 9 -> 63 - // 27 -> 18 -> 72 - // 0 -> 27 -> 81 - // offset required to make click translations - int clickOffset(int cell) { - return 54 + (cell < 9 ? cell + 27 : cell - 9); - } - - // offset required to make inventory translations - int invOffset(int cell) { - return 54 + cell; - } - - public void setStartStashed(boolean startStashed) { - this.startStashed = startStashed; - } - - public DoubleGui setPlayerUnlocked(int cell) { - unlockedCells.put(invOffset(cell), true); - return this; - } - - public DoubleGui setPlayerUnlocked(int row, int col) { - unlockedCells.put(invOffset(col + row * 9), true); - return this; - } - - public DoubleGui setPlayerUnlocked(int cell, boolean open) { - unlockedCells.put(invOffset(cell), open); - return this; - } - - public DoubleGui setPlayerUnlocked(int row, int col, boolean open) { - unlockedCells.put(invOffset(col + row * 9), open); - return this; - } - - public DoubleGui setPlayerUnlockedRange(int cellFirst, int cellLast) { - final int last = invOffset(cellLast); - for (int cell = invOffset(cellFirst); cell <= last; ++cell) { - unlockedCells.put(cell, true); - } - return this; - } - - public DoubleGui setPlayerUnlockedRange(int cellFirst, int cellLast, boolean open) { - final int last = invOffset(cellLast); - for (int cell = invOffset(cellFirst); cell <= last; ++cell) { - unlockedCells.put(cell, open); - } - return this; - } - - public DoubleGui setPlayerUnlockedRange(int cellRowFirst, int cellColFirst, int cellRowLast, int cellColLast) { - final int last = invOffset(cellColLast + cellRowLast * 9); - for (int cell = invOffset(cellColFirst + cellRowFirst * 9); cell <= last; ++cell) { - unlockedCells.put(cell, true); - } - return this; - } - - public DoubleGui setPlayerUnlockedRange(int cellRowFirst, int cellColFirst, int cellRowLast, int cellColLast, boolean open) { - final int last = invOffset(cellColLast + cellRowLast * 9); - for (int cell = invOffset(cellColFirst + cellRowFirst * 9); cell <= last; ++cell) { - unlockedCells.put(cell, open); - } - return this; - } - - public DoubleGui setPlayerItem(int cell, ItemStack item) { - cellItems.put(invOffset(cell), item); - if (open && cell >= 0 && cell < 36) { - cell = cell >= 27 ? cell - 27 : cell + 9; - for (HumanEntity e : inventory.getViewers()) { - e.getInventory().setItem(cell, item); - } - } - return this; - } - - public DoubleGui setPlayerItem(int row, int col, ItemStack item) { - int cell = col + row * 9; - cellItems.put(invOffset(cell), item); - if (open && cell >= 0 && cell < 36) { - cell = cell >= 27 ? cell - 27 : cell + 9; - for (HumanEntity e : inventory.getViewers()) { - e.getInventory().setItem(cell, item); - } - } - return this; - } - - public DoubleGui highlightPlayerItem(int cell) { - final int invCell = invOffset(cell); - ItemStack item = cellItems.get(invCell); - if (item != null) { - setPlayerItem(cell, ItemUtils.addGlow(item)); - } - return this; - } - - public DoubleGui highlightPlayerItem(int row, int col) { - final int cell = col + row * 9; - final int invCell = invOffset(cell); - ItemStack item = cellItems.get(invCell); - if (item != null) { - setPlayerItem(cell, ItemUtils.addGlow(item)); - } - return this; - } - - public DoubleGui setPlayerAction(int cell, Clickable action) { - setConditional(invOffset(cell), null, action); - return this; - } - - public DoubleGui setPlayerAction(int row, int col, Clickable action) { - setConditional(invOffset(col + row * 9), null, action); - return this; - } - - public DoubleGui setPlayerAction(int cell, ClickType type, Clickable action) { - setConditional(invOffset(cell), type, action); - return this; - } - - public DoubleGui setPlayerAction(int row, int col, ClickType type, Clickable action) { - setConditional(invOffset(col + row * 9), type, action); - return this; - } - - public DoubleGui setPlayerActionForRange(int cellFirst, int cellLast, Clickable action) { - for (int cell = cellFirst; cell <= cellLast; ++cell) { - setConditional(invOffset(cell), null, action); - } - return this; - } - - public DoubleGui setPlayerActionForRange(int cellRowFirst, int cellColFirst, int cellRowLast, int cellColLast, Clickable action) { - final int last = cellColLast + cellRowLast * 9; - for (int cell = cellColFirst + cellRowFirst * 9; cell <= last; ++cell) { - setConditional(invOffset(cell), null, action); - } - return this; - } - - public DoubleGui setPlayerActionForRange(int cellFirst, int cellLast, ClickType type, Clickable action) { - for (int cell = cellFirst; cell <= cellLast; ++cell) { - setConditional(invOffset(cell), type, action); - } - return this; - } - - public DoubleGui setPlayerActionForRange(int cellRowFirst, int cellColFirst, int cellRowLast, int cellColLast, ClickType type, Clickable action) { - final int last = cellColLast + cellRowLast * 9; - for (int cell = cellColFirst + cellRowFirst * 9; cell <= last; ++cell) { - setConditional(invOffset(cell), type, action); - } - return this; - } - - public DoubleGui clearPlayerActions(int cell) { - conditionalButtons.remove(cell = invOffset(cell)); - return this; - } - - public DoubleGui clearPlayerActions(int row, int col) { - final int cell = invOffset(col + row * 9); - conditionalButtons.remove(cell); - return this; - } - - public DoubleGui setPlayerButton(int cell, ItemStack item, Clickable action) { - setPlayerItem(cell, item); - setConditional(invOffset(cell), null, action); - return this; - } - - public DoubleGui setPlayerButton(int row, int col, ItemStack item, Clickable action) { - final int cell = col + row * 9; - setPlayerItem(cell, item); - setConditional(invOffset(cell), null, action); - return this; - } - - public DoubleGui setPlayerButton(int cell, ItemStack item, ClickType type, Clickable action) { - setItem(cell, item); - setConditional(invOffset(cell), type, action); - return this; - } - - public DoubleGui setPlayerButton(int row, int col, ItemStack item, ClickType type, Clickable action) { - final int cell = col + row * 9; - setPlayerItem(cell, item); - setConditional(invOffset(cell), type, action); - return this; - } - - @Override - protected boolean onClickPlayerInventory(GuiManager manager, Player player, Inventory openInv, InventoryClickEvent event) { - final int cell = event.getSlot(), offsetCell = clickOffset(cell); - Map conditionals = conditionalButtons.get(offsetCell); - Clickable button; - if (conditionals != null - && ((button = conditionals.get(event.getClick())) != null || (button = conditionals.get(null)) != null)) { - button.onClick(new GuiClickEvent(manager, this, player, event, cell, true)); - } else { - // no event for this button - return false; - } - event.setCancelled(!unlockedCells.entrySet().stream().anyMatch(e -> offsetCell == e.getKey() && e.getValue())); - return true; - } - - @Override - protected boolean onClickOutside(GuiManager manager, Player player, InventoryClickEvent event) { - if (dropper != null) { - return dropper.onDrop(new GuiDropItemEvent(manager, this, player, event)); - } - // do not allow by default - return false; - } - - @Override - public void onOpen(GuiManager manager, Player player) { - // replace the player's inventory - if (startStashed) - stashItems(player); - - // other opening functions - super.onOpen(manager, player); - } - - @Override - public void onClose(GuiManager manager, Player player) { - // restore the player's inventory - restoreStash(player); - - // other closing functions - super.onClose(manager, player); - } - - protected void restoreStash(Player player) { - if (stash.containsKey(player)) { - player.getInventory().setContents(stash.remove(player)); - player.updateInventory(); - } - } - - protected void stashItems(Player player) { - if (!stash.containsKey(player)) { - stash.put(player, player.getInventory().getContents().clone()); - player.getInventory().clear(); - } - } - - /* - ********************************************************* - * Other functions from GUI that we don't actually override - ********************************************************* - */ - @Override - public DoubleGui setAcceptsItems(boolean acceptsItems) { - return (DoubleGui) super.setAcceptsItems(acceptsItems); - } - - @Override - public DoubleGui setUnlocked(int cell) { - return (DoubleGui) super.setUnlocked(cell); - } - - @Override - public DoubleGui setUnlocked(int cell, boolean open) { - return (DoubleGui) super.setUnlocked(cell, open); - } - - @Override - public DoubleGui setUnlocked(int row, int col) { - return (DoubleGui) super.setUnlocked(row, col); - } - - @Override - public DoubleGui setUnlocked(int row, int col, boolean open) { - return (DoubleGui) super.setUnlocked(row, col, open); - } - - @Override - public DoubleGui setUnlockedRange(int cellFirst, int cellLast) { - return (DoubleGui) super.setUnlockedRange(cellFirst, cellLast); - } - - @Override - public DoubleGui setUnlockedRange(int cellRowFirst, int cellColFirst, int cellRowLast, int cellColLast) { - return (DoubleGui) super.setUnlockedRange(cellRowFirst, cellColFirst, cellRowLast, cellColLast); - } - - @Override - public DoubleGui setAllowDrops(boolean allow) { - return (DoubleGui) super.setAllowDrops(allow); - } - - @Override - public DoubleGui setAllowClose(boolean allow) { - return (DoubleGui) super.setAllowClose(allow); - } - - @Override - public DoubleGui setTitle(String title) { - return (DoubleGui) super.setTitle(title); - } - - @Override - public DoubleGui setRows(int rows) { - return (DoubleGui) super.setRows(rows); - } - - @Override - public DoubleGui setDefaultItem(ItemStack item) { - return (DoubleGui) super.setDefaultItem(item); - } - - @Override - public DoubleGui setItem(int cell, ItemStack item) { - return (DoubleGui) super.setItem(cell, item); - } - - @Override - public DoubleGui setItem(int row, int col, ItemStack item) { - return (DoubleGui) super.setItem(row, col, item); - } - - @Override - public DoubleGui highlightItem(int cell) { - return (DoubleGui) super.highlightItem(cell); - } - - @Override - public DoubleGui highlightItem(int row, int col) { - return (DoubleGui) super.highlightItem(row, col); - } - - @Override - public DoubleGui updateItem(int cell, String name, String... lore) { - return (DoubleGui) super.updateItem(cell, name, lore); - } - - @Override - public DoubleGui updateItem(int row, int col, String name, List lore) { - return (DoubleGui) super.updateItem(col + row * 9, name, lore); - } - - @Override - public DoubleGui updateItem(int cell, String name, List lore) { - return (DoubleGui) super.updateItem(cell, name, lore); - } - - @Override - public DoubleGui updateItem(int row, int col, ItemStack itemTo, String title, String... lore) { - return (DoubleGui) super.updateItem(col + row * 9, itemTo, title, lore); - } - - @Override - public DoubleGui updateItem(int cell, ItemStack itemTo, String title, String... lore) { - return (DoubleGui) super.updateItem(cell, itemTo, title, lore); - } - - @Override - public DoubleGui updateItem(int row, int col, CompatibleMaterial itemTo, String title, String... lore) { - return (DoubleGui) super.updateItem(col + row * 9, itemTo, title, lore); - } - - @Override - public DoubleGui updateItem(int cell, CompatibleMaterial itemTo, String title, String... lore) { - return (DoubleGui) super.updateItem(cell, itemTo, title, lore); - } - - @Override - public DoubleGui updateItem(int row, int col, ItemStack itemTo, String title, List lore) { - return (DoubleGui) super.updateItem(col + row * 9, itemTo, title, lore); - } - - @Override - public DoubleGui updateItem(int cell, ItemStack itemTo, String title, List lore) { - return (DoubleGui) super.updateItem(cell, itemTo, title, lore); - } - - @Override - public DoubleGui updateItem(int row, int col, CompatibleMaterial itemTo, String title, List lore) { - return (DoubleGui) super.updateItem(col + row * 9, itemTo, title, lore); - } - - @Override - public DoubleGui updateItem(int cell, CompatibleMaterial itemTo, String title, List lore) { - return (DoubleGui) super.updateItem(cell, itemTo, title, lore); - } - - @Override - public DoubleGui setAction(int cell, Clickable action) { - return (DoubleGui) super.setAction(cell, action); - } - - @Override - public DoubleGui setAction(int row, int col, Clickable action) { - return (DoubleGui) super.setAction(row, col, action); - } - - @Override - public DoubleGui setAction(int cell, ClickType type, Clickable action) { - return (DoubleGui) super.setAction(cell, type, action); - } - - @Override - public DoubleGui setAction(int row, int col, ClickType type, Clickable action) { - return (DoubleGui) super.setAction(row, col, type, action); - } - - @Override - public DoubleGui setActionForRange(int cellFirst, int cellLast, Clickable action) { - return (DoubleGui) super.setActionForRange(cellFirst, cellLast, action); - } - - @Override - public DoubleGui setActionForRange(int cellRowFirst, int cellColFirst, int cellRowLast, int cellColLast, Clickable action) { - return (DoubleGui) super.setActionForRange(cellRowFirst, cellColFirst, cellRowLast, cellColLast, action); - } - - @Override - public DoubleGui setActionForRange(int cellFirst, int cellLast, ClickType type, Clickable action) { - return (DoubleGui) super.setActionForRange(cellFirst, cellLast, type, action); - } - - @Override - public DoubleGui setActionForRange(int cellRowFirst, int cellColFirst, int cellRowLast, int cellColLast, ClickType type, Clickable action) { - return (DoubleGui) super.setActionForRange(cellRowFirst, cellColFirst, cellRowLast, cellColLast, type, action); - } - - @Override - public DoubleGui clearActions(int cell) { - return (DoubleGui) super.clearActions(cell); - } - - @Override - public DoubleGui clearActions(int row, int col) { - return (DoubleGui) super.clearActions(row, col); - } - - @Override - public DoubleGui setButton(int cell, ItemStack item, Clickable action) { - return (DoubleGui) super.setButton(cell, item, action); - } - - @Override - public DoubleGui setButton(int row, int col, ItemStack item, Clickable action) { - return (DoubleGui) super.setButton(row, col, item, action); - } - - @Override - public DoubleGui setButton(int cell, ItemStack item, ClickType type, Clickable action) { - return (DoubleGui) super.setButton(cell, item, type, action); - } - - @Override - public DoubleGui setButton(int row, int col, ItemStack item, ClickType type, Clickable action) { - return (DoubleGui) super.setButton(row, col, item, type, action); - } - - @Override - public DoubleGui setOnOpen(Openable action) { - return (DoubleGui) super.setOnOpen(action); - } - - @Override - public DoubleGui setOnClose(Closable action) { - return (DoubleGui) super.setOnClose(action); - } - - @Override - public DoubleGui setOnDrop(Droppable action) { - return (DoubleGui) super.setOnDrop(action); - } - - @Override - public DoubleGui setOnPage(Pagable action) { - return (DoubleGui) super.setOnPage(action); - } - - @Override - public DoubleGui setNextPage(int row, int col, ItemStack item) { - return (DoubleGui) super.setNextPage(row, col, item); - } - - @Override - public DoubleGui setPrevPage(int row, int col, ItemStack item) { - return (DoubleGui) super.setPrevPage(row, col, item); - } -} +package com.songoda.core.gui; + +import com.songoda.core.compatibility.CompatibleMaterial; +import com.songoda.core.gui.events.GuiClickEvent; +import com.songoda.core.gui.events.GuiDropItemEvent; +import com.songoda.core.gui.methods.Clickable; +import com.songoda.core.gui.methods.Closable; +import com.songoda.core.gui.methods.Droppable; +import com.songoda.core.gui.methods.Openable; +import com.songoda.core.gui.methods.Pagable; +import com.songoda.core.utils.ItemUtils; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * TODO: does not restore inventory if server crashes while player inventory is open + * Method to fix: save inv + ender slot to file, store paper in ender inv with name of cache file, check for paper item in slot when loading + * Or just manually manage all inventories in a file and remove when restored + * + * @author jascotty2 + * @since 2019-08-25 + */ +public class DoubleGui extends Gui { + protected boolean startStashed = true; + protected int playerRows = 4; + protected Map stash = new HashMap(); + + public DoubleGui() { + super(GuiType.STANDARD); + allowDropItems = false; + } + + public DoubleGui(GuiType type) { + super(type); + allowDropItems = false; + } + + public DoubleGui(int rows) { + super(rows); + allowDropItems = false; + } + + public DoubleGui(int rows, Gui parent) { + super(rows, parent); + allowDropItems = false; + } + + public DoubleGui(Gui parent) { + super(parent); + allowDropItems = false; + } + + public int getPlayerRows() { + return playerRows; + } + + // 9 -> 0 -> 54 + // 18 -> 9 -> 63 + // 27 -> 18 -> 72 + // 0 -> 27 -> 81 + // offset required to make click translations + int clickOffset(int cell) { + return 54 + (cell < 9 ? cell + 27 : cell - 9); + } + + // offset required to make inventory translations + int invOffset(int cell) { + return 54 + cell; + } + + public void setStartStashed(boolean startStashed) { + this.startStashed = startStashed; + } + + public DoubleGui setPlayerUnlocked(int cell) { + unlockedCells.put(invOffset(cell), true); + return this; + } + + public DoubleGui setPlayerUnlocked(int row, int col) { + unlockedCells.put(invOffset(col + row * 9), true); + return this; + } + + public DoubleGui setPlayerUnlocked(int cell, boolean open) { + unlockedCells.put(invOffset(cell), open); + return this; + } + + public DoubleGui setPlayerUnlocked(int row, int col, boolean open) { + unlockedCells.put(invOffset(col + row * 9), open); + return this; + } + + public DoubleGui setPlayerUnlockedRange(int cellFirst, int cellLast) { + final int last = invOffset(cellLast); + for (int cell = invOffset(cellFirst); cell <= last; ++cell) { + unlockedCells.put(cell, true); + } + return this; + } + + public DoubleGui setPlayerUnlockedRange(int cellFirst, int cellLast, boolean open) { + final int last = invOffset(cellLast); + + for (int cell = invOffset(cellFirst); cell <= last; ++cell) { + unlockedCells.put(cell, open); + } + + return this; + } + + public DoubleGui setPlayerUnlockedRange(int cellRowFirst, int cellColFirst, int cellRowLast, int cellColLast) { + final int last = invOffset(cellColLast + cellRowLast * 9); + + for (int cell = invOffset(cellColFirst + cellRowFirst * 9); cell <= last; ++cell) { + unlockedCells.put(cell, true); + } + + return this; + } + + public DoubleGui setPlayerUnlockedRange(int cellRowFirst, int cellColFirst, int cellRowLast, int cellColLast, boolean open) { + final int last = invOffset(cellColLast + cellRowLast * 9); + + for (int cell = invOffset(cellColFirst + cellRowFirst * 9); cell <= last; ++cell) { + unlockedCells.put(cell, open); + } + + return this; + } + + public DoubleGui setPlayerItem(int cell, ItemStack item) { + cellItems.put(invOffset(cell), item); + + if (open && cell >= 0 && cell < 36) { + cell = cell >= 27 ? cell - 27 : cell + 9; + + for (HumanEntity e : inventory.getViewers()) { + e.getInventory().setItem(cell, item); + } + } + + return this; + } + + public DoubleGui setPlayerItem(int row, int col, ItemStack item) { + int cell = col + row * 9; + cellItems.put(invOffset(cell), item); + + if (open && cell >= 0 && cell < 36) { + cell = cell >= 27 ? cell - 27 : cell + 9; + + for (HumanEntity e : inventory.getViewers()) { + e.getInventory().setItem(cell, item); + } + } + + return this; + } + + public DoubleGui highlightPlayerItem(int cell) { + final int invCell = invOffset(cell); + ItemStack item = cellItems.get(invCell); + + if (item != null) { + setPlayerItem(cell, ItemUtils.addGlow(item)); + } + + return this; + } + + public DoubleGui highlightPlayerItem(int row, int col) { + final int cell = col + row * 9; + final int invCell = invOffset(cell); + + ItemStack item = cellItems.get(invCell); + if (item != null) { + setPlayerItem(cell, ItemUtils.addGlow(item)); + } + + return this; + } + + public DoubleGui setPlayerAction(int cell, Clickable action) { + setConditional(invOffset(cell), null, action); + return this; + } + + public DoubleGui setPlayerAction(int row, int col, Clickable action) { + setConditional(invOffset(col + row * 9), null, action); + return this; + } + + public DoubleGui setPlayerAction(int cell, ClickType type, Clickable action) { + setConditional(invOffset(cell), type, action); + return this; + } + + public DoubleGui setPlayerAction(int row, int col, ClickType type, Clickable action) { + setConditional(invOffset(col + row * 9), type, action); + return this; + } + + public DoubleGui setPlayerActionForRange(int cellFirst, int cellLast, Clickable action) { + for (int cell = cellFirst; cell <= cellLast; ++cell) { + setConditional(invOffset(cell), null, action); + } + + return this; + } + + public DoubleGui setPlayerActionForRange(int cellRowFirst, int cellColFirst, int cellRowLast, int cellColLast, Clickable action) { + final int last = cellColLast + cellRowLast * 9; + + for (int cell = cellColFirst + cellRowFirst * 9; cell <= last; ++cell) { + setConditional(invOffset(cell), null, action); + } + + return this; + } + + public DoubleGui setPlayerActionForRange(int cellFirst, int cellLast, ClickType type, Clickable action) { + for (int cell = cellFirst; cell <= cellLast; ++cell) { + setConditional(invOffset(cell), type, action); + } + + return this; + } + + public DoubleGui setPlayerActionForRange(int cellRowFirst, int cellColFirst, int cellRowLast, int cellColLast, ClickType type, Clickable action) { + final int last = cellColLast + cellRowLast * 9; + + for (int cell = cellColFirst + cellRowFirst * 9; cell <= last; ++cell) { + setConditional(invOffset(cell), type, action); + } + + return this; + } + + public DoubleGui clearPlayerActions(int cell) { + conditionalButtons.remove(cell = invOffset(cell)); + return this; + } + + public DoubleGui clearPlayerActions(int row, int col) { + final int cell = invOffset(col + row * 9); + conditionalButtons.remove(cell); + + return this; + } + + public DoubleGui setPlayerButton(int cell, ItemStack item, Clickable action) { + setPlayerItem(cell, item); + setConditional(invOffset(cell), null, action); + + return this; + } + + public DoubleGui setPlayerButton(int row, int col, ItemStack item, Clickable action) { + final int cell = col + row * 9; + + setPlayerItem(cell, item); + setConditional(invOffset(cell), null, action); + + return this; + } + + public DoubleGui setPlayerButton(int cell, ItemStack item, ClickType type, Clickable action) { + setItem(cell, item); + setConditional(invOffset(cell), type, action); + + return this; + } + + public DoubleGui setPlayerButton(int row, int col, ItemStack item, ClickType type, Clickable action) { + final int cell = col + row * 9; + + setPlayerItem(cell, item); + setConditional(invOffset(cell), type, action); + + return this; + } + + @Override + protected boolean onClickPlayerInventory(GuiManager manager, Player player, Inventory openInv, InventoryClickEvent event) { + final int cell = event.getSlot(), offsetCell = clickOffset(cell); + Map conditionals = conditionalButtons.get(offsetCell); + Clickable button; + + if (conditionals != null + && ((button = conditionals.get(event.getClick())) != null || (button = conditionals.get(null)) != null)) { + button.onClick(new GuiClickEvent(manager, this, player, event, cell, true)); + } else { + // no event for this button + return false; + } + + event.setCancelled(!unlockedCells.entrySet().stream().anyMatch(e -> offsetCell == e.getKey() && e.getValue())); + + return true; + } + + @Override + protected boolean onClickOutside(GuiManager manager, Player player, InventoryClickEvent event) { + if (dropper != null) { + return dropper.onDrop(new GuiDropItemEvent(manager, this, player, event)); + } + + // do not allow by default + return false; + } + + @Override + public void onOpen(GuiManager manager, Player player) { + // replace the player's inventory + if (startStashed) { + stashItems(player); + } + + // other opening functions + super.onOpen(manager, player); + } + + @Override + public void onClose(GuiManager manager, Player player) { + // restore the player's inventory + restoreStash(player); + + // other closing functions + super.onClose(manager, player); + } + + protected void restoreStash(Player player) { + if (stash.containsKey(player)) { + player.getInventory().setContents(stash.remove(player)); + player.updateInventory(); + } + } + + protected void stashItems(Player player) { + if (!stash.containsKey(player)) { + stash.put(player, player.getInventory().getContents().clone()); + player.getInventory().clear(); + } + } + + /* + ********************************************************* + * Other functions from GUI that we don't actually override + ********************************************************* + */ + @Override + public DoubleGui setAcceptsItems(boolean acceptsItems) { + return (DoubleGui) super.setAcceptsItems(acceptsItems); + } + + @Override + public DoubleGui setUnlocked(int cell) { + return (DoubleGui) super.setUnlocked(cell); + } + + @Override + public DoubleGui setUnlocked(int cell, boolean open) { + return (DoubleGui) super.setUnlocked(cell, open); + } + + @Override + public DoubleGui setUnlocked(int row, int col) { + return (DoubleGui) super.setUnlocked(row, col); + } + + @Override + public DoubleGui setUnlocked(int row, int col, boolean open) { + return (DoubleGui) super.setUnlocked(row, col, open); + } + + @Override + public DoubleGui setUnlockedRange(int cellFirst, int cellLast) { + return (DoubleGui) super.setUnlockedRange(cellFirst, cellLast); + } + + @Override + public DoubleGui setUnlockedRange(int cellRowFirst, int cellColFirst, int cellRowLast, int cellColLast) { + return (DoubleGui) super.setUnlockedRange(cellRowFirst, cellColFirst, cellRowLast, cellColLast); + } + + @Override + public DoubleGui setAllowDrops(boolean allow) { + return (DoubleGui) super.setAllowDrops(allow); + } + + @Override + public DoubleGui setAllowClose(boolean allow) { + return (DoubleGui) super.setAllowClose(allow); + } + + @Override + public DoubleGui setTitle(String title) { + return (DoubleGui) super.setTitle(title); + } + + @Override + public DoubleGui setRows(int rows) { + return (DoubleGui) super.setRows(rows); + } + + @Override + public DoubleGui setDefaultItem(ItemStack item) { + return (DoubleGui) super.setDefaultItem(item); + } + + @Override + public DoubleGui setItem(int cell, ItemStack item) { + return (DoubleGui) super.setItem(cell, item); + } + + @Override + public DoubleGui setItem(int row, int col, ItemStack item) { + return (DoubleGui) super.setItem(row, col, item); + } + + @Override + public DoubleGui highlightItem(int cell) { + return (DoubleGui) super.highlightItem(cell); + } + + @Override + public DoubleGui highlightItem(int row, int col) { + return (DoubleGui) super.highlightItem(row, col); + } + + @Override + public DoubleGui updateItem(int cell, String name, String... lore) { + return (DoubleGui) super.updateItem(cell, name, lore); + } + + @Override + public DoubleGui updateItem(int row, int col, String name, List lore) { + return (DoubleGui) super.updateItem(col + row * 9, name, lore); + } + + @Override + public DoubleGui updateItem(int cell, String name, List lore) { + return (DoubleGui) super.updateItem(cell, name, lore); + } + + @Override + public DoubleGui updateItem(int row, int col, ItemStack itemTo, String title, String... lore) { + return (DoubleGui) super.updateItem(col + row * 9, itemTo, title, lore); + } + + @Override + public DoubleGui updateItem(int cell, ItemStack itemTo, String title, String... lore) { + return (DoubleGui) super.updateItem(cell, itemTo, title, lore); + } + + @Override + public DoubleGui updateItem(int row, int col, CompatibleMaterial itemTo, String title, String... lore) { + return (DoubleGui) super.updateItem(col + row * 9, itemTo, title, lore); + } + + @Override + public DoubleGui updateItem(int cell, CompatibleMaterial itemTo, String title, String... lore) { + return (DoubleGui) super.updateItem(cell, itemTo, title, lore); + } + + @Override + public DoubleGui updateItem(int row, int col, ItemStack itemTo, String title, List lore) { + return (DoubleGui) super.updateItem(col + row * 9, itemTo, title, lore); + } + + @Override + public DoubleGui updateItem(int cell, ItemStack itemTo, String title, List lore) { + return (DoubleGui) super.updateItem(cell, itemTo, title, lore); + } + + @Override + public DoubleGui updateItem(int row, int col, CompatibleMaterial itemTo, String title, List lore) { + return (DoubleGui) super.updateItem(col + row * 9, itemTo, title, lore); + } + + @Override + public DoubleGui updateItem(int cell, CompatibleMaterial itemTo, String title, List lore) { + return (DoubleGui) super.updateItem(cell, itemTo, title, lore); + } + + @Override + public DoubleGui setAction(int cell, Clickable action) { + return (DoubleGui) super.setAction(cell, action); + } + + @Override + public DoubleGui setAction(int row, int col, Clickable action) { + return (DoubleGui) super.setAction(row, col, action); + } + + @Override + public DoubleGui setAction(int cell, ClickType type, Clickable action) { + return (DoubleGui) super.setAction(cell, type, action); + } + + @Override + public DoubleGui setAction(int row, int col, ClickType type, Clickable action) { + return (DoubleGui) super.setAction(row, col, type, action); + } + + @Override + public DoubleGui setActionForRange(int cellFirst, int cellLast, Clickable action) { + return (DoubleGui) super.setActionForRange(cellFirst, cellLast, action); + } + + @Override + public DoubleGui setActionForRange(int cellRowFirst, int cellColFirst, int cellRowLast, int cellColLast, Clickable action) { + return (DoubleGui) super.setActionForRange(cellRowFirst, cellColFirst, cellRowLast, cellColLast, action); + } + + @Override + public DoubleGui setActionForRange(int cellFirst, int cellLast, ClickType type, Clickable action) { + return (DoubleGui) super.setActionForRange(cellFirst, cellLast, type, action); + } + + @Override + public DoubleGui setActionForRange(int cellRowFirst, int cellColFirst, int cellRowLast, int cellColLast, ClickType type, Clickable action) { + return (DoubleGui) super.setActionForRange(cellRowFirst, cellColFirst, cellRowLast, cellColLast, type, action); + } + + @Override + public DoubleGui clearActions(int cell) { + return (DoubleGui) super.clearActions(cell); + } + + @Override + public DoubleGui clearActions(int row, int col) { + return (DoubleGui) super.clearActions(row, col); + } + + @Override + public DoubleGui setButton(int cell, ItemStack item, Clickable action) { + return (DoubleGui) super.setButton(cell, item, action); + } + + @Override + public DoubleGui setButton(int row, int col, ItemStack item, Clickable action) { + return (DoubleGui) super.setButton(row, col, item, action); + } + + @Override + public DoubleGui setButton(int cell, ItemStack item, ClickType type, Clickable action) { + return (DoubleGui) super.setButton(cell, item, type, action); + } + + @Override + public DoubleGui setButton(int row, int col, ItemStack item, ClickType type, Clickable action) { + return (DoubleGui) super.setButton(row, col, item, type, action); + } + + @Override + public DoubleGui setOnOpen(Openable action) { + return (DoubleGui) super.setOnOpen(action); + } + + @Override + public DoubleGui setOnClose(Closable action) { + return (DoubleGui) super.setOnClose(action); + } + + @Override + public DoubleGui setOnDrop(Droppable action) { + return (DoubleGui) super.setOnDrop(action); + } + + @Override + public DoubleGui setOnPage(Pagable action) { + return (DoubleGui) super.setOnPage(action); + } + + @Override + public DoubleGui setNextPage(int row, int col, ItemStack item) { + return (DoubleGui) super.setNextPage(row, col, item); + } + + @Override + public DoubleGui setPrevPage(int row, int col, ItemStack item) { + return (DoubleGui) super.setPrevPage(row, col, item); + } +} diff --git a/Core/src/main/java/com/songoda/core/gui/Gui.java b/Core/src/main/java/com/songoda/core/gui/Gui.java index 8f99e8cc..862966d9 100644 --- a/Core/src/main/java/com/songoda/core/gui/Gui.java +++ b/Core/src/main/java/com/songoda/core/gui/Gui.java @@ -38,7 +38,6 @@ import java.util.stream.Collectors; * @since 2019-08-25 */ public class Gui { - protected Inventory inventory; protected String title; protected GuiType inventoryType = GuiType.STANDARD; @@ -72,6 +71,7 @@ public class Gui { public Gui(@NotNull GuiType type) { this.inventoryType = type; + switch (type) { case HOPPER: case DISPENSER: @@ -79,6 +79,7 @@ public class Gui { break; default: this.rows = 3; + break; } } @@ -97,8 +98,11 @@ public class Gui { @NotNull public List getPlayers() { - return inventory == null ? Collections.EMPTY_LIST - : inventory.getViewers().stream() + if (inventory == null) { + return Collections.EMPTY_LIST; + } + + return inventory.getViewers().stream() .filter(e -> e instanceof Player) .map(e -> (Player) e) .collect(Collectors.toList()); @@ -109,6 +113,7 @@ public class Gui { if (inventory != null && inventory.getViewers().isEmpty()) { open = false; } + return open; } @@ -154,6 +159,7 @@ public class Gui { public void exit() { allowClose = true; open = false; + inventory.getViewers().stream() .filter(e -> e instanceof Player) .map(e -> (Player) e) @@ -166,6 +172,7 @@ public class Gui { */ public void close() { allowClose = true; + inventory.getViewers().stream() .filter(e -> e instanceof Player) .map(e -> (Player) e) @@ -188,6 +195,7 @@ public class Gui { public Gui setUnlocked(int row, int col) { final int cell = col + row * inventoryType.columns; unlockedCells.put(cell, true); + return this; } @@ -196,6 +204,7 @@ public class Gui { for (int cell = cellFirst; cell <= cellLast; ++cell) { unlockedCells.put(cell, true); } + return this; } @@ -204,24 +213,29 @@ public class Gui { for (int cell = cellFirst; cell <= cellLast; ++cell) { unlockedCells.put(cell, open); } + return this; } @NotNull public Gui setUnlockedRange(int cellRowFirst, int cellColFirst, int cellRowLast, int cellColLast) { final int last = cellColLast + cellRowLast * inventoryType.columns; + for (int cell = cellColFirst + cellRowFirst * inventoryType.columns; cell <= last; ++cell) { unlockedCells.put(cell, true); } + return this; } @NotNull public Gui setUnlockedRange(int cellRowFirst, int cellColFirst, int cellRowLast, int cellColLast, boolean open) { final int last = cellColLast + cellRowLast * inventoryType.columns; + for (int cell = cellColFirst + cellRowFirst * inventoryType.columns; cell <= last; ++cell) { unlockedCells.put(cell, open); } + return this; } @@ -235,26 +249,35 @@ public class Gui { public Gui setUnlocked(int row, int col, boolean open) { final int cell = col + row * inventoryType.columns; unlockedCells.put(cell, open); + return this; } @NotNull public Gui setTitle(String title) { - if (title == null) title = ""; + if (title == null) { + title = ""; + } + if (!title.equals(this.title)) { this.title = title; + if (inventory != null) { // update active inventory List toUpdate = getPlayers(); boolean isAllowClose = allowClose; exit(); + Inventory oldInv = inventory; createInventory(); inventory.setContents(oldInv.getContents()); + toUpdate.forEach(player -> player.openInventory(inventory)); + allowClose = isAllowClose; } } + return this; } @@ -270,7 +293,9 @@ public class Gui { break; default: this.rows = Math.max(1, Math.min(6, rows)); + break; } + return this; } @@ -302,24 +327,29 @@ public class Gui { if (inventory != null && unlockedCells.getOrDefault(cell, false)) { return inventory.getItem(cell); } + return cellItems.get(cell); } @Nullable public ItemStack getItem(int row, int col) { final int cell = col + row * inventoryType.columns; + if (inventory != null && unlockedCells.getOrDefault(cell, false)) { return inventory.getItem(cell); } + return cellItems.get(cell); } @NotNull public Gui setItem(int cell, @Nullable ItemStack item) { cellItems.put(cell, item); + if (inventory != null && cell >= 0 && cell < inventory.getSize()) { inventory.setItem(cell, item); } + return this; } @@ -332,36 +362,48 @@ public class Gui { @NotNull public Gui mirrorFill(int row, int col, boolean mirrorRow, boolean mirrorCol, ItemStack item) { setItem(row, col, item); - if (mirrorRow) + + if (mirrorRow) { setItem(rows - row - 1, col, item); - if (mirrorCol) + } + + if (mirrorCol) { setItem(row, 8 - col, item); - if (mirrorRow && mirrorCol) + } + + if (mirrorRow && mirrorCol) { setItem(rows - row - 1, 8 - col, item); + } + return this; } @NotNull public Gui highlightItem(int cell) { ItemStack item = cellItems.get(cell); + if (item != null && item.getType() != Material.AIR) { setItem(cell, ItemUtils.addGlow(item)); } + return this; } @NotNull public Gui highlightItem(int row, int col) { final int cell = col + row * inventoryType.columns; + return highlightItem(cell); } @NotNull public Gui removeHighlight(int cell) { ItemStack item = cellItems.get(cell); + if (item != null && item.getType() != Material.AIR) { setItem(cell, ItemUtils.removeGlow(item)); } + return this; } @@ -379,9 +421,11 @@ public class Gui { @NotNull public Gui updateItemLore(int cell, @NotNull String... lore) { ItemStack item = cellItems.get(cell); + if (item != null && item.getType() != Material.AIR) { setItem(cell, GuiUtils.updateItemLore(item, lore)); } + return this; } @@ -393,9 +437,11 @@ public class Gui { @NotNull public Gui updateItemLore(int cell, @Nullable List lore) { ItemStack item = cellItems.get(cell); + if (item != null && item.getType() != Material.AIR) { setItem(cell, GuiUtils.updateItemLore(item, lore)); } + return this; } @@ -407,9 +453,11 @@ public class Gui { @NotNull public Gui updateItemName(int cell, @Nullable String name) { ItemStack item = cellItems.get(cell); + if (item != null && item.getType() != Material.AIR) { setItem(cell, GuiUtils.updateItemName(item, name)); } + return this; } @@ -431,9 +479,11 @@ public class Gui { @NotNull public Gui updateItem(int cell, @NotNull String name, @Nullable List lore) { ItemStack item = cellItems.get(cell); + if (item != null && item.getType() != Material.AIR) { setItem(cell, GuiUtils.updateItem(item, name, lore)); } + return this; } @@ -445,9 +495,11 @@ public class Gui { @NotNull public Gui updateItem(int cell, @NotNull ItemStack itemTo, @Nullable String title, @NotNull String... lore) { ItemStack item = cellItems.get(cell); + if (item != null && item.getType() != Material.AIR) { setItem(cell, GuiUtils.updateItem(item, itemTo, title, lore)); } + return this; } @@ -459,9 +511,11 @@ public class Gui { @NotNull public Gui updateItem(int cell, @NotNull CompatibleMaterial itemTo, @Nullable String title, @Nullable String... lore) { ItemStack item = cellItems.get(cell); + if (item != null && item.getType() != Material.AIR) { setItem(cell, GuiUtils.updateItem(item, itemTo, title, lore)); } + return this; } @@ -473,9 +527,11 @@ public class Gui { @NotNull public Gui updateItem(int cell, @NotNull ItemStack itemTo, @Nullable String title, @Nullable List lore) { ItemStack item = cellItems.get(cell); + if (item != null && item.getType() != Material.AIR) { setItem(cell, GuiUtils.updateItem(item, itemTo, title, lore)); } + return this; } @@ -487,9 +543,11 @@ public class Gui { @NotNull public Gui updateItem(int cell, @NotNull CompatibleMaterial itemTo, @Nullable String title, @Nullable List lore) { ItemStack item = cellItems.get(cell); + if (item != null && item.getType() != Material.AIR) { setItem(cell, GuiUtils.updateItem(item, itemTo, title, lore)); } + return this; } @@ -522,15 +580,18 @@ public class Gui { for (int cell = cellFirst; cell <= cellLast; ++cell) { setConditional(cell, null, action); } + return this; } @NotNull public Gui setActionForRange(int cellRowFirst, int cellColFirst, int cellRowLast, int cellColLast, @Nullable Clickable action) { final int last = cellColLast + cellRowLast * inventoryType.columns; + for (int cell = cellColFirst + cellRowFirst * inventoryType.columns; cell <= last; ++cell) { setConditional(cell, null, action); } + return this; } @@ -539,15 +600,18 @@ public class Gui { for (int cell = cellFirst; cell <= cellLast; ++cell) { setConditional(cell, type, action); } + return this; } @NotNull public Gui setActionForRange(int cellRowFirst, int cellColFirst, int cellRowLast, int cellColLast, @Nullable ClickType type, @Nullable Clickable action) { final int last = cellColLast + cellRowLast * inventoryType.columns; + for (int cell = cellColFirst + cellRowFirst * inventoryType.columns; cell <= last; ++cell) { setConditional(cell, type, action); } + return this; } @@ -566,14 +630,17 @@ public class Gui { public Gui setButton(int cell, ItemStack item, @Nullable Clickable action) { setItem(cell, item); setConditional(cell, null, action); + return this; } @NotNull public Gui setButton(int row, int col, @Nullable ItemStack item, @Nullable Clickable action) { final int cell = col + row * inventoryType.columns; + setItem(cell, item); setConditional(cell, null, action); + return this; } @@ -581,14 +648,17 @@ public class Gui { public Gui setButton(int cell, @Nullable ItemStack item, @Nullable ClickType type, @Nullable Clickable action) { setItem(cell, item); setConditional(cell, type, action); + return this; } @NotNull public Gui setButton(int row, int col, @Nullable ItemStack item, @Nullable ClickType type, @Nullable Clickable action) { final int cell = col + row * inventoryType.columns; + setItem(cell, item); setConditional(cell, type, action); + return this; } @@ -632,8 +702,9 @@ public class Gui { } public void reset() { - if (inventory != null) + if (inventory != null) { inventory.clear(); + } setActionForRange(0, 53, null); cellItems.clear(); @@ -645,9 +716,11 @@ public class Gui { nextPageItem = cellItems.get(cell); nextPageIndex = cell; nextPage = item; + if (page < pages) { setButton(nextPageIndex, nextPage, ClickType.LEFT, (event) -> this.nextPage()); } + return this; } @@ -661,9 +734,11 @@ public class Gui { prevPageItem = cellItems.get(cell); prevPageIndex = cell; prevPage = item; + if (page > 1) { setButton(prevPageIndex, prevPage, ClickType.LEFT, (event) -> this.prevPage()); } + return this; } @@ -674,6 +749,7 @@ public class Gui { public void setPages(int pages) { this.pages = Math.max(1, pages); + if (page > pages) { setPage(pages); } @@ -682,8 +758,10 @@ public class Gui { public void setPage(int page) { int lastPage = this.page; this.page = Math.max(1, Math.min(pages, page)); + if (pager != null && this.page != lastPage) { pager.onPageChange(new GuiPageEvent(this, guiManager, lastPage, page)); + // page markers updatePageNavigation(); } @@ -692,8 +770,10 @@ public class Gui { public void changePage(int direction) { int lastPage = page; this.page = Math.max(1, Math.min(pages, page + direction)); + if (pager != null && this.page != lastPage) { pager.onPageChange(new GuiPageEvent(this, guiManager, lastPage, page)); + // page markers updatePageNavigation(); } @@ -703,6 +783,7 @@ public class Gui { if (page < pages) { int lastPage = page; ++page; + // page switch events if (pager != null) { pager.onPageChange(new GuiPageEvent(this, guiManager, lastPage, page)); @@ -721,6 +802,7 @@ public class Gui { if (page > 1) { int lastPage = page; --page; + if (pager != null) { pager.onPageChange(new GuiPageEvent(this, guiManager, lastPage, page)); @@ -743,6 +825,7 @@ public class Gui { this.clearActions(prevPageIndex); } } + if (nextPage != null) { if (pages > 1 && page != pages) { this.setButton(nextPageIndex, nextPage, ClickType.LEFT, (event) -> this.nextPage()); @@ -764,6 +847,7 @@ public class Gui { final int cells = rows * inventoryType.columns; createInventory(); + for (int i = 0; i < cells; ++i) { final ItemStack item = cellItems.get(i); inventory.setItem(i, item != null ? item : (unlockedCells.getOrDefault(i, false) ? AIR : blankItem)); @@ -784,6 +868,7 @@ public class Gui { default: inventory = new GuiHolder(guiManager, this).newInventory(rows * 9, title == null ? "" : trimTitle(title)); + break; } } @@ -793,8 +878,9 @@ public class Gui { } public void update() { - if (inventory == null) + if (inventory == null) { return; + } final int cells = rows * inventoryType.columns; for (int i = 0; i < cells; ++i) { @@ -806,9 +892,12 @@ public class Gui { protected static String trimTitle(String title) { if (title == null) { return ""; - } else if (ServerVersion.isServerVersionAtOrBelow(ServerVersion.V1_8) && title.length() > 32) { + } + + if (ServerVersion.isServerVersionAtOrBelow(ServerVersion.V1_8) && title.length() > 32) { return title.charAt(30) == '\u00A7' ? title.substring(0, 30) : title.substring(0, 31); } + return title; } @@ -819,6 +908,7 @@ public class Gui { protected boolean onClick(@NotNull GuiManager manager, @NotNull Player player, @NotNull Inventory inventory, @NotNull InventoryClickEvent event) { final int cell = event.getSlot(); Map conditionals = conditionalButtons.get(cell); + Clickable button; if (conditionals != null && ((button = conditionals.get(event.getClick())) != null || (button = conditionals.get(null)) != null)) { @@ -829,12 +919,15 @@ public class Gui { // this is a default action, not a triggered action defaultClicker.onClick(new GuiClickEvent(manager, this, player, event, cell, true)); } + if (privateDefaultClicker != null) { // this is a private default action, not a triggered action privateDefaultClicker.onClick(new GuiClickEvent(manager, this, player, event, cell, true)); } + return false; } + return true; } @@ -846,6 +939,7 @@ public class Gui { public void onOpen(@NotNull GuiManager manager, @NotNull Player player) { open = true; guiManager = manager; + if (opener != null) { opener.onOpen(new GuiOpenEvent(manager, this, player)); } @@ -856,10 +950,13 @@ public class Gui { manager.showGUI(player, this); return; } + boolean showParent = open && parent != null; + if (closer != null) { closer.onClose(new GuiCloseEvent(manager, this, player)); } + if (showParent) { manager.showGUI(player, parent); } diff --git a/Core/src/main/java/com/songoda/core/gui/GuiHolder.java b/Core/src/main/java/com/songoda/core/gui/GuiHolder.java index b2acd014..8cf884fc 100644 --- a/Core/src/main/java/com/songoda/core/gui/GuiHolder.java +++ b/Core/src/main/java/com/songoda/core/gui/GuiHolder.java @@ -1,40 +1,39 @@ -package com.songoda.core.gui; - -import org.bukkit.Bukkit; -import org.bukkit.event.inventory.InventoryType; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.InventoryHolder; - -/** - * Internal class for marking an inventory as a GUI inventory - * - * @author jascotty2 - * @since 2019-08-25 - */ -class GuiHolder implements InventoryHolder { - - final Gui gui; - final GuiManager manager; - - public GuiHolder(GuiManager manager, Gui gui) { - this.gui = gui; - this.manager = manager; - } - - @Override - public Inventory getInventory() { - return gui.inventory; - } - - public Gui getGUI() { - return gui; - } - - public Inventory newInventory(int size, String title) { - return Bukkit.createInventory(this, size, title); - } - - public Inventory newInventory(InventoryType type, String title) { - return Bukkit.createInventory(this, type, title); - } -} +package com.songoda.core.gui; + +import org.bukkit.Bukkit; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; + +/** + * Internal class for marking an inventory as a GUI inventory + * + * @author jascotty2 + * @since 2019-08-25 + */ +class GuiHolder implements InventoryHolder { + final Gui gui; + final GuiManager manager; + + public GuiHolder(GuiManager manager, Gui gui) { + this.gui = gui; + this.manager = manager; + } + + @Override + public Inventory getInventory() { + return gui.inventory; + } + + public Gui getGUI() { + return gui; + } + + public Inventory newInventory(int size, String title) { + return Bukkit.createInventory(this, size, title); + } + + public Inventory newInventory(InventoryType type, String title) { + return Bukkit.createInventory(this, type, title); + } +} diff --git a/Core/src/main/java/com/songoda/core/gui/GuiManager.java b/Core/src/main/java/com/songoda/core/gui/GuiManager.java index 489ceeb1..151a1fac 100644 --- a/Core/src/main/java/com/songoda/core/gui/GuiManager.java +++ b/Core/src/main/java/com/songoda/core/gui/GuiManager.java @@ -1,275 +1,303 @@ -package com.songoda.core.gui; - -import com.songoda.core.compatibility.ClientVersion; -import com.songoda.core.compatibility.CompatibleMaterial; -import com.songoda.core.compatibility.ServerVersion; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.event.Event.Result; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.inventory.ClickType; -import org.bukkit.event.inventory.InventoryAction; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.event.inventory.InventoryCloseEvent; -import org.bukkit.event.inventory.InventoryDragEvent; -import org.bukkit.event.inventory.InventoryType.SlotType; -import org.bukkit.event.server.PluginDisableEvent; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.plugin.Plugin; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; -import java.util.stream.Collectors; - -/** - * Manages events for GUI screens - * - * @author jascotty2 - * @since 2019-08-25 - */ -public class GuiManager { - - final Plugin plugin; - final UUID uuid = UUID.randomUUID(); // manager tracking to fix weird bugs from lazy programming - final GuiListener listener = new GuiListener(this); - final Map openInventories = new HashMap(); - private final Object lock = new Object(); - private boolean initialized = false; - private boolean shutdown = false; - - public GuiManager(Plugin plugin) { - this.plugin = plugin; - } - - public Plugin getPlugin() { - return plugin; - } - - /** - * Initialize the GUI handlers - */ - public void init() { - Bukkit.getPluginManager().registerEvents(listener, plugin); - initialized = true; - shutdown = false; - } - - /** - * Check to see if this manager cannot open any more GUI screens - * - * @return true if the owning plugin has shutdown - */ - public boolean isClosed() { - return shutdown; - } - - /** - * Create and display a GUI interface for a player - * - * @param player player to open the interface for - * @param gui GUI to use - */ - public void showGUI(Player player, Gui gui) { - if (shutdown) { - if (plugin.isEnabled()) { - // recover if reloaded without calling init manually - init(); - } else { - return; - } - } else if (!initialized) { - init(); - } - if (gui instanceof AnvilGui) { - // bukkit throws a fit now if you try to set anvil stuff asynchronously - Gui openInv = openInventories.get(player); - if (openInv != null) { - openInv.open = false; - } - gui.getOrCreateInventory(this); - ((AnvilGui) gui).open(); - gui.onOpen(this, player); - synchronized (lock) { - openInventories.put(player, gui); - } - } else { - Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { - Gui openInv = openInventories.get(player); - if (openInv != null) { - openInv.open = false; - } - Inventory inv = gui.getOrCreateInventory(this); - Bukkit.getScheduler().runTask(plugin, () -> { - player.openInventory(inv); - gui.onOpen(this, player); - synchronized (lock) { - openInventories.put(player, gui); - } - }); - }); - } - } - - public void showPopup(Player player, String message) { - showPopup(player, message, CompatibleMaterial.NETHER_STAR, BackgroundType.ADVENTURE); - } - - public void showPopup(Player player, String message, CompatibleMaterial icon) { - showPopup(player, message, icon, BackgroundType.ADVENTURE); - } - - public void showPopup(Player player, String message, CompatibleMaterial icon, BackgroundType background) { - if (ClientVersion.getClientVersion(player).isAtLeast(ServerVersion.V1_12)) { - PopupMessage popup = new PopupMessage(plugin, icon, message, background); - popup.add(); - popup.grant(player); - Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> { - popup.revoke(player); - popup.remove(); - }, 70); - } else if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_11)) { - player.sendTitle("", message, 10, 70, 10); - } else { - player.sendTitle("", message); - } - } - - /** - * Close all active GUIs - */ - public void closeAll() { - synchronized (lock) { - openInventories.entrySet().stream() - .filter(e -> e.getKey().getOpenInventory().getTopInventory().getHolder() instanceof GuiHolder) - .collect(Collectors.toList()) // to prevent concurrency exceptions - .forEach(e -> e.getKey().closeInventory()); - openInventories.clear(); - } - } - - protected static class GuiListener implements Listener { - - final GuiManager manager; - - public GuiListener(GuiManager manager) { - this.manager = manager; - } - - @EventHandler(priority = EventPriority.LOW) - void onDragGUI(InventoryDragEvent event) { - if (!(event.getWhoClicked() instanceof Player)) { - return; - } - - Inventory openInv = event.getInventory(); - Gui gui; - if (openInv.getHolder() != null && openInv.getHolder() instanceof GuiHolder - && ((GuiHolder) openInv.getHolder()).manager.uuid.equals(manager.uuid)) { - gui = ((GuiHolder) openInv.getHolder()).getGUI(); - - if (event.getRawSlots().stream().filter(slot -> gui.inventory.getSize() > slot).anyMatch(slot -> !gui.unlockedCells.getOrDefault(slot, false))) { - event.setCancelled(true); - event.setResult(Result.DENY); - } - } - } - - @EventHandler(priority = EventPriority.LOW) - void onClickGUI(InventoryClickEvent event) { - if (!(event.getWhoClicked() instanceof Player)) { - return; - } - - Inventory openInv = event.getInventory(); - final Player player = (Player) event.getWhoClicked(); - - Gui gui; - if (openInv.getHolder() != null && openInv.getHolder() instanceof GuiHolder - && ((GuiHolder) openInv.getHolder()).manager.uuid.equals(manager.uuid)) { - gui = ((GuiHolder) openInv.getHolder()).getGUI(); - - if (event.getClick() == ClickType.DOUBLE_CLICK) { - // always cancel this event if there are matching gui elements, since it tends to do bad things - ItemStack clicked = event.getCursor(); - if (clicked != null && clicked.getType() != Material.AIR) { - int cell = 0; - for (ItemStack it : gui.inventory.getContents()) { - if (!gui.unlockedCells.getOrDefault(cell++, false) && clicked.isSimilar(it)) { - event.setCancelled(true); - if (gui instanceof AnvilGui) { - ((AnvilGui) gui).anvil.update(); - } - break; - } - } - } - } - - if (event.getSlotType() == SlotType.OUTSIDE) { - if (!gui.onClickOutside(manager, player, event)) { - event.setCancelled(true); - } - } // did we click the gui or in the user's inventory? - else if (event.getRawSlot() < gui.inventory.getSize()) {// or could use event.getClickedInventory() == gui.inventory - // allow event if this is not a GUI element - event.setCancelled(gui.unlockedCells.entrySet().stream().noneMatch(e -> event.getSlot() == e.getKey() && e.getValue())); - // process button press - if (gui.onClick(manager, player, openInv, event)) { - player.playSound(player.getLocation(), gui.getDefaultSound().getSound(), 1F, 1F); - } - } else { - // Player clicked in the bottom inventory while GUI is open - if (gui.onClickPlayerInventory(manager, player, openInv, event)) { - player.playSound(player.getLocation(), gui.getDefaultSound().getSound(), 1F, 1F); - } else if (!gui.acceptsItems || event.getAction() == InventoryAction.MOVE_TO_OTHER_INVENTORY) { - event.setCancelled(true); - if (gui instanceof AnvilGui) { - ((AnvilGui) gui).anvil.update(); - } - } - } - } - } - - @EventHandler(priority = EventPriority.LOW) - void onCloseGUI(InventoryCloseEvent event) { - Inventory openInv = event.getInventory(); - if (openInv.getHolder() != null && openInv.getHolder() instanceof GuiHolder - && ((GuiHolder) openInv.getHolder()).manager.uuid.equals(manager.uuid)) { - Gui gui = ((GuiHolder) openInv.getHolder()).getGUI(); - if (gui instanceof AnvilGui) { - gui.inventory.clear(); - gui.inventory = null; - } - if (!gui.open) { - return; - } - final Player player = (Player) event.getPlayer(); - if (!gui.allowDropItems) { - player.setItemOnCursor(null); - } - if (manager.shutdown) { - gui.onClose(manager, player); - } else { - Bukkit.getScheduler().runTaskLater(manager.plugin, () -> gui.onClose(manager, player), 1); - } - manager.openInventories.remove(player); - } - } - - @EventHandler - void onDisable(PluginDisableEvent event) { - if (event.getPlugin() == manager.plugin) { - // uh-oh! Abandon ship!! - manager.shutdown = true; - manager.closeAll(); - manager.initialized = false; - } - } - } -} +package com.songoda.core.gui; + +import com.songoda.core.compatibility.ClientVersion; +import com.songoda.core.compatibility.CompatibleMaterial; +import com.songoda.core.compatibility.ServerVersion; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.Event.Result; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.event.inventory.InventoryAction; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.inventory.InventoryDragEvent; +import org.bukkit.event.inventory.InventoryType.SlotType; +import org.bukkit.event.server.PluginDisableEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.Plugin; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; + +/** + * Manages events for GUI screens + * + * @author jascotty2 + * @since 2019-08-25 + */ +public class GuiManager { + final Plugin plugin; + final UUID uuid = UUID.randomUUID(); // manager tracking to fix weird bugs from lazy programming + final GuiListener listener = new GuiListener(this); + final Map openInventories = new HashMap(); + private final Object lock = new Object(); + private boolean initialized = false; + private boolean shutdown = false; + + public GuiManager(Plugin plugin) { + this.plugin = plugin; + } + + public Plugin getPlugin() { + return plugin; + } + + /** + * Initialize the GUI handlers + */ + public void init() { + Bukkit.getPluginManager().registerEvents(listener, plugin); + + initialized = true; + shutdown = false; + } + + /** + * Check to see if this manager cannot open any more GUI screens + * + * @return true if the owning plugin has shutdown + */ + public boolean isClosed() { + return shutdown; + } + + /** + * Create and display a GUI interface for a player + * + * @param player player to open the interface for + * @param gui GUI to use + */ + public void showGUI(Player player, Gui gui) { + if (shutdown) { + if (!plugin.isEnabled()) { + return; + } + + // recover if reloaded without calling init manually + init(); + } else if (!initialized) { + init(); + } + + if (gui instanceof AnvilGui) { + // bukkit throws a fit now if you try to set anvil stuff asynchronously + Gui openInv = openInventories.get(player); + + if (openInv != null) { + openInv.open = false; + } + + gui.getOrCreateInventory(this); + ((AnvilGui) gui).open(); + gui.onOpen(this, player); + + synchronized (lock) { + openInventories.put(player, gui); + } + + return; + } + + Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + Gui openInv = openInventories.get(player); + + if (openInv != null) { + openInv.open = false; + } + + Inventory inv = gui.getOrCreateInventory(this); + + Bukkit.getScheduler().runTask(plugin, () -> { + player.openInventory(inv); + gui.onOpen(this, player); + + synchronized (lock) { + openInventories.put(player, gui); + } + }); + }); + } + + public void showPopup(Player player, String message) { + showPopup(player, message, CompatibleMaterial.NETHER_STAR, BackgroundType.ADVENTURE); + } + + public void showPopup(Player player, String message, CompatibleMaterial icon) { + showPopup(player, message, icon, BackgroundType.ADVENTURE); + } + + public void showPopup(Player player, String message, CompatibleMaterial icon, BackgroundType background) { + if (ClientVersion.getClientVersion(player).isAtLeast(ServerVersion.V1_12)) { + PopupMessage popup = new PopupMessage(plugin, icon, message, background); + popup.add(); + popup.grant(player); + + Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> { + popup.revoke(player); + popup.remove(); + }, 70); + + return; + } + + if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_11)) { + player.sendTitle("", message, 10, 70, 10); + return; + } + + player.sendTitle("", message); + } + + /** + * Close all active GUIs + */ + public void closeAll() { + synchronized (lock) { + openInventories.entrySet().stream() + .filter(e -> e.getKey().getOpenInventory().getTopInventory().getHolder() instanceof GuiHolder) + .collect(Collectors.toList()) // to prevent concurrency exceptions + .forEach(e -> e.getKey().closeInventory()); + + openInventories.clear(); + } + } + + protected static class GuiListener implements Listener { + final GuiManager manager; + + public GuiListener(GuiManager manager) { + this.manager = manager; + } + + @EventHandler(priority = EventPriority.LOW) + void onDragGUI(InventoryDragEvent event) { + if (!(event.getWhoClicked() instanceof Player)) { + return; + } + + Inventory openInv = event.getInventory(); + Gui gui; + if (openInv.getHolder() != null && openInv.getHolder() instanceof GuiHolder + && ((GuiHolder) openInv.getHolder()).manager.uuid.equals(manager.uuid)) { + gui = ((GuiHolder) openInv.getHolder()).getGUI(); + + if (event.getRawSlots().stream() + .filter(slot -> gui.inventory.getSize() > slot) + .anyMatch(slot -> !gui.unlockedCells.getOrDefault(slot, false))) { + event.setCancelled(true); + event.setResult(Result.DENY); + } + } + } + + @EventHandler(priority = EventPriority.LOW) + void onClickGUI(InventoryClickEvent event) { + if (!(event.getWhoClicked() instanceof Player)) { + return; + } + + Inventory openInv = event.getInventory(); + final Player player = (Player) event.getWhoClicked(); + + Gui gui; + if (openInv.getHolder() != null && openInv.getHolder() instanceof GuiHolder && + ((GuiHolder) openInv.getHolder()).manager.uuid.equals(manager.uuid)) { + gui = ((GuiHolder) openInv.getHolder()).getGUI(); + + if (event.getClick() == ClickType.DOUBLE_CLICK) { + // always cancel this event if there are matching gui elements, since it tends to do bad things + ItemStack clicked = event.getCursor(); + if (clicked != null && clicked.getType() != Material.AIR) { + int cell = 0; + for (ItemStack it : gui.inventory.getContents()) { + if (!gui.unlockedCells.getOrDefault(cell++, false) && clicked.isSimilar(it)) { + event.setCancelled(true); + + if (gui instanceof AnvilGui) { + ((AnvilGui) gui).anvil.update(); + } + + break; + } + } + } + } + + if (event.getSlotType() == SlotType.OUTSIDE) { + if (!gui.onClickOutside(manager, player, event)) { + event.setCancelled(true); + } + } // did we click the gui or in the user's inventory? + else if (event.getRawSlot() < gui.inventory.getSize()) { // or could use event.getClickedInventory() == gui.inventory + // allow event if this is not a GUI element + event.setCancelled(gui.unlockedCells.entrySet().stream().noneMatch(e -> event.getSlot() == e.getKey() && e.getValue())); + + // process button press + if (gui.onClick(manager, player, openInv, event)) { + player.playSound(player.getLocation(), gui.getDefaultSound().getSound(), 1F, 1F); + } + } else { + // Player clicked in the bottom inventory while GUI is open + if (gui.onClickPlayerInventory(manager, player, openInv, event)) { + player.playSound(player.getLocation(), gui.getDefaultSound().getSound(), 1F, 1F); + } else if (!gui.acceptsItems || event.getAction() == InventoryAction.MOVE_TO_OTHER_INVENTORY) { + event.setCancelled(true); + + if (gui instanceof AnvilGui) { + ((AnvilGui) gui).anvil.update(); + } + } + } + } + } + + @EventHandler(priority = EventPriority.LOW) + void onCloseGUI(InventoryCloseEvent event) { + Inventory openInv = event.getInventory(); + + if (openInv.getHolder() != null && openInv.getHolder() instanceof GuiHolder && + ((GuiHolder) openInv.getHolder()).manager.uuid.equals(manager.uuid)) { + Gui gui = ((GuiHolder) openInv.getHolder()).getGUI(); + + if (gui instanceof AnvilGui) { + gui.inventory.clear(); + gui.inventory = null; + } + + if (!gui.open) { + return; + } + + final Player player = (Player) event.getPlayer(); + if (!gui.allowDropItems) { + player.setItemOnCursor(null); + } + + if (manager.shutdown) { + gui.onClose(manager, player); + } else { + Bukkit.getScheduler().runTaskLater(manager.plugin, () -> gui.onClose(manager, player), 1); + } + + manager.openInventories.remove(player); + } + } + + @EventHandler + void onDisable(PluginDisableEvent event) { + if (event.getPlugin() == manager.plugin) { + // uh-oh! Abandon ship!! + manager.shutdown = true; + manager.closeAll(); + manager.initialized = false; + } + } + } +} diff --git a/Core/src/main/java/com/songoda/core/gui/GuiType.java b/Core/src/main/java/com/songoda/core/gui/GuiType.java index af5e3931..3c4bd634 100644 --- a/Core/src/main/java/com/songoda/core/gui/GuiType.java +++ b/Core/src/main/java/com/songoda/core/gui/GuiType.java @@ -3,7 +3,6 @@ package com.songoda.core.gui; import org.bukkit.event.inventory.InventoryType; public enum GuiType { - STANDARD(InventoryType.CHEST, 6, 9), DISPENSER(InventoryType.DISPENSER, 9, 3), HOPPER(InventoryType.HOPPER, 5, 1); diff --git a/Core/src/main/java/com/songoda/core/gui/GuiUtils.java b/Core/src/main/java/com/songoda/core/gui/GuiUtils.java index 65c52a90..c812b822 100644 --- a/Core/src/main/java/com/songoda/core/gui/GuiUtils.java +++ b/Core/src/main/java/com/songoda/core/gui/GuiUtils.java @@ -15,27 +15,32 @@ import java.util.List; * @since 2019-08-25 */ public class GuiUtils { - public static ItemStack getBorderGlassItem() { ItemStack glass = CompatibleMaterial.LIGHT_BLUE_STAINED_GLASS_PANE.getItem(); ItemMeta glassmeta = glass.getItemMeta(); + glassmeta.setDisplayName(ChatColor.BLACK.toString()); glass.setItemMeta(glassmeta); + return glass; } public static ItemStack getBorderItem(ItemStack item) { ItemMeta glassmeta = item.getItemMeta(); + glassmeta.setDisplayName(ChatColor.BLACK.toString()); item.setItemMeta(glassmeta); + return item; } public static ItemStack getBorderItem(CompatibleMaterial mat) { ItemStack item = mat.getItem(); ItemMeta glassmeta = item.getItemMeta(); + glassmeta.setDisplayName(ChatColor.BLACK.toString()); item.setItemMeta(glassmeta); + return item; } @@ -53,197 +58,247 @@ public class GuiUtils { public static List getSafeLore(List lines) { // fix newlines ArrayList newLore = new ArrayList(); + for (String l : lines) { for (String l2 : l.split("\n")) { if (l2.length() < 54) { newLore.add(l2); - } else { - // try to shorten the string - String shorterString = l2; - ChatColor lastColor = null; // todo? probably should also track formatting codes.. - int line = 0; - while (shorterString.length() > 50) { - int breakingSpace = -1; - for (int i = 0; i < 50; ++i) { - if (shorterString.charAt(i) == ChatColor.COLOR_CHAR) { - lastColor = ChatColor.getByChar(shorterString.charAt(++i)); - } else if (shorterString.charAt(i) == ' ' || shorterString.charAt(i) == '-') { - breakingSpace = i; - } + continue; + } + + // try to shorten the string + String shorterString = l2; + ChatColor lastColor = null; // todo? probably should also track formatting codes.. + int line = 0; + while (shorterString.length() > 50) { + int breakingSpace = -1; + + for (int i = 0; i < 50; ++i) { + if (shorterString.charAt(i) == ChatColor.COLOR_CHAR) { + lastColor = ChatColor.getByChar(shorterString.charAt(++i)); + } else if (shorterString.charAt(i) == ' ' || shorterString.charAt(i) == '-') { + breakingSpace = i; } - if (breakingSpace == -1) { - breakingSpace = Math.max(50, shorterString.length()); - newLore.add((line != 0 && lastColor != null ? lastColor.toString() : "") + shorterString.substring(0, breakingSpace) + "-"); - shorterString = breakingSpace == shorterString.length() ? "" : shorterString.substring(breakingSpace + 1); - } else { - newLore.add((line != 0 && lastColor != null ? lastColor.toString() : "") + shorterString.substring(0, breakingSpace)); - shorterString = breakingSpace == shorterString.length() ? "" : shorterString.substring(breakingSpace + 1); - } - ++line; } - if (!shorterString.isEmpty()) { - newLore.add((line != 0 && lastColor != null ? lastColor.toString() : "") + " " + shorterString); + + if (breakingSpace == -1) { + breakingSpace = Math.max(50, shorterString.length()); + newLore.add((line != 0 && lastColor != null ? lastColor.toString() : "") + shorterString.substring(0, breakingSpace) + "-"); + shorterString = breakingSpace == shorterString.length() ? "" : shorterString.substring(breakingSpace + 1); + } else { + newLore.add((line != 0 && lastColor != null ? lastColor.toString() : "") + shorterString.substring(0, breakingSpace)); + shorterString = breakingSpace == shorterString.length() ? "" : shorterString.substring(breakingSpace + 1); } + + ++line; + } + + if (!shorterString.isEmpty()) { + newLore.add((line != 0 && lastColor != null ? lastColor.toString() : "") + " " + shorterString); } } } + return newLore; } public static ItemStack createButtonItem(CompatibleMaterial mat, String title, String... lore) { ItemStack item = mat.getItem(); ItemMeta meta = item.getItemMeta(); + if (meta != null) { meta.setDisplayName(title); + if (lore != null) { meta.setLore(getSafeLore(lore)); } else { meta.setLore(Collections.EMPTY_LIST); } + item.setItemMeta(meta); } + return item; } public static ItemStack createButtonItem(CompatibleMaterial mat, int amount, String title, String... lore) { ItemStack item = mat.getItem(); item.setAmount(amount); + ItemMeta meta = item.getItemMeta(); + if (meta != null) { meta.setDisplayName(title); + if (lore != null) { meta.setLore(getSafeLore(lore)); } else { meta.setLore(Collections.EMPTY_LIST); } + item.setItemMeta(meta); } + return item; } public static ItemStack createButtonItem(ItemStack from, String title, String... lore) { ItemStack item = from.clone(); ItemMeta meta = item.getItemMeta(); + if (meta != null) { meta.setDisplayName(title); + if (lore != null) { meta.setLore(getSafeLore(lore)); } else { meta.setLore(Collections.EMPTY_LIST); } + item.setItemMeta(meta); } + return item; } public static ItemStack createButtonItem(CompatibleMaterial mat, String title, List lore) { ItemStack item = mat.getItem(); ItemMeta meta = item.getItemMeta(); + if (meta != null) { meta.setDisplayName(title); + if (lore != null) { meta.setLore(getSafeLore(lore)); } else { meta.setLore(Collections.EMPTY_LIST); } + item.setItemMeta(meta); } + return item; } public static ItemStack createButtonItem(CompatibleMaterial mat, int amount, String title, List lore) { ItemStack item = mat.getItem(); item.setAmount(amount); + ItemMeta meta = item.getItemMeta(); + if (meta != null) { meta.setDisplayName(title); + if (lore != null) { meta.setLore(getSafeLore(lore)); } else { meta.setLore(Collections.EMPTY_LIST); } + item.setItemMeta(meta); } + return item; } public static ItemStack createButtonItem(ItemStack from, String title, List lore) { ItemStack item = from.clone(); ItemMeta meta = item.getItemMeta(); + if (meta != null) { meta.setDisplayName(title); + if (lore != null) { meta.setLore(getSafeLore(lore)); } else { meta.setLore(Collections.EMPTY_LIST); } + item.setItemMeta(meta); } + return item; } public static ItemStack createButtonItem(CompatibleMaterial mat, String[] lore) { ItemStack item = mat.getItem(); ItemMeta meta = item.getItemMeta(); + if (meta != null) { if (lore != null && lore.length != 0) { List safe = getSafeLore(lore); + meta.setDisplayName(safe.get(0)); meta.setLore(safe.subList(1, safe.size())); } else { meta.setLore(Collections.EMPTY_LIST); } + item.setItemMeta(meta); } + return item; } public static ItemStack createButtonItem(CompatibleMaterial mat, int amount, String[] lore) { ItemStack item = mat.getItem(); item.setAmount(amount); + ItemMeta meta = item.getItemMeta(); + if (meta != null) { if (lore != null && lore.length != 0) { List safe = getSafeLore(lore); + meta.setDisplayName(safe.get(0)); meta.setLore(safe.subList(1, safe.size())); } else { meta.setLore(Collections.EMPTY_LIST); } + item.setItemMeta(meta); } + return item; } public static ItemStack createButtonItem(ItemStack from, String[] lore) { ItemStack item = from.clone(); ItemMeta meta = item.getItemMeta(); + if (meta != null) { if (lore != null && lore.length != 0) { List safe = getSafeLore(lore); + meta.setDisplayName(safe.get(0)); meta.setLore(safe.subList(1, safe.size())); } else { meta.setLore(Collections.EMPTY_LIST); } + item.setItemMeta(meta); } + return item; } public static ItemStack createButtonItem(CompatibleMaterial mat, List lore) { ItemStack item = mat.getItem(); ItemMeta meta = item.getItemMeta(); + if (meta != null) { if (lore != null && !lore.isEmpty()) { List safe = getSafeLore(lore); + meta.setDisplayName(safe.get(0)); meta.setLore(safe.subList(1, safe.size())); } else { meta.setLore(Collections.EMPTY_LIST); } + item.setItemMeta(meta); } + return item; } @@ -251,81 +306,101 @@ public class GuiUtils { ItemStack item = mat.getItem(); item.setAmount(amount); ItemMeta meta = item.getItemMeta(); + if (meta != null) { if (lore != null && !lore.isEmpty()) { List safe = getSafeLore(lore); + meta.setDisplayName(safe.get(0)); meta.setLore(safe.subList(1, safe.size())); } else { meta.setLore(Collections.EMPTY_LIST); } + item.setItemMeta(meta); } + return item; } public static ItemStack createButtonItem(ItemStack from, List lore) { ItemStack item = from.clone(); ItemMeta meta = item.getItemMeta(); + if (meta != null) { if (lore != null && !lore.isEmpty()) { List safe = getSafeLore(lore); + meta.setDisplayName(safe.get(0)); meta.setLore(safe.subList(1, safe.size())); } else { meta.setLore(Collections.EMPTY_LIST); } + item.setItemMeta(meta); } + return item; } public static ItemStack updateItem(ItemStack item, String title, String... lore) { ItemMeta meta = item.getItemMeta(); + if (meta != null) { meta.setDisplayName(title); + if (lore != null) { meta.setLore(getSafeLore(lore)); } else { meta.setLore(Collections.EMPTY_LIST); } + item.setItemMeta(meta); } + return item; } public static ItemStack updateItemName(ItemStack item, String title) { ItemMeta meta = item.getItemMeta(); + if (meta != null) { meta.setDisplayName(title); item.setItemMeta(meta); } + return item; } public static ItemStack updateItemLore(ItemStack item, String... lore) { ItemMeta meta = item.getItemMeta(); + if (meta != null) { if (lore != null && lore.length != 0) { meta.setLore(getSafeLore(lore)); } else { meta.setLore(Collections.EMPTY_LIST); } + item.setItemMeta(meta); } + return item; } public static ItemStack updateItemLore(ItemStack item, List lore) { ItemMeta meta = item.getItemMeta(); + if (meta != null) { if (lore != null) { meta.setLore(getSafeLore(lore)); } else { meta.setLore(Collections.EMPTY_LIST); } + item.setItemMeta(meta); } + return item; } @@ -333,16 +408,21 @@ public class GuiUtils { if (!matTo.matches(item)) { item = matTo.getItem(); } + ItemMeta meta = item.getItemMeta(); + if (meta != null) { meta.setDisplayName(title); + if (lore != null) { meta.setLore(getSafeLore(lore)); } else { meta.setLore(Collections.EMPTY_LIST); } + item.setItemMeta(meta); } + return item; } @@ -350,30 +430,39 @@ public class GuiUtils { if (!CompatibleMaterial.getMaterial(item).matches(to)) { item = to.clone(); } + ItemMeta meta = item.getItemMeta(); + if (meta != null) { meta.setDisplayName(title); + if (lore != null) { meta.setLore(getSafeLore(lore)); } else { meta.setLore(Collections.EMPTY_LIST); } + item.setItemMeta(meta); } + return item; } public static ItemStack updateItem(ItemStack item, String title, List lore) { ItemMeta meta = item.getItemMeta(); + if (meta != null) { meta.setDisplayName(title); + if (lore != null) { meta.setLore(getSafeLore(lore)); } else { meta.setLore(Collections.EMPTY_LIST); } + item.setItemMeta(meta); } + return item; } @@ -381,16 +470,21 @@ public class GuiUtils { if (!matTo.matches(item)) { item = matTo.getItem(); } + ItemMeta meta = item.getItemMeta(); + if (meta != null) { meta.setDisplayName(title); + if (lore != null) { meta.setLore(getSafeLore(lore)); } else { meta.setLore(Collections.EMPTY_LIST); } + item.setItemMeta(meta); } + return item; } @@ -398,16 +492,21 @@ public class GuiUtils { if (!CompatibleMaterial.getMaterial(item).matches(to)) { item = to.clone(); } + ItemMeta meta = item.getItemMeta(); + if (meta != null) { meta.setDisplayName(title); + if (lore != null) { meta.setLore(getSafeLore(lore)); } else { meta.setLore(Collections.EMPTY_LIST); } + item.setItemMeta(meta); } + return item; } } diff --git a/Core/src/main/java/com/songoda/core/gui/PopupMessage.java b/Core/src/main/java/com/songoda/core/gui/PopupMessage.java index 76067e85..28d329ad 100644 --- a/Core/src/main/java/com/songoda/core/gui/PopupMessage.java +++ b/Core/src/main/java/com/songoda/core/gui/PopupMessage.java @@ -24,7 +24,6 @@ import java.util.UUID; * Calling this class on anything below 1.12 will cause ClassLoader Exceptions! */ class PopupMessage { - private static final Gson gson = new GsonBuilder().setPrettyPrinting().create(); private static final HashSet registeredMessages = new HashSet(); @@ -52,14 +51,18 @@ class PopupMessage { private String getJSON() { JsonObject json = new JsonObject(); JsonObject advDisplay = new JsonObject(); + if (this.icon != null) { JsonObject displayIcon = new JsonObject(); displayIcon.addProperty("item", "minecraft:" + this.icon.getMaterial().name().toLowerCase()); + if (this.icon.usesData()) { displayIcon.addProperty("data", this.icon.getData()); } + advDisplay.add("icon", displayIcon); } + advDisplay.add("title", gson.fromJson(ComponentSerializer.toString(this.title), JsonElement.class)); advDisplay.addProperty("background", background.key); advDisplay.addProperty("description", ""); @@ -88,24 +91,27 @@ class PopupMessage { final Advancement adv = getAdvancement(); final AdvancementProgress progress = pl.getAdvancementProgress(adv); - if (!progress.isDone()) + if (!progress.isDone()) { progress.getRemainingCriteria().forEach((crit) -> progress.awardCriteria(crit)); + } } protected void revoke(final Player pl) { final Advancement adv = getAdvancement(); final AdvancementProgress prog = pl.getAdvancementProgress(adv); - if (prog.isDone()) + if (prog.isDone()) { prog.getAwardedCriteria().forEach((crit) -> prog.revokeCriteria(crit)); + } } protected void add() { if (!registeredMessages.contains(id)) { registeredMessages.add(id); + try { Bukkit.getUnsafe().loadAdvancement(key, getJSON()); - } catch (IllegalArgumentException e) { + } catch (IllegalArgumentException ex) { Bukkit.getLogger().warning("Failed to create popup advancement!"); } } @@ -126,6 +132,7 @@ class PopupMessage { TASK, CHALLENGE, GOAL; + final String id; private FrameType() { @@ -163,6 +170,7 @@ class PopupMessage { USED_ENDER_EYE, USED_TOTEM, VILLAGER_TRADE; + final ServerVersion minVersion; final String compatible; final String key; diff --git a/Core/src/main/java/com/songoda/core/gui/SimplePagedGui.java b/Core/src/main/java/com/songoda/core/gui/SimplePagedGui.java index 025dd119..2ea84098 100644 --- a/Core/src/main/java/com/songoda/core/gui/SimplePagedGui.java +++ b/Core/src/main/java/com/songoda/core/gui/SimplePagedGui.java @@ -1,225 +1,238 @@ -package com.songoda.core.gui; - -import com.songoda.core.compatibility.CompatibleMaterial; -import com.songoda.core.gui.events.GuiClickEvent; -import com.songoda.core.gui.methods.Clickable; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.event.inventory.ClickType; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; - -import java.util.List; -import java.util.Map; - -/** - * Paged GUI for when you aren't going to be making too many pages - * - * @author jascotty2 - * @since 2019-08-31 - */ -public class SimplePagedGui extends Gui { - - protected boolean useHeader; - private int rowsPerPage, maxCellSlot; - protected ItemStack headerBackItem; - protected ItemStack footerBackItem; - final int nextPageIndex = 4, prevPageIndex = 6; - - public SimplePagedGui() { - this(null); - } - - public SimplePagedGui(Gui parent) { - super(parent); - - nextPage = GuiUtils.createButtonItem(CompatibleMaterial.ARROW, "Next Page"); - prevPage = GuiUtils.createButtonItem(CompatibleMaterial.ARROW, "Previous Page"); - } - - public SimplePagedGui setUseHeader(boolean useHeader) { - this.useHeader = useHeader; - return this; - } - - public ItemStack getHeaderBackItem() { - return headerBackItem; - } - - public SimplePagedGui setHeaderBackItem(ItemStack headerBackItem) { - this.headerBackItem = headerBackItem; - return this; - } - - public ItemStack getFooterBackItem() { - return footerBackItem; - } - - public SimplePagedGui setFooterBackItem(ItemStack footerBackItem) { - this.footerBackItem = footerBackItem; - return this; - } - - @Override - public SimplePagedGui setItem(int row, int col, ItemStack item) { - return setItem(col + row * 9, item); - } - - @Override - public SimplePagedGui setItem(int cell, ItemStack item) { - // set the cell relative to the current page - int cellIndex = cell < 0 ? cell : (page == 1 || (useHeader && cell < 9) ? cell : (cell + (page - 1) * (rowsPerPage * 9))); - - cellItems.put(cellIndex, item); - if (open && cell >= 0 && cell < inventory.getSize()) { - inventory.setItem(cell, item); - } - return this; - } - - @Override - public void nextPage() { - if (page < pages) { - ++page; - showPage(); - } - } - - @Override - public void prevPage() { - if (page > 1) { - --page; - showPage(); - } - } - - public void showPage() { - int startCell = useHeader ? 9 : 0; - int cellIndex = startCell + (page - 1) * (rowsPerPage * 9); - - for (int i = startCell; i < (rows - 1) * 9; ++i) { - final ItemStack item = cellItems.get(cellIndex++); - inventory.setItem(i, item != null ? item : blankItem); - } - // page markers - updatePageNavigation(); - } - - @Override - protected void updatePageNavigation() { - if (page > 1) { - inventory.setItem(inventory.getSize() - prevPageIndex, prevPage); - this.setButton(-prevPageIndex, prevPage, ClickType.LEFT, (event) -> this.prevPage()); - } else { - inventory.setItem(inventory.getSize() - prevPageIndex, footerBackItem != null ? footerBackItem : blankItem); - this.setItem(-prevPageIndex, null); - this.clearActions(-prevPageIndex); - } - if (pages > 1 && page != pages) { - inventory.setItem(inventory.getSize() - nextPageIndex, nextPage); - this.setButton(-nextPageIndex, nextPage, ClickType.LEFT, (event) -> this.nextPage()); - } else { - inventory.setItem(inventory.getSize() - nextPageIndex, footerBackItem != null ? footerBackItem : blankItem); - this.setItem(-nextPageIndex, null); - this.clearActions(-nextPageIndex); - } - } - - @Override - protected Inventory generateInventory(GuiManager manager) { - this.guiManager = manager; - // calculate pages here - rowsPerPage = useHeader ? 4 : 5; - maxCellSlot = (this.cellItems.isEmpty() ? 0 : this.cellItems.keySet().stream().max(Integer::compare).get()) + 1; - int maxRows = (int) Math.ceil(maxCellSlot / 9.); - pages = (int) Math.max(1, Math.ceil(maxRows / (double) rowsPerPage)); - this.setRows(maxRows + (useHeader ? 1 : 0)); - - // create inventory view - createInventory(); - - // populate and return the display inventory - setPage(Math.min(page, pages)); - update(); - return inventory; - } - - @Override - protected void createInventory() { - final int cells = rows * 9; - inventory = Bukkit.getServer().createInventory(new GuiHolder(guiManager, this), cells, - title == null ? "" : trimTitle(title)); - } - - @Override - public void update() { - if (inventory == null) { - return; - } - - // calculate pages here - rowsPerPage = useHeader ? 4 : 5; - maxCellSlot = (this.cellItems.isEmpty() ? 0 : this.cellItems.keySet().stream().max(Integer::compare).get()) + 1; - int maxRows = Math.max((useHeader ? 1 : 0), (int) Math.ceil(maxCellSlot / 9.)); - pages = (int) Math.ceil(maxRows / rowsPerPage); - - // create a new inventory if needed - List toUpdate = null; - if (Math.min(54, (maxRows + (useHeader ? 1 : 0)) * 9) != inventory.getSize()) { - toUpdate = getPlayers(); - this.setRows(maxRows + (useHeader ? 1 : 0)); - createInventory(); - } - - // populate header - if (useHeader) { - for (int i = 0; i < 9; ++i) { - final ItemStack item = cellItems.get(i); - inventory.setItem(i, item != null ? item : (headerBackItem != null ? headerBackItem : blankItem)); - } - } - - // last row is dedicated to pagation - final int cells = rows * 9; - for (int i = cells - 9; i < cells; ++i) { - inventory.setItem(i, footerBackItem != null ? footerBackItem : blankItem); - } - - // fill out the rest of the page - showPage(); - - // did we need to change the display window size? - if (toUpdate != null) { - // whoopsie! - exit(); - toUpdate.forEach(player -> guiManager.showGUI(player, this)); - } - } - - @Override - protected boolean onClick(GuiManager manager, Player player, Inventory inventory, InventoryClickEvent event) { - int cell = event.getSlot(); - Map conditionals; - - if (useHeader && cell < 9) { - conditionals = conditionalButtons.get(cell); - } else if (cell >= (rows - 1) * 9) { - // footer row - conditionals = conditionalButtons.get(cell - (rows * 9)); - } else { - int cellIndex = page == 1 || (useHeader && cell < 9) ? cell : (cell + (page - 1) * (rowsPerPage * 9)); - conditionals = conditionalButtons.get(cellIndex); - } - - Clickable button; - if (conditionals != null - && ((button = conditionals.get(event.getClick())) != null || (button = conditionals.get(null)) != null)) { - button.onClick(new GuiClickEvent(manager, this, player, event, cell, true)); - } else { - // no event for this button - return false; - } - return true; - } -} +package com.songoda.core.gui; + +import com.songoda.core.compatibility.CompatibleMaterial; +import com.songoda.core.gui.events.GuiClickEvent; +import com.songoda.core.gui.methods.Clickable; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +import java.util.List; +import java.util.Map; + +/** + * Paged GUI for when you aren't going to be making too many pages + * + * @author jascotty2 + * @since 2019-08-31 + */ +public class SimplePagedGui extends Gui { + protected boolean useHeader; + private int rowsPerPage, maxCellSlot; + protected ItemStack headerBackItem; + protected ItemStack footerBackItem; + final int nextPageIndex = 4, prevPageIndex = 6; + + public SimplePagedGui() { + this(null); + } + + public SimplePagedGui(Gui parent) { + super(parent); + + nextPage = GuiUtils.createButtonItem(CompatibleMaterial.ARROW, "Next Page"); + prevPage = GuiUtils.createButtonItem(CompatibleMaterial.ARROW, "Previous Page"); + } + + public SimplePagedGui setUseHeader(boolean useHeader) { + this.useHeader = useHeader; + return this; + } + + public ItemStack getHeaderBackItem() { + return headerBackItem; + } + + public SimplePagedGui setHeaderBackItem(ItemStack headerBackItem) { + this.headerBackItem = headerBackItem; + return this; + } + + public ItemStack getFooterBackItem() { + return footerBackItem; + } + + public SimplePagedGui setFooterBackItem(ItemStack footerBackItem) { + this.footerBackItem = footerBackItem; + return this; + } + + @Override + public SimplePagedGui setItem(int row, int col, ItemStack item) { + return setItem(col + row * 9, item); + } + + @Override + public SimplePagedGui setItem(int cell, ItemStack item) { + // set the cell relative to the current page + int cellIndex = cell < 0 ? cell : (page == 1 || (useHeader && cell < 9) ? cell : (cell + (page - 1) * (rowsPerPage * 9))); + + cellItems.put(cellIndex, item); + if (open && cell >= 0 && cell < inventory.getSize()) { + inventory.setItem(cell, item); + } + + return this; + } + + @Override + public void nextPage() { + if (page < pages) { + ++page; + showPage(); + } + } + + @Override + public void prevPage() { + if (page > 1) { + --page; + showPage(); + } + } + + public void showPage() { + int startCell = useHeader ? 9 : 0; + int cellIndex = startCell + (page - 1) * (rowsPerPage * 9); + + for (int i = startCell; i < (rows - 1) * 9; ++i) { + final ItemStack item = cellItems.get(cellIndex++); + inventory.setItem(i, item != null ? item : blankItem); + } + + // page markers + updatePageNavigation(); + } + + @Override + protected void updatePageNavigation() { + if (page > 1) { + inventory.setItem(inventory.getSize() - prevPageIndex, prevPage); + + this.setButton(-prevPageIndex, prevPage, ClickType.LEFT, (event) -> this.prevPage()); + } else { + inventory.setItem(inventory.getSize() - prevPageIndex, footerBackItem != null ? footerBackItem : blankItem); + + this.setItem(-prevPageIndex, null); + this.clearActions(-prevPageIndex); + } + + if (pages > 1 && page != pages) { + inventory.setItem(inventory.getSize() - nextPageIndex, nextPage); + + this.setButton(-nextPageIndex, nextPage, ClickType.LEFT, (event) -> this.nextPage()); + } else { + inventory.setItem(inventory.getSize() - nextPageIndex, footerBackItem != null ? footerBackItem : blankItem); + + this.setItem(-nextPageIndex, null); + this.clearActions(-nextPageIndex); + } + } + + @Override + protected Inventory generateInventory(GuiManager manager) { + this.guiManager = manager; + + // calculate pages here + rowsPerPage = useHeader ? 4 : 5; + maxCellSlot = (this.cellItems.isEmpty() ? 0 : this.cellItems.keySet().stream().max(Integer::compare).get()) + 1; + int maxRows = (int) Math.ceil(maxCellSlot / 9.); + pages = (int) Math.max(1, Math.ceil(maxRows / (double) rowsPerPage)); + this.setRows(maxRows + (useHeader ? 1 : 0)); + + // create inventory view + createInventory(); + + // populate and return the display inventory + setPage(Math.min(page, pages)); + update(); + + return inventory; + } + + @Override + protected void createInventory() { + final int cells = rows * 9; + + inventory = Bukkit.getServer().createInventory(new GuiHolder(guiManager, this), cells, + title == null ? "" : trimTitle(title)); + } + + @Override + public void update() { + if (inventory == null) { + return; + } + + // calculate pages here + rowsPerPage = useHeader ? 4 : 5; + maxCellSlot = (this.cellItems.isEmpty() ? 0 : this.cellItems.keySet().stream().max(Integer::compare).get()) + 1; + int maxRows = Math.max((useHeader ? 1 : 0), (int) Math.ceil(maxCellSlot / 9.)); + pages = (int) Math.ceil(maxRows / rowsPerPage); + + // create a new inventory if needed + List toUpdate = null; + if (Math.min(54, (maxRows + (useHeader ? 1 : 0)) * 9) != inventory.getSize()) { + toUpdate = getPlayers(); + + this.setRows(maxRows + (useHeader ? 1 : 0)); + + createInventory(); + } + + // populate header + if (useHeader) { + for (int i = 0; i < 9; ++i) { + final ItemStack item = cellItems.get(i); + + inventory.setItem(i, item != null ? item : (headerBackItem != null ? headerBackItem : blankItem)); + } + } + + // last row is dedicated to pagation + final int cells = rows * 9; + for (int i = cells - 9; i < cells; ++i) { + inventory.setItem(i, footerBackItem != null ? footerBackItem : blankItem); + } + + // fill out the rest of the page + showPage(); + + // did we need to change the display window size? + if (toUpdate != null) { + // whoopsie! + exit(); + toUpdate.forEach(player -> guiManager.showGUI(player, this)); + } + } + + @Override + protected boolean onClick(GuiManager manager, Player player, Inventory inventory, InventoryClickEvent event) { + int cell = event.getSlot(); + Map conditionals; + + if (useHeader && cell < 9) { + conditionals = conditionalButtons.get(cell); + } else if (cell >= (rows - 1) * 9) { + // footer row + conditionals = conditionalButtons.get(cell - (rows * 9)); + } else { + int cellIndex = page == 1 || (useHeader && cell < 9) ? cell : (cell + (page - 1) * (rowsPerPage * 9)); + conditionals = conditionalButtons.get(cellIndex); + } + + Clickable button; + if (conditionals != null + && ((button = conditionals.get(event.getClick())) != null || (button = conditionals.get(null)) != null)) { + button.onClick(new GuiClickEvent(manager, this, player, event, cell, true)); + } else { + // no event for this button + return false; + } + + return true; + } +} diff --git a/Core/src/main/java/com/songoda/core/gui/events/GuiClickEvent.java b/Core/src/main/java/com/songoda/core/gui/events/GuiClickEvent.java index 7864b33b..233445e4 100644 --- a/Core/src/main/java/com/songoda/core/gui/events/GuiClickEvent.java +++ b/Core/src/main/java/com/songoda/core/gui/events/GuiClickEvent.java @@ -17,10 +17,13 @@ public class GuiClickEvent extends GuiEvent { public GuiClickEvent(GuiManager manager, Gui gui, Player player, InventoryClickEvent event, int slot, boolean guiClicked) { super(manager, gui, player); + this.slot = slot; this.guiClicked = guiClicked; this.cursor = event.getCursor(); + Inventory clicked = event.getClickedInventory(); + this.clickedItem = clicked == null ? null : clicked.getItem(event.getSlot()); this.clickType = event.getClick(); this.event = event; diff --git a/Core/src/main/java/com/songoda/core/gui/events/GuiCloseEvent.java b/Core/src/main/java/com/songoda/core/gui/events/GuiCloseEvent.java index 94dcedd5..4cd62880 100644 --- a/Core/src/main/java/com/songoda/core/gui/events/GuiCloseEvent.java +++ b/Core/src/main/java/com/songoda/core/gui/events/GuiCloseEvent.java @@ -5,7 +5,6 @@ import com.songoda.core.gui.GuiManager; import org.bukkit.entity.Player; public class GuiCloseEvent extends GuiEvent { - public GuiCloseEvent(GuiManager manager, Gui gui, Player player) { super(manager, gui, player); } diff --git a/Core/src/main/java/com/songoda/core/gui/events/GuiDropItemEvent.java b/Core/src/main/java/com/songoda/core/gui/events/GuiDropItemEvent.java index 0f90f4fa..6fb22fa0 100644 --- a/Core/src/main/java/com/songoda/core/gui/events/GuiDropItemEvent.java +++ b/Core/src/main/java/com/songoda/core/gui/events/GuiDropItemEvent.java @@ -14,6 +14,7 @@ public class GuiDropItemEvent extends GuiEvent { public GuiDropItemEvent(GuiManager manager, Gui gui, Player player, InventoryClickEvent event) { super(manager, gui, player); + this.cursor = event.getCursor(); this.clickType = event.getClick(); this.event = event; diff --git a/Core/src/main/java/com/songoda/core/gui/events/GuiEvent.java b/Core/src/main/java/com/songoda/core/gui/events/GuiEvent.java index 4bcd4e77..3792cc23 100644 --- a/Core/src/main/java/com/songoda/core/gui/events/GuiEvent.java +++ b/Core/src/main/java/com/songoda/core/gui/events/GuiEvent.java @@ -5,7 +5,6 @@ import com.songoda.core.gui.GuiManager; import org.bukkit.entity.Player; public abstract class GuiEvent { - public final GuiManager manager; public final Gui gui; public final Player player; diff --git a/Core/src/main/java/com/songoda/core/gui/events/GuiOpenEvent.java b/Core/src/main/java/com/songoda/core/gui/events/GuiOpenEvent.java index def71475..405b416c 100644 --- a/Core/src/main/java/com/songoda/core/gui/events/GuiOpenEvent.java +++ b/Core/src/main/java/com/songoda/core/gui/events/GuiOpenEvent.java @@ -5,7 +5,6 @@ import com.songoda.core.gui.GuiManager; import org.bukkit.entity.Player; public class GuiOpenEvent extends GuiEvent { - public GuiOpenEvent(GuiManager manager, Gui gui, Player player) { super(manager, gui, player); } diff --git a/Core/src/main/java/com/songoda/core/gui/events/GuiPageEvent.java b/Core/src/main/java/com/songoda/core/gui/events/GuiPageEvent.java index 4d3b15fd..6065599c 100644 --- a/Core/src/main/java/com/songoda/core/gui/events/GuiPageEvent.java +++ b/Core/src/main/java/com/songoda/core/gui/events/GuiPageEvent.java @@ -4,7 +4,6 @@ import com.songoda.core.gui.Gui; import com.songoda.core.gui.GuiManager; public class GuiPageEvent { - final Gui gui; final GuiManager manager; final int lastPage; diff --git a/Core/src/main/java/com/songoda/core/gui/methods/Clickable.java b/Core/src/main/java/com/songoda/core/gui/methods/Clickable.java index f65edd10..de703df1 100644 --- a/Core/src/main/java/com/songoda/core/gui/methods/Clickable.java +++ b/Core/src/main/java/com/songoda/core/gui/methods/Clickable.java @@ -3,6 +3,5 @@ package com.songoda.core.gui.methods; import com.songoda.core.gui.events.GuiClickEvent; public interface Clickable { - void onClick(GuiClickEvent event); } diff --git a/Core/src/main/java/com/songoda/core/gui/methods/Closable.java b/Core/src/main/java/com/songoda/core/gui/methods/Closable.java index 41e5898d..01f0807d 100644 --- a/Core/src/main/java/com/songoda/core/gui/methods/Closable.java +++ b/Core/src/main/java/com/songoda/core/gui/methods/Closable.java @@ -3,6 +3,5 @@ package com.songoda.core.gui.methods; import com.songoda.core.gui.events.GuiCloseEvent; public interface Closable { - void onClose(GuiCloseEvent event); } diff --git a/Core/src/main/java/com/songoda/core/gui/methods/Droppable.java b/Core/src/main/java/com/songoda/core/gui/methods/Droppable.java index e8815565..1a8bdb64 100644 --- a/Core/src/main/java/com/songoda/core/gui/methods/Droppable.java +++ b/Core/src/main/java/com/songoda/core/gui/methods/Droppable.java @@ -3,6 +3,5 @@ package com.songoda.core.gui.methods; import com.songoda.core.gui.events.GuiDropItemEvent; public interface Droppable { - boolean onDrop(GuiDropItemEvent event); } diff --git a/Core/src/main/java/com/songoda/core/gui/methods/Openable.java b/Core/src/main/java/com/songoda/core/gui/methods/Openable.java index 02033422..78c2b451 100644 --- a/Core/src/main/java/com/songoda/core/gui/methods/Openable.java +++ b/Core/src/main/java/com/songoda/core/gui/methods/Openable.java @@ -1,8 +1,7 @@ -package com.songoda.core.gui.methods; - -import com.songoda.core.gui.events.GuiOpenEvent; - -public interface Openable { - - void onOpen(GuiOpenEvent event); -} +package com.songoda.core.gui.methods; + +import com.songoda.core.gui.events.GuiOpenEvent; + +public interface Openable { + void onOpen(GuiOpenEvent event); +} diff --git a/Core/src/main/java/com/songoda/core/gui/methods/Pagable.java b/Core/src/main/java/com/songoda/core/gui/methods/Pagable.java index 239ba099..7b948435 100644 --- a/Core/src/main/java/com/songoda/core/gui/methods/Pagable.java +++ b/Core/src/main/java/com/songoda/core/gui/methods/Pagable.java @@ -3,6 +3,5 @@ package com.songoda.core.gui.methods; import com.songoda.core.gui.events.GuiPageEvent; public interface Pagable { - void onPageChange(GuiPageEvent event); } diff --git a/Core/src/main/java/com/songoda/core/hooks/EconomyManager.java b/Core/src/main/java/com/songoda/core/hooks/EconomyManager.java index 5c900f58..1f6d3434 100644 --- a/Core/src/main/java/com/songoda/core/hooks/EconomyManager.java +++ b/Core/src/main/java/com/songoda/core/hooks/EconomyManager.java @@ -8,7 +8,6 @@ import org.bukkit.OfflinePlayer; * A convenience class for static access to an Economy HookManager */ public class EconomyManager { - private static char currencySymbol = '$'; private static final HookManager manager = new HookManager(Economy.class); @@ -48,8 +47,6 @@ public class EconomyManager { /** * Get the name of the economy plugin being used.
* NOTE: using a default economy assumes that this library is shaded - * - * @return */ public static String getName() { return manager.getName(); @@ -119,7 +116,7 @@ public class EconomyManager { } /** - * Change the curency symbl used in the #formatEconomy method. + * Change the curency symbol used in the #formatEconomy method. * * @param currencySymbol the new symbol */ @@ -128,7 +125,7 @@ public class EconomyManager { } /** - * Change the curency symbl used in the #formatEconomy method. + * Change the curency symbol used in the #formatEconomy method. * * @param currencySymbol the new symbol */ diff --git a/Core/src/main/java/com/songoda/core/hooks/EntityStackerManager.java b/Core/src/main/java/com/songoda/core/hooks/EntityStackerManager.java index feac60bf..0f263fc3 100644 --- a/Core/src/main/java/com/songoda/core/hooks/EntityStackerManager.java +++ b/Core/src/main/java/com/songoda/core/hooks/EntityStackerManager.java @@ -8,7 +8,6 @@ import org.bukkit.entity.LivingEntity; * A convenience class for static access to a Stacker HookManager */ public class EntityStackerManager { - private static final HookManager manager = new HookManager(Stacker.class); /** @@ -56,8 +55,9 @@ public class EntityStackerManager { } public static void remove(LivingEntity entity, int amount) { - if (manager.isEnabled()) + if (manager.isEnabled()) { manager.getCurrentHook().remove(entity, amount); + } } public static void addOne(LivingEntity entity) { @@ -65,8 +65,9 @@ public class EntityStackerManager { } public static void add(LivingEntity entity, int amount) { - if (manager.isEnabled()) + if (manager.isEnabled()) { manager.getCurrentHook().add(entity, amount); + } } public static int getMinStackSize(EntityType type) { diff --git a/Core/src/main/java/com/songoda/core/hooks/HologramManager.java b/Core/src/main/java/com/songoda/core/hooks/HologramManager.java index de105a42..23abc545 100644 --- a/Core/src/main/java/com/songoda/core/hooks/HologramManager.java +++ b/Core/src/main/java/com/songoda/core/hooks/HologramManager.java @@ -11,7 +11,6 @@ import java.util.Map; * A convenience class for static access to a Holograms HookManager */ public class HologramManager { - private static final HookManager manager = new HookManager(Holograms.class); /** @@ -49,37 +48,44 @@ public class HologramManager { } public static void createHologram(Location location, String line) { - if (manager.isEnabled()) + if (manager.isEnabled()) { manager.getCurrentHook().createHologram(location, line); + } } public static void createHologram(Location location, List lines) { - if (manager.isEnabled()) + if (manager.isEnabled()) { manager.getCurrentHook().createHologram(location, lines); + } } public static void removeHologram(Location location) { - if (manager.isEnabled()) + if (manager.isEnabled()) { manager.getCurrentHook().removeHologram(location); + } } public static void removeAllHolograms() { - if (manager.isEnabled()) + if (manager.isEnabled()) { manager.getCurrentHook().removeAllHolograms(); + } } public static void updateHologram(Location location, String line) { - if (manager.isEnabled()) + if (manager.isEnabled()) { manager.getCurrentHook().updateHologram(location, line); + } } public static void updateHologram(Location location, List lines) { - if (manager.isEnabled()) + if (manager.isEnabled()) { manager.getCurrentHook().updateHologram(location, lines); + } } public static void bulkUpdateHolograms(Map> holograms) { - if (manager.isEnabled()) + if (manager.isEnabled()) { manager.getCurrentHook().bulkUpdateHolograms(holograms); + } } } diff --git a/Core/src/main/java/com/songoda/core/hooks/Hook.java b/Core/src/main/java/com/songoda/core/hooks/Hook.java index 99502f4b..647eadeb 100644 --- a/Core/src/main/java/com/songoda/core/hooks/Hook.java +++ b/Core/src/main/java/com/songoda/core/hooks/Hook.java @@ -1,18 +1,15 @@ -package com.songoda.core.hooks; - -public interface Hook { - - /** - * Get the name of the plugin being used - * - * @return - */ - abstract String getName(); - - /** - * Check to see if the economy plugin being used is active - * - * @return true if the plugin is loaded and active - */ - abstract boolean isEnabled(); -} +package com.songoda.core.hooks; + +public interface Hook { + /** + * Get the name of the plugin being used + */ + abstract String getName(); + + /** + * Check to see if the economy plugin being used is active + * + * @return true if the plugin is loaded and active + */ + abstract boolean isEnabled(); +} diff --git a/Core/src/main/java/com/songoda/core/hooks/HookManager.java b/Core/src/main/java/com/songoda/core/hooks/HookManager.java index 0f96017d..425cc706 100644 --- a/Core/src/main/java/com/songoda/core/hooks/HookManager.java +++ b/Core/src/main/java/com/songoda/core/hooks/HookManager.java @@ -10,7 +10,6 @@ import java.util.Map; import java.util.stream.Collectors; public class HookManager { - private final Class typeClass; private T defaultHook = null; private boolean loaded = false; @@ -36,9 +35,11 @@ public class HookManager { if (!loaded) { registeredHooks.putAll(PluginHook.loadHooks(typeClass, hookingPlugin).entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> (T) e.getValue()))); + if (!registeredHooks.isEmpty()) { defaultHook = (T) registeredHooks.values().iterator().next(); } + loaded = true; } } @@ -66,8 +67,10 @@ public class HookManager { T hook = getHook(name); if (hook != null) { defaultHook = hook; + return true; } + return false; } @@ -84,8 +87,10 @@ public class HookManager { T hook = getHook(plugin); if (hook != null) { defaultHook = hook; + return true; } + return false; } @@ -97,8 +102,10 @@ public class HookManager { * @return returns null if plugin is not enabled */ public T getHook(String name) { - if (name == null) + if (name == null) { return null; + } + final String plugin = name.trim(); return (T) registeredHooks.get(registeredHooks.keySet().stream() .filter(type -> type.plugin.equalsIgnoreCase(plugin)) diff --git a/Core/src/main/java/com/songoda/core/hooks/JobsHook.java b/Core/src/main/java/com/songoda/core/hooks/JobsHook.java index 7e43d6f8..2c6145fc 100644 --- a/Core/src/main/java/com/songoda/core/hooks/JobsHook.java +++ b/Core/src/main/java/com/songoda/core/hooks/JobsHook.java @@ -1,233 +1,267 @@ -package com.songoda.core.hooks; - -import com.songoda.core.hooks.jobs.JobsHandler; -import com.songoda.core.hooks.jobs.JobsPlayerHandler; -import org.bukkit.block.Block; -import org.bukkit.entity.Entity; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - -import java.util.Collections; -import java.util.List; - -public class JobsHook { - - static boolean canHook; - - static { - try { - // if this class exists, we're good to use Jobs classes - Class.forName("com.gamingmesh.jobs.Jobs"); - canHook = true; - } catch (ClassNotFoundException ex) { - } - } - - public static JobsPlayerHandler getPlayer(Player player) { - if (canHook) { - return JobsPlayerHandler.loadPlayer(player); - } - return null; - } - - public static boolean isEnabled() { - return canHook; - } - - public static List getAllJobs() { - if (canHook) { - return JobsHandler.getJobs(); - } - return Collections.EMPTY_LIST; - } - - public static double getBoostExp(Player player, String job) { - JobsPlayerHandler jPlayer = getPlayer(player); - if (jPlayer != null) { - return jPlayer.getBoostExp(job); - } - return -1; - } - - public static double getBoostMoney(Player player, String job) { - JobsPlayerHandler jPlayer = getPlayer(player); - if (jPlayer != null) { - return jPlayer.getBoostMoney(job); - } - return -1; - } - - public static double getBoostPoints(Player player, String job) { - JobsPlayerHandler jPlayer = getPlayer(player); - if (jPlayer != null) { - return jPlayer.getBoostPoints(job); - } - return -1; - } - - public static void promoteJob(Player player, String job) { - JobsPlayerHandler jPlayer = getPlayer(player); - if (jPlayer != null) { - jPlayer.promoteJob(job); - } - } - - public static void promoteJob(Player player, String job, int levels) { - JobsPlayerHandler jPlayer = getPlayer(player); - if (jPlayer != null) { - jPlayer.promoteJob(job, levels); - } - } - - public static void demoteJob(Player player, String job) { - JobsPlayerHandler jPlayer = getPlayer(player); - if (jPlayer != null) { - jPlayer.demoteJob(job); - } - } - - public static void demoteJob(Player player, String job, int levels) { - JobsPlayerHandler jPlayer = getPlayer(player); - if (jPlayer != null) { - jPlayer.demoteJob(job, levels); - } - } - - public static void joinJob(Player player, String job) { - JobsPlayerHandler jPlayer = getPlayer(player); - if (jPlayer != null) { - jPlayer.joinJob(job); - } - } - - public static void leaveAllJobs(Player player) { - JobsPlayerHandler jPlayer = getPlayer(player); - if (jPlayer != null) { - jPlayer.leaveAllJobs(); - } - } - - public static void leaveJob(Player player, String job) { - JobsPlayerHandler jPlayer = getPlayer(player); - if (jPlayer != null) { - jPlayer.leaveJob(job); - } - } - - public static int getTotalLevels(Player player) { - JobsPlayerHandler jPlayer = getPlayer(player); - if (jPlayer != null) { - return jPlayer.getTotalLevels(); - } - return -1; - } - - public static int getMaxBrewingStandsAllowed(Player player) { - JobsPlayerHandler jPlayer = getPlayer(player); - if (jPlayer != null) { - return jPlayer.getMaxBrewingStandsAllowed(); - } - return -1; - } - - public static int getMaxFurnacesAllowed(Player player) { - JobsPlayerHandler jPlayer = getPlayer(player); - if (jPlayer != null) { - return jPlayer.getMaxFurnacesAllowed(); - } - return -1; - } - - public static List getJobs(Player player) { - JobsPlayerHandler jPlayer = getPlayer(player); - if (jPlayer != null) { - return jPlayer.getJobs(); - } - return Collections.EMPTY_LIST; - } - - public static void eatItem(Player player, ItemStack item) { - JobsPlayerHandler jPlayer = getPlayer(player); - if (jPlayer != null) { - jPlayer.eatItem(item); - } - } - - public static void breakBlock(Player player, Block block) { - JobsPlayerHandler jPlayer = getPlayer(player); - if (jPlayer != null) { - jPlayer.breakBlock(block); - } - } - - public static void tntBreakBlock(Player player, Block block) { - JobsPlayerHandler jPlayer = getPlayer(player); - if (jPlayer != null) { - jPlayer.tntBreakBlock(block); - } - } - - public static void placeBlock(Player player, Block block) { - JobsPlayerHandler jPlayer = getPlayer(player); - if (jPlayer != null) { - jPlayer.placeBlock(block); - } - } - - public static void placeEntity(Player player, Entity block) { - JobsPlayerHandler jPlayer = getPlayer(player); - if (jPlayer != null) { - jPlayer.placeEntity(block); - } - } - - public static void breakEntity(Player player, Entity block) { - JobsPlayerHandler jPlayer = getPlayer(player); - if (jPlayer != null) { - jPlayer.breakEntity(block); - } - } - - public static void breedEntity(Player player, LivingEntity entity) { - JobsPlayerHandler jPlayer = getPlayer(player); - if (jPlayer != null) { - jPlayer.breedEntity(entity); - } - } - - public static void killEntity(Player player, LivingEntity entity) { - JobsPlayerHandler jPlayer = getPlayer(player); - if (jPlayer != null) { - jPlayer.killEntity(entity); - } - } - - public static void tameEntity(Player player, LivingEntity entity) { - JobsPlayerHandler jPlayer = getPlayer(player); - if (jPlayer != null) { - jPlayer.tameEntity(entity); - } - } - - public static void catchFish(Player player, ItemStack items) { - JobsPlayerHandler jPlayer = getPlayer(player); - if (jPlayer != null) { - jPlayer.catchFish(items); - } - } - - public static void killEntity(Player player, LivingEntity entity, Entity damageSource) { - JobsPlayerHandler jPlayer = getPlayer(player); - if (jPlayer != null) { - jPlayer.killEntity(entity, damageSource); - } - } - - public static void itemEnchanted(Player player, ItemStack resultStack) { - JobsPlayerHandler jPlayer = getPlayer(player); - if (jPlayer != null) { - jPlayer.itemEnchanted(resultStack); - } - } -} +package com.songoda.core.hooks; + +import com.songoda.core.hooks.jobs.JobsHandler; +import com.songoda.core.hooks.jobs.JobsPlayerHandler; +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.Collections; +import java.util.List; + +public class JobsHook { + static boolean canHook; + + static { + try { + // if this class exists, we're good to use Jobs classes + Class.forName("com.gamingmesh.jobs.Jobs"); + canHook = true; + } catch (ClassNotFoundException ignore) { + } + } + + public static JobsPlayerHandler getPlayer(Player player) { + if (canHook) { + return JobsPlayerHandler.loadPlayer(player); + } + + return null; + } + + public static boolean isEnabled() { + return canHook; + } + + public static List getAllJobs() { + if (canHook) { + return JobsHandler.getJobs(); + } + + return Collections.EMPTY_LIST; + } + + public static double getBoostExp(Player player, String job) { + JobsPlayerHandler jPlayer = getPlayer(player); + + if (jPlayer != null) { + return jPlayer.getBoostExp(job); + } + + return -1; + } + + public static double getBoostMoney(Player player, String job) { + JobsPlayerHandler jPlayer = getPlayer(player); + + if (jPlayer != null) { + return jPlayer.getBoostMoney(job); + } + + return -1; + } + + public static double getBoostPoints(Player player, String job) { + JobsPlayerHandler jPlayer = getPlayer(player); + + if (jPlayer != null) { + return jPlayer.getBoostPoints(job); + } + + return -1; + } + + public static void promoteJob(Player player, String job) { + JobsPlayerHandler jPlayer = getPlayer(player); + + if (jPlayer != null) { + jPlayer.promoteJob(job); + } + } + + public static void promoteJob(Player player, String job, int levels) { + JobsPlayerHandler jPlayer = getPlayer(player); + + if (jPlayer != null) { + jPlayer.promoteJob(job, levels); + } + } + + public static void demoteJob(Player player, String job) { + JobsPlayerHandler jPlayer = getPlayer(player); + + if (jPlayer != null) { + jPlayer.demoteJob(job); + } + } + + public static void demoteJob(Player player, String job, int levels) { + JobsPlayerHandler jPlayer = getPlayer(player); + + if (jPlayer != null) { + jPlayer.demoteJob(job, levels); + } + } + + public static void joinJob(Player player, String job) { + JobsPlayerHandler jPlayer = getPlayer(player); + + if (jPlayer != null) { + jPlayer.joinJob(job); + } + } + + public static void leaveAllJobs(Player player) { + JobsPlayerHandler jPlayer = getPlayer(player); + + if (jPlayer != null) { + jPlayer.leaveAllJobs(); + } + } + + public static void leaveJob(Player player, String job) { + JobsPlayerHandler jPlayer = getPlayer(player); + + if (jPlayer != null) { + jPlayer.leaveJob(job); + } + } + + public static int getTotalLevels(Player player) { + JobsPlayerHandler jPlayer = getPlayer(player); + + if (jPlayer != null) { + return jPlayer.getTotalLevels(); + } + + return -1; + } + + public static int getMaxBrewingStandsAllowed(Player player) { + JobsPlayerHandler jPlayer = getPlayer(player); + + if (jPlayer != null) { + return jPlayer.getMaxBrewingStandsAllowed(); + } + + return -1; + } + + public static int getMaxFurnacesAllowed(Player player) { + JobsPlayerHandler jPlayer = getPlayer(player); + + if (jPlayer != null) { + return jPlayer.getMaxFurnacesAllowed(); + } + + return -1; + } + + public static List getJobs(Player player) { + JobsPlayerHandler jPlayer = getPlayer(player); + + if (jPlayer != null) { + return jPlayer.getJobs(); + } + + return Collections.EMPTY_LIST; + } + + public static void eatItem(Player player, ItemStack item) { + JobsPlayerHandler jPlayer = getPlayer(player); + + if (jPlayer != null) { + jPlayer.eatItem(item); + } + } + + public static void breakBlock(Player player, Block block) { + JobsPlayerHandler jPlayer = getPlayer(player); + + if (jPlayer != null) { + jPlayer.breakBlock(block); + } + } + + public static void tntBreakBlock(Player player, Block block) { + JobsPlayerHandler jPlayer = getPlayer(player); + + if (jPlayer != null) { + jPlayer.tntBreakBlock(block); + } + } + + public static void placeBlock(Player player, Block block) { + JobsPlayerHandler jPlayer = getPlayer(player); + + if (jPlayer != null) { + jPlayer.placeBlock(block); + } + } + + public static void placeEntity(Player player, Entity block) { + JobsPlayerHandler jPlayer = getPlayer(player); + + if (jPlayer != null) { + jPlayer.placeEntity(block); + } + } + + public static void breakEntity(Player player, Entity block) { + JobsPlayerHandler jPlayer = getPlayer(player); + + if (jPlayer != null) { + jPlayer.breakEntity(block); + } + } + + public static void breedEntity(Player player, LivingEntity entity) { + JobsPlayerHandler jPlayer = getPlayer(player); + + if (jPlayer != null) { + jPlayer.breedEntity(entity); + } + } + + public static void killEntity(Player player, LivingEntity entity) { + JobsPlayerHandler jPlayer = getPlayer(player); + + if (jPlayer != null) { + jPlayer.killEntity(entity); + } + } + + public static void tameEntity(Player player, LivingEntity entity) { + JobsPlayerHandler jPlayer = getPlayer(player); + + if (jPlayer != null) { + jPlayer.tameEntity(entity); + } + } + + public static void catchFish(Player player, ItemStack items) { + JobsPlayerHandler jPlayer = getPlayer(player); + + if (jPlayer != null) { + jPlayer.catchFish(items); + } + } + + public static void killEntity(Player player, LivingEntity entity, Entity damageSource) { + JobsPlayerHandler jPlayer = getPlayer(player); + + if (jPlayer != null) { + jPlayer.killEntity(entity, damageSource); + } + } + + public static void itemEnchanted(Player player, ItemStack resultStack) { + JobsPlayerHandler jPlayer = getPlayer(player); + + if (jPlayer != null) { + jPlayer.itemEnchanted(resultStack); + } + } +} diff --git a/Core/src/main/java/com/songoda/core/hooks/LogManager.java b/Core/src/main/java/com/songoda/core/hooks/LogManager.java index 37e845f2..b4478091 100644 --- a/Core/src/main/java/com/songoda/core/hooks/LogManager.java +++ b/Core/src/main/java/com/songoda/core/hooks/LogManager.java @@ -9,7 +9,6 @@ import org.bukkit.block.Block; * A convenience class for static access to a Log HookManager */ public class LogManager { - private static final HookManager manager = new HookManager(Log.class); /** @@ -47,8 +46,6 @@ public class LogManager { /** * Get the name of the log plugin being used.
* NOTE: using a default log assumes that this library is shaded - * - * @return */ public static String getName() { return manager.getName(); @@ -62,8 +59,9 @@ public class LogManager { * @param block the block that is placed */ public static void logPlacement(OfflinePlayer player, Block block) { - if (manager.isEnabled()) + if (manager.isEnabled()) { manager.getCurrentHook().logPlacement(player, block); + } } /** @@ -73,8 +71,9 @@ public class LogManager { * @param player player to commit actionremvedplaced */ public static void logRemoval(OfflinePlayer player, Block block) { - if (manager.isEnabled()) + if (manager.isEnabled()) { manager.getCurrentHook().logRemoval(player, block); + } } /** @@ -85,7 +84,8 @@ public class LogManager { * @param location the location that is interacted with */ public static void logInteraction(OfflinePlayer player, Location location) { - if (manager.isEnabled()) + if (manager.isEnabled()) { manager.getCurrentHook().logInteraction(player, location); + } } } diff --git a/Core/src/main/java/com/songoda/core/hooks/McMMOHook.java b/Core/src/main/java/com/songoda/core/hooks/McMMOHook.java index 558d3b39..c8a6f371 100644 --- a/Core/src/main/java/com/songoda/core/hooks/McMMOHook.java +++ b/Core/src/main/java/com/songoda/core/hooks/McMMOHook.java @@ -8,7 +8,6 @@ import org.bukkit.entity.Player; import java.util.Collection; public class McMMOHook { - static boolean canHook = false; static { @@ -16,7 +15,7 @@ public class McMMOHook { // if this class exists, we're good to use McMMO Class.forName("com.gmail.nossr50.api.AbilityAPI"); canHook = true; - } catch (ClassNotFoundException ex) { + } catch (ClassNotFoundException ignore) { } } diff --git a/Core/src/main/java/com/songoda/core/hooks/PluginHook.java b/Core/src/main/java/com/songoda/core/hooks/PluginHook.java index 3d70a01e..4be5c554 100644 --- a/Core/src/main/java/com/songoda/core/hooks/PluginHook.java +++ b/Core/src/main/java/com/songoda/core/hooks/PluginHook.java @@ -35,7 +35,6 @@ import java.util.logging.Level; import java.util.stream.Collectors; public final class PluginHook { - public static final PluginHook ECO_VAULT = new PluginHook(Economy.class, "Vault", VaultEconomy.class); public static final PluginHook ECO_PLAYER_POINTS = new PluginHook(Economy.class, "PlayerPoints", PlayerPointsEconomy.class); public static final PluginHook ECO_RESERVE = new PluginHook(Economy.class, "Reserve", ReserveEconomy.class); @@ -65,13 +64,17 @@ public final class PluginHook { if (!Hook.class.isAssignableFrom(handler)) { throw new RuntimeException("Tried to register a non-Hook plugin hook! " + pluginName + " -> " + handler.getName()); } + this.hookGeneric = type; this.plugin = pluginName; this.managerClass = handler; + if (hooks == null) { hooks = new LinkedHashMap(); } + hooks.put(handler, this); + // Does this class have a plugin constructor? try { pluginConstructor = handler.getDeclaredConstructor(Plugin.class); @@ -89,7 +92,6 @@ public final class PluginHook { * Permissible constructors are empty () or (org.bukkit.plugin.Plugin)
* Each plugin defined must use a different handler class. * - * @param * @param type Generic hook type for this plugin * @param pluginName Plugin name * @param handler Specific class that will handle this plugin, if enabled. @@ -107,6 +109,7 @@ public final class PluginHook { for (PluginHook hook : getHooks(type)) { if (pluginManager.isPluginEnabled(hook.plugin)) { Hook handler = (Hook) (plugin != null ? hook.load(plugin) : hook.load()); + if (handler != null && handler.isEnabled()) { loaded.put(hook, handler); } @@ -136,6 +139,7 @@ public final class PluginHook { } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException ex) { Bukkit.getLogger().log(Level.SEVERE, "Unexpected Error while creating a new Hook Manager for " + plugin, ex); } + return null; } @@ -148,6 +152,7 @@ public final class PluginHook { } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException ex) { Bukkit.getLogger().log(Level.SEVERE, "Unexpected Error while creating a new Hook Manager for " + plugin, ex); } + return null; } @@ -156,6 +161,7 @@ public final class PluginHook { int hash = 3; hash = 37 * hash + Objects.hashCode(this.plugin); hash = 37 * hash + Objects.hashCode(this.managerClass); + return hash; } @@ -164,8 +170,8 @@ public final class PluginHook { if (obj == null || getClass() != obj.getClass()) { return false; } + final PluginHook other = (PluginHook) obj; - return Objects.equals(this.plugin, other.plugin) - && Objects.equals(this.managerClass, other.managerClass); + return Objects.equals(this.plugin, other.plugin) && Objects.equals(this.managerClass, other.managerClass); } } diff --git a/Core/src/main/java/com/songoda/core/hooks/ProtectionManager.java b/Core/src/main/java/com/songoda/core/hooks/ProtectionManager.java index 65cff0c1..397cf238 100644 --- a/Core/src/main/java/com/songoda/core/hooks/ProtectionManager.java +++ b/Core/src/main/java/com/songoda/core/hooks/ProtectionManager.java @@ -6,7 +6,6 @@ import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; public class ProtectionManager { - private static final HookManager manager = new HookManager(Protection.class); /** diff --git a/Core/src/main/java/com/songoda/core/hooks/WorldGuardHook.java b/Core/src/main/java/com/songoda/core/hooks/WorldGuardHook.java index 130c6d48..01a2b910 100644 --- a/Core/src/main/java/com/songoda/core/hooks/WorldGuardHook.java +++ b/Core/src/main/java/com/songoda/core/hooks/WorldGuardHook.java @@ -13,7 +13,6 @@ import java.util.List; import java.util.Objects; public class WorldGuardHook { - static boolean canHook = false; static { @@ -21,7 +20,7 @@ public class WorldGuardHook { // if this class exists, we're good to use WG classes Class.forName("com.sk89q.worldguard.protection.flags.Flag"); canHook = true; - } catch (ClassNotFoundException ex) { + } catch (ClassNotFoundException ignore) { } } diff --git a/Core/src/main/java/com/songoda/core/hooks/economies/Economy.java b/Core/src/main/java/com/songoda/core/hooks/economies/Economy.java index 98b7f405..448a6db4 100644 --- a/Core/src/main/java/com/songoda/core/hooks/economies/Economy.java +++ b/Core/src/main/java/com/songoda/core/hooks/economies/Economy.java @@ -4,7 +4,6 @@ import com.songoda.core.hooks.Hook; import org.bukkit.OfflinePlayer; public abstract class Economy implements Hook { - /** * Get the players available balance * diff --git a/Core/src/main/java/com/songoda/core/hooks/economies/PlayerPointsEconomy.java b/Core/src/main/java/com/songoda/core/hooks/economies/PlayerPointsEconomy.java index 71947150..3530f9f2 100644 --- a/Core/src/main/java/com/songoda/core/hooks/economies/PlayerPointsEconomy.java +++ b/Core/src/main/java/com/songoda/core/hooks/economies/PlayerPointsEconomy.java @@ -5,7 +5,6 @@ import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; public class PlayerPointsEconomy extends Economy { - private final PlayerPoints playerPoints; public PlayerPointsEconomy() { @@ -34,18 +33,21 @@ public class PlayerPointsEconomy extends Economy { @Override public boolean hasBalance(OfflinePlayer player, double cost) { int amount = convertAmount(cost); + return playerPoints.getAPI().look(player.getUniqueId()) >= amount; } @Override public boolean withdrawBalance(OfflinePlayer player, double cost) { int amount = convertAmount(cost); + return playerPoints.getAPI().take(player.getUniqueId(), amount); } @Override public boolean deposit(OfflinePlayer player, double amount) { int amt = convertAmount(amount); + return playerPoints.getAPI().give(player.getUniqueId(), amt); } } diff --git a/Core/src/main/java/com/songoda/core/hooks/economies/ReserveEconomy.java b/Core/src/main/java/com/songoda/core/hooks/economies/ReserveEconomy.java index 754ed78d..f46a9035 100644 --- a/Core/src/main/java/com/songoda/core/hooks/economies/ReserveEconomy.java +++ b/Core/src/main/java/com/songoda/core/hooks/economies/ReserveEconomy.java @@ -7,12 +7,12 @@ import org.bukkit.OfflinePlayer; import java.math.BigDecimal; public class ReserveEconomy extends Economy { - EconomyAPI economyAPI; public ReserveEconomy() { - if (Reserve.instance().economyProvided()) + if (Reserve.instance().economyProvided()) { economyAPI = Reserve.instance().economy(); + } } @Override diff --git a/Core/src/main/java/com/songoda/core/hooks/economies/VaultEconomy.java b/Core/src/main/java/com/songoda/core/hooks/economies/VaultEconomy.java index 0a3acda0..4c8dc685 100644 --- a/Core/src/main/java/com/songoda/core/hooks/economies/VaultEconomy.java +++ b/Core/src/main/java/com/songoda/core/hooks/economies/VaultEconomy.java @@ -5,12 +5,12 @@ import org.bukkit.OfflinePlayer; import org.bukkit.plugin.RegisteredServiceProvider; public class VaultEconomy extends Economy { - private final net.milkbowl.vault.economy.Economy vault; public VaultEconomy() { // this returns null if we have Vault with no compatible eco plugin RegisteredServiceProvider v = Bukkit.getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); + if (v != null) { this.vault = v.getProvider(); } else { @@ -31,8 +31,10 @@ public class VaultEconomy extends Economy { @Override public double getBalance(OfflinePlayer player) { - if (vault == null) + if (vault == null) { return 0; + } + return vault.getBalance(player); } diff --git a/Core/src/main/java/com/songoda/core/hooks/holograms/CMIHolograms.java b/Core/src/main/java/com/songoda/core/hooks/holograms/CMIHolograms.java index b61bc644..3c98768d 100644 --- a/Core/src/main/java/com/songoda/core/hooks/holograms/CMIHolograms.java +++ b/Core/src/main/java/com/songoda/core/hooks/holograms/CMIHolograms.java @@ -17,7 +17,6 @@ import java.util.logging.Level; import java.util.logging.Logger; public class CMIHolograms extends Holograms { - private static CMI cmi; private static HologramManager cmiHologramManager; private static HashSet ourHolograms = new HashSet<>(); @@ -28,14 +27,16 @@ public class CMIHolograms extends Holograms { try { useOldMethod = CMIHologram.class.getDeclaredField("lines").getDeclaringClass() == String[].class; cmi_CMIHologram_getLines = CMIHologram.class.getMethod("getLines"); - } catch (NoSuchFieldException | NoSuchMethodException e) { - e.printStackTrace(); + } catch (NoSuchFieldException | NoSuchMethodException ex) { + ex.printStackTrace(); } } public CMIHolograms(Plugin plugin) { super(plugin); + cmi = (CMI) Bukkit.getPluginManager().getPlugin("CMI"); + if (cmi != null) { cmiHologramManager = cmi.getHologramManager(); } @@ -64,11 +65,14 @@ public class CMIHolograms extends Holograms { @Override public void removeHologram(Location location) { location = fixLocation(location); + final String id = locStr(location); CMIHologram holo = cmiHologramManager.getByName(id); + if (holo != null) { cmiHologramManager.removeHolo(holo); } + ourHolograms.remove(id); } @@ -76,10 +80,12 @@ public class CMIHolograms extends Holograms { public void removeAllHolograms() { for (String id : ourHolograms) { CMIHologram holo = cmiHologramManager.getByName(id); + if (holo != null) { cmiHologramManager.removeHolo(holo); } } + ourHolograms.clear(); } @@ -87,6 +93,7 @@ public class CMIHolograms extends Holograms { public void updateHologram(Location location, List lines) { location = fixLocation(location); CMIHologram holo = cmiHologramManager.getByName(locStr(location)); + if (holo != null) { // only update if there is a change to the text List holoLines; @@ -100,6 +107,7 @@ public class CMIHolograms extends Holograms { Logger.getLogger(CMIHolograms.class.getName()).log(Level.SEVERE, "CMI Hologram error!", ex); holoLines = Collections.emptyList(); } + boolean isChanged = lines.size() != holoLines.size(); if (!isChanged) { // double-check the lines @@ -107,12 +115,15 @@ public class CMIHolograms extends Holograms { isChanged = !holo.getLine(i).equals(lines.get(i)); } } + if (isChanged) { holo.setLines(lines); holo.update(); } + return; } + createAt(location, lines); } @@ -129,6 +140,7 @@ public class CMIHolograms extends Holograms { private void createAt(Location location, List lines) { final String id = locStr(location); + CMIHologram holo = new CMIHologram(id, location); holo.setLines(lines); diff --git a/Core/src/main/java/com/songoda/core/hooks/holograms/Holograms.java b/Core/src/main/java/com/songoda/core/hooks/holograms/Holograms.java index f4daa74d..105cefd0 100644 --- a/Core/src/main/java/com/songoda/core/hooks/holograms/Holograms.java +++ b/Core/src/main/java/com/songoda/core/hooks/holograms/Holograms.java @@ -9,7 +9,6 @@ import java.util.List; import java.util.Map; public abstract class Holograms implements Hook { - protected double xOffset = 0.5; protected double yOffset = 0.5; protected double zOffset = 0.5; @@ -24,6 +23,7 @@ public abstract class Holograms implements Hook { this.xOffset = x; this.yOffset = y; this.zOffset = z; + return this; } @@ -38,6 +38,7 @@ public abstract class Holograms implements Hook { double x = location.getX(); double y = location.getY(); double z = location.getZ(); + return location.clone().add((x - (int) x) + xOffset, (y - (int) y) + yOffset + defaultHeightOffset(), (z - (int) z) + zOffset); } diff --git a/Core/src/main/java/com/songoda/core/hooks/holograms/HologramsHolograms.java b/Core/src/main/java/com/songoda/core/hooks/holograms/HologramsHolograms.java index 8c5817a4..76ec8fc4 100644 --- a/Core/src/main/java/com/songoda/core/hooks/holograms/HologramsHolograms.java +++ b/Core/src/main/java/com/songoda/core/hooks/holograms/HologramsHolograms.java @@ -13,12 +13,12 @@ import java.util.List; import java.util.Map; public class HologramsHolograms extends Holograms { - HologramPlugin hologramPlugin; HashSet ourHolograms = new HashSet<>(); public HologramsHolograms(Plugin plugin) { super(plugin); + hologramPlugin = (HologramPlugin) Bukkit.getPluginManager().getPlugin("Holograms"); } @@ -45,12 +45,15 @@ public class HologramsHolograms extends Holograms { @Override public void removeHologram(Location location) { location = fixLocation(location); + final String id = locStr(location); Hologram hologram = hologramPlugin.getHologramManager().getHologram(id); + if (hologram != null) { hologram.despawn(); hologramPlugin.getHologramManager().removeActiveHologram(hologram); } + ourHolograms.remove(id); } @@ -58,11 +61,13 @@ public class HologramsHolograms extends Holograms { public void removeAllHolograms() { for (String id : ourHolograms) { Hologram hologram = hologramPlugin.getHologramManager().getHologram(id); + if (hologram != null) { hologram.despawn(); hologramPlugin.getHologramManager().removeActiveHologram(hologram); } } + ourHolograms.clear(); } @@ -112,14 +117,17 @@ public class HologramsHolograms extends Holograms { private void createAt(Location location, List lines) { final String id = locStr(location); + Hologram hologram = new Hologram(id, location); + for (String line : lines) { hologram.addLine(new TextLine(hologram, line)); } hologramPlugin.getHologramManager().addActiveHologram(hologram); - if (!ourHolograms.contains(id)) + if (!ourHolograms.contains(id)) { ourHolograms.add(id); + } } } diff --git a/Core/src/main/java/com/songoda/core/hooks/holograms/HolographicDisplaysHolograms.java b/Core/src/main/java/com/songoda/core/hooks/holograms/HolographicDisplaysHolograms.java index 0e6a601a..9bf7c34d 100644 --- a/Core/src/main/java/com/songoda/core/hooks/holograms/HolographicDisplaysHolograms.java +++ b/Core/src/main/java/com/songoda/core/hooks/holograms/HolographicDisplaysHolograms.java @@ -11,7 +11,6 @@ import java.util.List; import java.util.Map; public class HolographicDisplaysHolograms extends Holograms { - public HolographicDisplaysHolograms(Plugin plugin) { super(plugin); } @@ -39,10 +38,14 @@ public class HolographicDisplaysHolograms extends Holograms { @Override public void removeHologram(Location location) { location = fixLocation(location); + for (Hologram hologram : HologramsAPI.getHolograms(plugin)) { if (hologram.getX() != location.getX() || hologram.getY() != location.getY() - || hologram.getZ() != location.getZ()) continue; + || hologram.getZ() != location.getZ()) { + continue; + } + hologram.delete(); } } @@ -63,7 +66,9 @@ public class HolographicDisplaysHolograms extends Holograms { for (Hologram hologram : holograms) { if (hologram.getX() != location.getX() || hologram.getY() != location.getY() - || hologram.getZ() != location.getZ()) continue; + || hologram.getZ() != location.getZ()) { + continue; + } // only update if there is a change to the text boolean isChanged = lines.size() != hologram.size(); @@ -92,6 +97,7 @@ public class HolographicDisplaysHolograms extends Holograms { private void createAt(Location location, List lines) { Hologram hologram = HologramsAPI.createHologram(plugin, location); + for (String line : lines) { hologram.appendTextLine(line); } diff --git a/Core/src/main/java/com/songoda/core/hooks/jobs/JobsHandler.java b/Core/src/main/java/com/songoda/core/hooks/jobs/JobsHandler.java index ab443ce7..fd9802dc 100644 --- a/Core/src/main/java/com/songoda/core/hooks/jobs/JobsHandler.java +++ b/Core/src/main/java/com/songoda/core/hooks/jobs/JobsHandler.java @@ -1,13 +1,12 @@ -package com.songoda.core.hooks.jobs; - -import com.gamingmesh.jobs.Jobs; - -import java.util.List; -import java.util.stream.Collectors; - -public class JobsHandler { - - public static List getJobs() { - return Jobs.getJobs().stream().map(j -> j.getName()).collect(Collectors.toList()); - } -} +package com.songoda.core.hooks.jobs; + +import com.gamingmesh.jobs.Jobs; + +import java.util.List; +import java.util.stream.Collectors; + +public class JobsHandler { + public static List getJobs() { + return Jobs.getJobs().stream().map(j -> j.getName()).collect(Collectors.toList()); + } +} diff --git a/Core/src/main/java/com/songoda/core/hooks/jobs/JobsPlayerHandler.java b/Core/src/main/java/com/songoda/core/hooks/jobs/JobsPlayerHandler.java index a2e7a15e..5e928045 100644 --- a/Core/src/main/java/com/songoda/core/hooks/jobs/JobsPlayerHandler.java +++ b/Core/src/main/java/com/songoda/core/hooks/jobs/JobsPlayerHandler.java @@ -1,183 +1,195 @@ -package com.songoda.core.hooks.jobs; - -import com.gamingmesh.jobs.CMILib.CMIEnchantment; -import com.gamingmesh.jobs.Jobs; -import com.gamingmesh.jobs.actions.BlockActionInfo; -import com.gamingmesh.jobs.actions.CustomKillInfo; -import com.gamingmesh.jobs.actions.EnchantActionInfo; -import com.gamingmesh.jobs.actions.EntityActionInfo; -import com.gamingmesh.jobs.actions.ItemActionInfo; -import com.gamingmesh.jobs.container.ActionType; -import com.gamingmesh.jobs.container.CurrencyType; -import com.gamingmesh.jobs.container.Job; -import com.gamingmesh.jobs.container.JobProgression; -import com.gamingmesh.jobs.container.JobsPlayer; -import org.bukkit.block.Block; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.Entity; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -public class JobsPlayerHandler { - - protected final JobsPlayer jPlayer; - - protected JobsPlayerHandler(JobsPlayer jPlayer) { - this.jPlayer = jPlayer; - } - - public static JobsPlayerHandler loadPlayer(Player player) { - JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); - return jPlayer != null ? new JobsPlayerHandler(jPlayer) : null; - } - - public double getBoostExp(String job) { - return jPlayer.getBoost(job, CurrencyType.EXP); - } - - public double getBoostMoney(String job) { - return jPlayer.getBoost(job, CurrencyType.MONEY); - } - - public double getBoostPoints(String job) { - return jPlayer.getBoost(job, CurrencyType.POINTS); - } - - public void promoteJob(String jobName) { - Job job = Jobs.getJob(jobName); - if (job != null) { - jPlayer.promoteJob(job, 1); - } - } - - public void promoteJob(String jobName, int levels) { - Job job = Jobs.getJob(jobName); - if (job != null) { - jPlayer.promoteJob(job, levels); - } - } - - public void demoteJob(String jobName) { - Job job = Jobs.getJob(jobName); - if (job != null) { - jPlayer.demoteJob(job, 1); - } - } - - public void demoteJob(String jobName, int levels) { - Job job = Jobs.getJob(jobName); - if (job != null) { - jPlayer.demoteJob(job, levels); - } - } - - public void joinJob(String jobName) { - Job job = Jobs.getJob(jobName); - if (job != null) { - jPlayer.joinJob(job); - } - } - - public void leaveAllJobs() { - jPlayer.leaveAllJobs(); - } - - public void leaveJob(String jobName) { - Job job = Jobs.getJob(jobName); - if (job != null) { - jPlayer.leaveJob(job); - } - } - - public int getTotalLevels() { - return jPlayer.getTotalLevels(); - } - - public int getMaxBrewingStandsAllowed() { - return jPlayer.getMaxBrewingStandsAllowed(); - } - - public int getMaxFurnacesAllowed() { - return jPlayer.getMaxFurnacesAllowed(); - } - - public List getJobs() { - return jPlayer.getJobProgression().stream().map(p -> p.getJob().getName()).collect(Collectors.toList()); - } - - public void eatItem(ItemStack item) { - Jobs.action(jPlayer, new ItemActionInfo(item, ActionType.EAT)); - } - - public void breakBlock(Block block) { - Jobs.action(jPlayer, new BlockActionInfo(block, ActionType.BREAK), block); - } - - public void tntBreakBlock(Block block) { - Jobs.action(jPlayer, new BlockActionInfo(block, ActionType.TNTBREAK), block); - } - - public void placeBlock(Block block) { - Jobs.action(jPlayer, new BlockActionInfo(block, ActionType.PLACE), block); - } - - public void placeEntity(Entity block) { - Jobs.action(jPlayer, new EntityActionInfo(block, ActionType.PLACE)); - } - - public void breakEntity(Entity block) { - Jobs.action(jPlayer, new EntityActionInfo(block, ActionType.BREAK)); - } - - public void breedEntity(LivingEntity entity) { - Jobs.action(jPlayer, new EntityActionInfo(entity, ActionType.BREED)); - } - - public void killEntity(LivingEntity entity) { - killEntity(entity, jPlayer.getPlayer()); - } - - public void tameEntity(LivingEntity entity) { - Jobs.action(jPlayer, new EntityActionInfo((Entity) entity, ActionType.TAME)); - } - - public void catchFish(ItemStack items) { - Jobs.action(jPlayer, new ItemActionInfo(items, ActionType.FISH)); - } - - public void killEntity(LivingEntity entity, Entity damageSource) { - Jobs.action(jPlayer, new EntityActionInfo(entity, ActionType.KILL), damageSource, entity); - if (entity instanceof Player && !entity.hasMetadata("NPC")) { - JobsPlayer jVictim = Jobs.getPlayerManager().getJobsPlayer((Player) entity); - if (jVictim == null) { - return; - } - List jobs = jVictim.getJobProgression(); - if (jobs == null) { - return; - } - for (JobProgression job : jobs) { - Jobs.action(jPlayer, new CustomKillInfo(job.getJob().getName(), ActionType.CUSTOMKILL), damageSource, entity); - } - } - } - - public void itemEnchanted(ItemStack resultStack) { - Map enchants = resultStack.getEnchantments(); - for (Map.Entry oneEnchant : enchants.entrySet()) { - CMIEnchantment e; - String enchantName; - Integer level2; - Enchantment enchant = oneEnchant.getKey(); - if (enchant == null || (enchantName = (e = CMIEnchantment.get(enchant)) == null ? null : e.toString()) == null || (level2 = oneEnchant.getValue()) == null) { - continue; - } - Jobs.action(jPlayer, new EnchantActionInfo(enchantName, level2, ActionType.ENCHANT)); - } - } -} +package com.songoda.core.hooks.jobs; + +import com.gamingmesh.jobs.CMILib.CMIEnchantment; +import com.gamingmesh.jobs.Jobs; +import com.gamingmesh.jobs.actions.BlockActionInfo; +import com.gamingmesh.jobs.actions.CustomKillInfo; +import com.gamingmesh.jobs.actions.EnchantActionInfo; +import com.gamingmesh.jobs.actions.EntityActionInfo; +import com.gamingmesh.jobs.actions.ItemActionInfo; +import com.gamingmesh.jobs.container.ActionType; +import com.gamingmesh.jobs.container.CurrencyType; +import com.gamingmesh.jobs.container.Job; +import com.gamingmesh.jobs.container.JobProgression; +import com.gamingmesh.jobs.container.JobsPlayer; +import org.bukkit.block.Block; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class JobsPlayerHandler { + protected final JobsPlayer jPlayer; + + protected JobsPlayerHandler(JobsPlayer jPlayer) { + this.jPlayer = jPlayer; + } + + public static JobsPlayerHandler loadPlayer(Player player) { + JobsPlayer jPlayer = Jobs.getPlayerManager().getJobsPlayer(player); + + return jPlayer != null ? new JobsPlayerHandler(jPlayer) : null; + } + + public double getBoostExp(String job) { + return jPlayer.getBoost(job, CurrencyType.EXP); + } + + public double getBoostMoney(String job) { + return jPlayer.getBoost(job, CurrencyType.MONEY); + } + + public double getBoostPoints(String job) { + return jPlayer.getBoost(job, CurrencyType.POINTS); + } + + public void promoteJob(String jobName) { + Job job = Jobs.getJob(jobName); + + if (job != null) { + jPlayer.promoteJob(job, 1); + } + } + + public void promoteJob(String jobName, int levels) { + Job job = Jobs.getJob(jobName); + + if (job != null) { + jPlayer.promoteJob(job, levels); + } + } + + public void demoteJob(String jobName) { + Job job = Jobs.getJob(jobName); + + if (job != null) { + jPlayer.demoteJob(job, 1); + } + } + + public void demoteJob(String jobName, int levels) { + Job job = Jobs.getJob(jobName); + + if (job != null) { + jPlayer.demoteJob(job, levels); + } + } + + public void joinJob(String jobName) { + Job job = Jobs.getJob(jobName); + + if (job != null) { + jPlayer.joinJob(job); + } + } + + public void leaveAllJobs() { + jPlayer.leaveAllJobs(); + } + + public void leaveJob(String jobName) { + Job job = Jobs.getJob(jobName); + + if (job != null) { + jPlayer.leaveJob(job); + } + } + + public int getTotalLevels() { + return jPlayer.getTotalLevels(); + } + + public int getMaxBrewingStandsAllowed() { + return jPlayer.getMaxBrewingStandsAllowed(); + } + + public int getMaxFurnacesAllowed() { + return jPlayer.getMaxFurnacesAllowed(); + } + + public List getJobs() { + return jPlayer.getJobProgression().stream().map(p -> p.getJob().getName()).collect(Collectors.toList()); + } + + public void eatItem(ItemStack item) { + Jobs.action(jPlayer, new ItemActionInfo(item, ActionType.EAT)); + } + + public void breakBlock(Block block) { + Jobs.action(jPlayer, new BlockActionInfo(block, ActionType.BREAK), block); + } + + public void tntBreakBlock(Block block) { + Jobs.action(jPlayer, new BlockActionInfo(block, ActionType.TNTBREAK), block); + } + + public void placeBlock(Block block) { + Jobs.action(jPlayer, new BlockActionInfo(block, ActionType.PLACE), block); + } + + public void placeEntity(Entity block) { + Jobs.action(jPlayer, new EntityActionInfo(block, ActionType.PLACE)); + } + + public void breakEntity(Entity block) { + Jobs.action(jPlayer, new EntityActionInfo(block, ActionType.BREAK)); + } + + public void breedEntity(LivingEntity entity) { + Jobs.action(jPlayer, new EntityActionInfo(entity, ActionType.BREED)); + } + + public void killEntity(LivingEntity entity) { + killEntity(entity, jPlayer.getPlayer()); + } + + public void tameEntity(LivingEntity entity) { + Jobs.action(jPlayer, new EntityActionInfo((Entity) entity, ActionType.TAME)); + } + + public void catchFish(ItemStack items) { + Jobs.action(jPlayer, new ItemActionInfo(items, ActionType.FISH)); + } + + public void killEntity(LivingEntity entity, Entity damageSource) { + Jobs.action(jPlayer, new EntityActionInfo(entity, ActionType.KILL), damageSource, entity); + if (entity instanceof Player && !entity.hasMetadata("NPC")) { + JobsPlayer jVictim = Jobs.getPlayerManager().getJobsPlayer((Player) entity); + + if (jVictim == null) { + return; + } + + List jobs = jVictim.getJobProgression(); + if (jobs == null) { + return; + } + + for (JobProgression job : jobs) { + Jobs.action(jPlayer, new CustomKillInfo(job.getJob().getName(), ActionType.CUSTOMKILL), damageSource, entity); + } + } + } + + public void itemEnchanted(ItemStack resultStack) { + Map enchants = resultStack.getEnchantments(); + + for (Map.Entry oneEnchant : enchants.entrySet()) { + CMIEnchantment e; + String enchantName; + Integer level2; + Enchantment enchant = oneEnchant.getKey(); + + if (enchant == null || (enchantName = (e = CMIEnchantment.get(enchant)) == null ? null : e.toString()) == null || (level2 = oneEnchant.getValue()) == null) { + continue; + } + + Jobs.action(jPlayer, new EnchantActionInfo(enchantName, level2, ActionType.ENCHANT)); + } + } +} diff --git a/Core/src/main/java/com/songoda/core/hooks/log/CoreProtectLog.java b/Core/src/main/java/com/songoda/core/hooks/log/CoreProtectLog.java index 60e843fb..e6e31756 100644 --- a/Core/src/main/java/com/songoda/core/hooks/log/CoreProtectLog.java +++ b/Core/src/main/java/com/songoda/core/hooks/log/CoreProtectLog.java @@ -8,7 +8,6 @@ import org.bukkit.OfflinePlayer; import org.bukkit.block.Block; public class CoreProtectLog extends Log { - private CoreProtectAPI api; private boolean useDeprecatedMethod = ServerVersion.isServerVersionAtOrBelow(ServerVersion.V1_12); @@ -30,18 +29,20 @@ public class CoreProtectLog extends Log { public void logPlacement(OfflinePlayer player, Block block) { if (this.useDeprecatedMethod) { this.api.logPlacement(player.getName(), block.getLocation(), block.getType(), block.getData()); - } else { - this.api.logPlacement(player.getName(), block.getLocation(), block.getType(), block.getBlockData()); + return; } + + this.api.logPlacement(player.getName(), block.getLocation(), block.getType(), block.getBlockData()); } @Override public void logRemoval(OfflinePlayer player, Block block) { if (this.useDeprecatedMethod) { this.api.logRemoval(player.getName(), block.getLocation(), block.getType(), block.getData()); - } else { - this.api.logRemoval(player.getName(), block.getLocation(), block.getType(), block.getBlockData()); + return; } + + this.api.logRemoval(player.getName(), block.getLocation(), block.getType(), block.getBlockData()); } @Override diff --git a/Core/src/main/java/com/songoda/core/hooks/log/Log.java b/Core/src/main/java/com/songoda/core/hooks/log/Log.java index ec85ebd5..3f41a6d0 100644 --- a/Core/src/main/java/com/songoda/core/hooks/log/Log.java +++ b/Core/src/main/java/com/songoda/core/hooks/log/Log.java @@ -6,7 +6,6 @@ import org.bukkit.OfflinePlayer; import org.bukkit.block.Block; public abstract class Log implements Hook { - public abstract void logPlacement(OfflinePlayer player, Block block); public abstract void logRemoval(OfflinePlayer player, Block block); diff --git a/Core/src/main/java/com/songoda/core/hooks/mcmmo/McMMOHandler.java b/Core/src/main/java/com/songoda/core/hooks/mcmmo/McMMOHandler.java index 33d37248..51b716c4 100644 --- a/Core/src/main/java/com/songoda/core/hooks/mcmmo/McMMOHandler.java +++ b/Core/src/main/java/com/songoda/core/hooks/mcmmo/McMMOHandler.java @@ -26,7 +26,6 @@ import java.util.logging.Logger; import java.util.stream.Collectors; public class McMMOHandler { - static boolean mcmmo_v2 = false; static boolean legacy_v13 = false; static boolean legacy_v12 = false; @@ -62,6 +61,7 @@ public class McMMOHandler { mcmmo_SecondaryAbility_valueOf = mcmmo_SecondaryAbility.getDeclaredMethod("valueOf", String.class); mcmmo_Permissions_secondaryAbilityEnabled = com.gmail.nossr50.util.Permissions.class.getDeclaredMethod("secondaryAbilityEnabled", Player.class, mcmmo_SecondaryAbility); mcmmo_SkillUtils_activationSuccessful = com.gmail.nossr50.util.skills.SkillUtils.class.getDeclaredMethod("activationSuccessful", mcmmo_SecondaryAbility, Player.class, int.class, int.class); + if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_13)) { mcmmo_ExperienceConfig_getXp = mcmmo_ExperienceConfig_instance.getClass().getDeclaredMethod("getXp", mcmmo_SkillType, org.bukkit.block.data.BlockData.class); legacy_v13 = true; @@ -72,8 +72,8 @@ public class McMMOHandler { mcmmo_ExperienceConfig_getXp = mcmmo_ExperienceConfig_instance.getClass().getDeclaredMethod("getXp", mcmmo_SkillType, org.bukkit.Material.class); legacy_v8 = true; } - } catch (Exception ex1) { - Logger.getLogger(McMMOHandler.class.getName()).log(Level.SEVERE, "Failed to register McMMO Legacy Hook", ex1); + } catch (Exception ex2) { + Logger.getLogger(McMMOHandler.class.getName()).log(Level.SEVERE, "Failed to register McMMO Legacy Hook", ex2); } } } @@ -81,10 +81,13 @@ public class McMMOHandler { public static void addMining(Player player, Collection blocks) { if (player == null || blocks == null || blocks.isEmpty()) { return; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { addBlockSkillLegacy(player, blocks, "mining"); return; } + ArrayList blockStates = blocks.stream().map(b -> b.getState()).collect(Collectors.toCollection(ArrayList::new)); ExperienceAPI.addXpFromBlocksBySkill(blockStates, UserManager.getPlayer(player), PrimarySkillType.MINING); } @@ -92,10 +95,13 @@ public class McMMOHandler { public static void addExcavation(Player player, Collection blocks) { if (player == null || blocks == null || blocks.isEmpty()) { return; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { addBlockSkillLegacy(player, blocks, "excavation"); return; } + ArrayList blockStates = blocks.stream().map(b -> b.getState()).collect(Collectors.toCollection(ArrayList::new)); ExperienceAPI.addXpFromBlocksBySkill(blockStates, UserManager.getPlayer(player), PrimarySkillType.EXCAVATION); } @@ -103,10 +109,13 @@ public class McMMOHandler { public static void addHerbalism(Player player, Collection blocks) { if (player == null || blocks == null || blocks.isEmpty()) { return; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { addBlockSkillLegacy(player, blocks, "herbalism"); return; } + ArrayList blockStates = blocks.stream().map(b -> b.getState()).collect(Collectors.toCollection(ArrayList::new)); ExperienceAPI.addXpFromBlocksBySkill(blockStates, UserManager.getPlayer(player), PrimarySkillType.HERBALISM); } @@ -114,10 +123,13 @@ public class McMMOHandler { public static void addWoodcutting(Player player, Collection blocks) { if (player == null || blocks == null || blocks.isEmpty()) { return; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { addBlockSkillLegacy(player, blocks, "woodcutting"); return; } + ArrayList blockStates = blocks.stream().map(b -> b.getState()).collect(Collectors.toCollection(ArrayList::new)); ExperienceAPI.addXpFromBlocksBySkill(blockStates, UserManager.getPlayer(player), PrimarySkillType.WOODCUTTING); } @@ -125,252 +137,336 @@ public class McMMOHandler { public static int getAcrobaticsSkill(Player player) { if (player == null) { return -1; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { return getSkillLegacy(player, "acrobatics"); } + return UserManager.getPlayer(player).getSkillLevel(PrimarySkillType.ACROBATICS); } public static int getAlchemySkill(Player player) { if (player == null) { return -1; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { return getSkillLegacy(player, "alchemy"); } + return UserManager.getPlayer(player).getSkillLevel(PrimarySkillType.ALCHEMY); } public static int getArcherySkill(Player player) { if (player == null) { return -1; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { return getSkillLegacy(player, "archery"); } + return UserManager.getPlayer(player).getSkillLevel(PrimarySkillType.ARCHERY); } public static int getAxesSkill(Player player) { if (player == null) { return -1; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { return getSkillLegacy(player, "axes"); } + return UserManager.getPlayer(player).getSkillLevel(PrimarySkillType.AXES); } public static int getExcavationSkill(Player player) { if (player == null) { return -1; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { return getSkillLegacy(player, "excavation"); } + return UserManager.getPlayer(player).getSkillLevel(PrimarySkillType.EXCAVATION); } public static int getFishingSkill(Player player) { if (player == null) { return -1; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { return getSkillLegacy(player, "fishing"); } + return UserManager.getPlayer(player).getSkillLevel(PrimarySkillType.FISHING); } public static int getHerbalismSkill(Player player) { if (player == null) { return -1; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { return getSkillLegacy(player, "herbalism"); } + return UserManager.getPlayer(player).getSkillLevel(PrimarySkillType.HERBALISM); } public static int getMiningSkill(Player player) { if (player == null) { return -1; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { return getSkillLegacy(player, "mining"); } + return UserManager.getPlayer(player).getSkillLevel(PrimarySkillType.MINING); } public static int getRepairSkill(Player player) { if (player == null) { return -1; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { return getSkillLegacy(player, "repair"); } + return UserManager.getPlayer(player).getSkillLevel(PrimarySkillType.REPAIR); } public static int getSmeltingSkill(Player player) { if (player == null) { return -1; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { return getSkillLegacy(player, "smelting"); } + return UserManager.getPlayer(player).getSkillLevel(PrimarySkillType.SMELTING); } public static int getSwordsSkill(Player player) { if (player == null) { return -1; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { return getSkillLegacy(player, "swords"); } + return UserManager.getPlayer(player).getSkillLevel(PrimarySkillType.SWORDS); } public static int getTamingSkill(Player player) { if (player == null) { return -1; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { return getSkillLegacy(player, "taming"); } + return UserManager.getPlayer(player).getSkillLevel(PrimarySkillType.TAMING); } public static int getUnarmedSkill(Player player) { if (player == null) { return -1; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { return getSkillLegacy(player, "unarmed"); } + return UserManager.getPlayer(player).getSkillLevel(PrimarySkillType.UNARMED); } public static int getWoodcuttingSkill(Player player) { if (player == null) { return -1; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { return getSkillLegacy(player, "woodcutting"); } + return UserManager.getPlayer(player).getSkillLevel(PrimarySkillType.WOODCUTTING); } public static void addAcrobatics(Player player, int xp) { if (player == null) { return; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { ExperienceAPI.addXP(player, "acrobatics", xp); } + UserManager.getPlayer(player).beginXpGain(PrimarySkillType.ACROBATICS, xp, XPGainReason.UNKNOWN, XPGainSource.CUSTOM); } public static void addAlchemy(Player player, int xp) { if (player == null) { return; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { ExperienceAPI.addXP(player, "alchemy", xp); } + UserManager.getPlayer(player).beginXpGain(PrimarySkillType.ALCHEMY, xp, XPGainReason.UNKNOWN, XPGainSource.CUSTOM); } public static void addArchery(Player player, int xp) { if (player == null) { return; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { ExperienceAPI.addXP(player, "archery", xp); } + UserManager.getPlayer(player).beginXpGain(PrimarySkillType.ARCHERY, xp, XPGainReason.UNKNOWN, XPGainSource.CUSTOM); } public static void addAxes(Player player, int xp) { if (player == null) { return; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { ExperienceAPI.addXP(player, "axes", xp); } + UserManager.getPlayer(player).beginXpGain(PrimarySkillType.AXES, xp, XPGainReason.UNKNOWN, XPGainSource.CUSTOM); } public static void addExcavation(Player player, int xp) { if (player == null) { return; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { ExperienceAPI.addXP(player, "excavation", xp); } + UserManager.getPlayer(player).beginXpGain(PrimarySkillType.EXCAVATION, xp, XPGainReason.UNKNOWN, XPGainSource.CUSTOM); } public static void addFishing(Player player, int xp) { if (player == null) { return; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { ExperienceAPI.addXP(player, "fishing", xp); } + UserManager.getPlayer(player).beginXpGain(PrimarySkillType.FISHING, xp, XPGainReason.UNKNOWN, XPGainSource.CUSTOM); } public static void addHerbalism(Player player, int xp) { if (player == null) { return; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { ExperienceAPI.addXP(player, "herbalism", xp); } + UserManager.getPlayer(player).beginXpGain(PrimarySkillType.HERBALISM, xp, XPGainReason.UNKNOWN, XPGainSource.CUSTOM); } public static void addMining(Player player, int xp) { if (player == null) { return; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { ExperienceAPI.addXP(player, "mining", xp); } + UserManager.getPlayer(player).beginXpGain(PrimarySkillType.MINING, xp, XPGainReason.UNKNOWN, XPGainSource.CUSTOM); } public static void addRepair(Player player, int xp) { if (player == null) { return; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { ExperienceAPI.addXP(player, "repair", xp); } + UserManager.getPlayer(player).beginXpGain(PrimarySkillType.REPAIR, xp, XPGainReason.UNKNOWN, XPGainSource.CUSTOM); } public static void addSmelting(Player player, int xp) { if (player == null) { return; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { ExperienceAPI.addXP(player, "smelting", xp); } + UserManager.getPlayer(player).beginXpGain(PrimarySkillType.SMELTING, xp, XPGainReason.UNKNOWN, XPGainSource.CUSTOM); } public static void addSwords(Player player, int xp) { if (player == null) { return; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { ExperienceAPI.addXP(player, "swords", xp); } + UserManager.getPlayer(player).beginXpGain(PrimarySkillType.SWORDS, xp, XPGainReason.UNKNOWN, XPGainSource.CUSTOM); } public static void addTaming(Player player, int xp) { if (player == null) { return; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { ExperienceAPI.addXP(player, "taming", xp); } + UserManager.getPlayer(player).beginXpGain(PrimarySkillType.TAMING, xp, XPGainReason.UNKNOWN, XPGainSource.CUSTOM); } public static void addUnarmed(Player player, int xp) { if (player == null) { return; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { ExperienceAPI.addXP(player, "unarmed", xp); } + UserManager.getPlayer(player).beginXpGain(PrimarySkillType.UNARMED, xp, XPGainReason.UNKNOWN, XPGainSource.CUSTOM); } public static void addWoodcutting(Player player, int xp) { if (player == null) { return; - } else if (legacy_v13 || legacy_v12 || legacy_v8) { + } + + if (legacy_v13 || legacy_v12 || legacy_v8) { ExperienceAPI.addXP(player, "woodcutting", xp); } + UserManager.getPlayer(player).beginXpGain(PrimarySkillType.WOODCUTTING, xp, XPGainReason.UNKNOWN, XPGainSource.CUSTOM); } @@ -455,22 +551,25 @@ public class McMMOHandler { if (player.hasMetadata("mcMMO: Player Data")) { try { Object skillType = mcmmo_SkillType_valueOf.invoke(null, skill.toUpperCase()); + if ((boolean) mcmmo_SkillType_getDoubleDropsDisabled.invoke(skillType)) { return false; } int skillLevel = (int) mcmmo_McMMOPlayer_getSkillLevel.invoke(UserManager.getPlayer(player), skillType); int activationChance = (int) mcmmo_PerksUtils_handleLuckyPerks.invoke(null, player, skillType); - Object secondaryDouble = mcmmo_SecondaryAbility_valueOf.invoke(null, skill.toUpperCase() + "_DOUBLE_DROPS"); + if (!((boolean) mcmmo_Permissions_secondaryAbilityEnabled.invoke(null, player, secondaryDouble))) { return false; } + return (boolean) mcmmo_SkillUtils_activationSuccessful.invoke(null, secondaryDouble, player, skillLevel, activationChance); - } catch (Exception ex1) { - Logger.getLogger(McMMOHandler.class.getName()).log(Level.SEVERE, "Failed to invoke McMMO Legacy Hook", ex1); + } catch (Exception ex) { + Logger.getLogger(McMMOHandler.class.getName()).log(Level.SEVERE, "Failed to invoke McMMO Legacy Hook", ex); } } + return false; } @@ -484,30 +583,34 @@ public class McMMOHandler { } ExperienceAPI.addXP(player, skill, xp); - } catch (Exception ex1) { - Logger.getLogger(McMMOHandler.class.getName()).log(Level.SEVERE, "Failed to invoke McMMO Legacy Hook", ex1); + } catch (Exception ex) { + Logger.getLogger(McMMOHandler.class.getName()).log(Level.SEVERE, "Failed to invoke McMMO Legacy Hook", ex); } } protected static Object legacy_getBlock(Block block) { if (legacy_v13) { return block.getBlockData(); - } else if (legacy_v12) { - return block.getState().getData(); - } else { - return block.getType(); } + + if (legacy_v12) { + return block.getState().getData(); + } + + return block.getType(); } protected static int getSkillLegacy(Player player, String skill) { if (player.hasMetadata("mcMMO: Player Data")) { try { Object skillType = mcmmo_SkillType_valueOf.invoke(null, skill.toUpperCase()); + return (int) mcmmo_McMMOPlayer_getSkillLevel.invoke(UserManager.getPlayer(player), skillType); - } catch (Exception ex1) { - Logger.getLogger(McMMOHandler.class.getName()).log(Level.SEVERE, "Failed to invoke McMMO Legacy Hook", ex1); + } catch (Exception ex) { + Logger.getLogger(McMMOHandler.class.getName()).log(Level.SEVERE, "Failed to invoke McMMO Legacy Hook", ex); } } + return 0; } } diff --git a/Core/src/main/java/com/songoda/core/hooks/protection/BentoBoxProtection.java b/Core/src/main/java/com/songoda/core/hooks/protection/BentoBoxProtection.java index 5428d424..c9352c07 100644 --- a/Core/src/main/java/com/songoda/core/hooks/protection/BentoBoxProtection.java +++ b/Core/src/main/java/com/songoda/core/hooks/protection/BentoBoxProtection.java @@ -13,11 +13,11 @@ import world.bentobox.bentobox.managers.IslandsManager; import java.util.Optional; public class BentoBoxProtection extends Protection { - private final IslandsManager islandsManager; public BentoBoxProtection(Plugin plugin) { super(plugin); + this.islandsManager = BentoBox.getInstance().getIslands(); } diff --git a/Core/src/main/java/com/songoda/core/hooks/protection/GriefPreventionProtection.java b/Core/src/main/java/com/songoda/core/hooks/protection/GriefPreventionProtection.java index 171061d4..69169083 100644 --- a/Core/src/main/java/com/songoda/core/hooks/protection/GriefPreventionProtection.java +++ b/Core/src/main/java/com/songoda/core/hooks/protection/GriefPreventionProtection.java @@ -8,38 +8,44 @@ import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; public class GriefPreventionProtection extends Protection { - private final DataStore dataStore; public GriefPreventionProtection(Plugin plugin) { super(plugin); + this.dataStore = GriefPrevention.instance.dataStore; } @Override public boolean canPlace(Player player, Location location) { Claim claim = getClaim(location); + if (claim == null) { return true; } + return claim.allowBuild(player, location.getBlock().getType()) == null; } @Override public boolean canBreak(Player player, Location location) { Claim claim = getClaim(location); + if (claim == null) { return true; } + return claim.allowBreak(player, location.getBlock().getType()) == null; } @Override public boolean canInteract(Player player, Location location) { Claim claim = getClaim(location); + if (claim == null) { return true; } + return claim.allowContainers(player) == null; } diff --git a/Core/src/main/java/com/songoda/core/hooks/protection/LandsProtection.java b/Core/src/main/java/com/songoda/core/hooks/protection/LandsProtection.java index 4c86c7e6..cf73e7a6 100644 --- a/Core/src/main/java/com/songoda/core/hooks/protection/LandsProtection.java +++ b/Core/src/main/java/com/songoda/core/hooks/protection/LandsProtection.java @@ -8,11 +8,11 @@ import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; public class LandsProtection extends Protection { - private final LandsIntegration landsIntegration; public LandsProtection(Plugin plugin) { super(plugin); + this.landsIntegration = new LandsIntegration(plugin); } @@ -33,6 +33,7 @@ public class LandsProtection extends Protection { private boolean hasPerms(Player player, Location location, RoleSetting roleSetting) { Area area = landsIntegration.getAreaByLoc(location); + if (area == null) { return true; } diff --git a/Core/src/main/java/com/songoda/core/hooks/protection/Protection.java b/Core/src/main/java/com/songoda/core/hooks/protection/Protection.java index 12c23126..63d4963c 100644 --- a/Core/src/main/java/com/songoda/core/hooks/protection/Protection.java +++ b/Core/src/main/java/com/songoda/core/hooks/protection/Protection.java @@ -6,7 +6,6 @@ import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; public abstract class Protection implements Hook { - protected final Plugin plugin; public Protection(Plugin plugin) { diff --git a/Core/src/main/java/com/songoda/core/hooks/protection/RedProtectProtection.java b/Core/src/main/java/com/songoda/core/hooks/protection/RedProtectProtection.java index 1e9c853f..5630f285 100644 --- a/Core/src/main/java/com/songoda/core/hooks/protection/RedProtectProtection.java +++ b/Core/src/main/java/com/songoda/core/hooks/protection/RedProtectProtection.java @@ -8,17 +8,18 @@ import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; public class RedProtectProtection extends Protection { - private final RedProtectAPI api; public RedProtectProtection(Plugin plugin) { super(plugin); + this.api = RedProtect.get().getAPI(); } @Override public boolean canPlace(Player player, Location location) { Region region = api.getRegion(location); + if (region == null) { return true; } @@ -29,6 +30,7 @@ public class RedProtectProtection extends Protection { @Override public boolean canBreak(Player player, Location location) { Region region = api.getRegion(location); + if (region == null) { return true; } @@ -39,6 +41,7 @@ public class RedProtectProtection extends Protection { @Override public boolean canInteract(Player player, Location location) { Region region = api.getRegion(location); + if (region == null) { return true; } diff --git a/Core/src/main/java/com/songoda/core/hooks/protection/ResidenceProtection.java b/Core/src/main/java/com/songoda/core/hooks/protection/ResidenceProtection.java index 3ea13f5b..cec1e3db 100644 --- a/Core/src/main/java/com/songoda/core/hooks/protection/ResidenceProtection.java +++ b/Core/src/main/java/com/songoda/core/hooks/protection/ResidenceProtection.java @@ -9,22 +9,25 @@ import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; public class ResidenceProtection extends Protection { - private final Residence instance; + public ResidenceProtection(Plugin plugin) { super(plugin); + this.instance = Residence.getInstance(); } @Override public boolean canPlace(Player player, Location location) { ResidencePlayer rPlayer = Residence.getInstance().getPlayerManager().getResidencePlayer(player); + return rPlayer.canPlaceBlock(location.getBlock(), false); } @Override public boolean canBreak(Player player, Location location) { ResidencePlayer rPlayer = Residence.getInstance().getPlayerManager().getResidencePlayer(player); + return rPlayer.canBreakBlock(location.getBlock(), false); } @@ -34,11 +37,13 @@ public class ResidenceProtection extends Protection { } private boolean hasPerms(Player player, Location location, Flags flag) { - if (instance.isDisabledWorldListener(location.getWorld())) + if (instance.isDisabledWorldListener(location.getWorld())) { return true; + } - if (instance.isResAdminOn(player)) + if (instance.isResAdminOn(player)) { return true; + } FlagPermissions perms = instance.getPermsByLocForPlayer(location, player); return perms.playerHas(player, flag, true); diff --git a/Core/src/main/java/com/songoda/core/hooks/protection/UltimateClaimsProtection.java b/Core/src/main/java/com/songoda/core/hooks/protection/UltimateClaimsProtection.java index 0921497b..08a1534c 100644 --- a/Core/src/main/java/com/songoda/core/hooks/protection/UltimateClaimsProtection.java +++ b/Core/src/main/java/com/songoda/core/hooks/protection/UltimateClaimsProtection.java @@ -8,11 +8,11 @@ import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; public class UltimateClaimsProtection extends Protection { - private final UltimateClaims instance; public UltimateClaimsProtection(Plugin plugin) { super(plugin); + instance = UltimateClaims.getInstance(); } diff --git a/Core/src/main/java/com/songoda/core/hooks/stackers/StackMob.java b/Core/src/main/java/com/songoda/core/hooks/stackers/StackMob.java index 215f3e6c..c16dcfce 100644 --- a/Core/src/main/java/com/songoda/core/hooks/stackers/StackMob.java +++ b/Core/src/main/java/com/songoda/core/hooks/stackers/StackMob.java @@ -8,7 +8,6 @@ import uk.antiperson.stackmob.api.EntityManager; import uk.antiperson.stackmob.api.StackedEntity; public class StackMob extends Stacker { - private final EntityManager plugin; public StackMob() { diff --git a/Core/src/main/java/com/songoda/core/hooks/stackers/Stacker.java b/Core/src/main/java/com/songoda/core/hooks/stackers/Stacker.java index 5ed03c4c..ec2ffaa0 100644 --- a/Core/src/main/java/com/songoda/core/hooks/stackers/Stacker.java +++ b/Core/src/main/java/com/songoda/core/hooks/stackers/Stacker.java @@ -6,7 +6,6 @@ import org.bukkit.entity.Item; import org.bukkit.entity.LivingEntity; public abstract class Stacker implements Hook { - public abstract boolean supportsItemStacking(); public abstract boolean supportsEntityStacking(); diff --git a/Core/src/main/java/com/songoda/core/hooks/stackers/UltimateStacker.java b/Core/src/main/java/com/songoda/core/hooks/stackers/UltimateStacker.java index aea6ca49..4564b740 100644 --- a/Core/src/main/java/com/songoda/core/hooks/stackers/UltimateStacker.java +++ b/Core/src/main/java/com/songoda/core/hooks/stackers/UltimateStacker.java @@ -8,7 +8,6 @@ import org.bukkit.entity.LivingEntity; import org.bukkit.plugin.Plugin; public class UltimateStacker extends Stacker { - private final com.songoda.ultimatestacker.UltimateStacker plugin; public UltimateStacker() { diff --git a/Core/src/main/java/com/songoda/core/hooks/stackers/WildStacker.java b/Core/src/main/java/com/songoda/core/hooks/stackers/WildStacker.java index 01b0fb6b..911f04e6 100644 --- a/Core/src/main/java/com/songoda/core/hooks/stackers/WildStacker.java +++ b/Core/src/main/java/com/songoda/core/hooks/stackers/WildStacker.java @@ -8,7 +8,6 @@ import org.bukkit.entity.LivingEntity; import org.bukkit.plugin.Plugin; public class WildStacker extends Stacker { - final Plugin plugin; public WildStacker(Plugin plugin) { @@ -70,9 +69,11 @@ public class WildStacker extends Stacker { @Override public int getMinStackSize(EntityType type) { int min = plugin.getConfig().getInt("entities.minimum-limits." + type.name(), -1); + if (min == -1) { min = plugin.getConfig().getInt("entities.minimum-limits.all", -1); } + return min == -1 ? 0 : min; } } diff --git a/Core/src/main/java/com/songoda/core/hooks/worldguard/WorldGuardFlagHandler.java b/Core/src/main/java/com/songoda/core/hooks/worldguard/WorldGuardFlagHandler.java index f141fd77..34f60dcd 100644 --- a/Core/src/main/java/com/songoda/core/hooks/worldguard/WorldGuardFlagHandler.java +++ b/Core/src/main/java/com/songoda/core/hooks/worldguard/WorldGuardFlagHandler.java @@ -33,7 +33,6 @@ import java.util.stream.Stream; * Note: Hooks must be added before WG loads! */ public class WorldGuardFlagHandler { - static boolean wgPlugin; static Object worldGuardPlugin; static boolean wg_v7 = false; @@ -44,7 +43,7 @@ public class WorldGuardFlagHandler { static Map flags = new HashMap(); static { - if ((wgPlugin = (worldGuardPlugin = Bukkit.getPluginManager().getPlugin("WorldGuard")) != null)) { + if (wgPlugin = (worldGuardPlugin = Bukkit.getPluginManager().getPlugin("WorldGuard")) != null) { // a number of flags were introduced in 7.x that aren't in 5 or 6 try { // if this class exists, we're on 7.x @@ -99,6 +98,7 @@ public class WorldGuardFlagHandler { } catch (Exception ex) { Bukkit.getServer().getLogger().log(Level.WARNING, "Could not add flag {0} to WorldGuard", addFlag.getName()); Object wgFlag = WorldGuard.getInstance().getFlagRegistry().get(addFlag.getName()); + if (wgFlag == null || !(wgFlag instanceof StateFlag)) { wgPlugin = false; Bukkit.getServer().getLogger().log(Level.WARNING, "Could not hook WorldGuard"); @@ -120,6 +120,7 @@ public class WorldGuardFlagHandler { Flag wgFlag = Stream.of(flagsOld) .filter(f -> ((Flag) f).getName().equalsIgnoreCase(flag)) .findFirst().orElse(null); + if (wgFlag != null) { // we already have one flags.put(flag, wgFlag); @@ -148,6 +149,7 @@ public class WorldGuardFlagHandler { legacy_simpleFlagRegistryClazz = Class.forName("com.sk89q.worldguard.protection.flags.registry.SimpleFlagRegistry"); legacy_simpleFlagRegistry_get = legacy_simpleFlagRegistryClazz.getDeclaredMethod("get", String.class); } + legacy_simpleFlagRegistryClazz.getDeclaredMethod("register", Flag.class).invoke(legacy_worldGuardPlugin_flagRegistry, wgFlag); } @@ -164,6 +166,7 @@ public class WorldGuardFlagHandler { private static Object getPrivateField(Class c, Object handle, String fieldName) throws Exception { Field field = c.getDeclaredField(fieldName); field.setAccessible(true); // This should be okay since it only runs on older versions. + return field.get(handle); } @@ -193,6 +196,7 @@ public class WorldGuardFlagHandler { legacy_simpleFlagRegistryClazz = Class.forName("com.sk89q.worldguard.protection.flags.registry.SimpleFlagRegistry"); legacy_simpleFlagRegistry_get = legacy_simpleFlagRegistryClazz.getDeclaredMethod("get", String.class); } + flags.put(flag, flagObj = legacy_simpleFlagRegistry_get.invoke(legacy_worldGuardPlugin_flagRegistry, flag)); } catch (Exception ex) { Bukkit.getServer().getLogger().log(Level.WARNING, "Could not grab flags from WorldGuard", ex); @@ -207,9 +211,11 @@ public class WorldGuardFlagHandler { } catch (Exception ex) { Bukkit.getServer().getLogger().log(Level.WARNING, "Could not grab flags from WorldGuard", ex); } + legacy_loadedFlags = true; } } + return flagObj; } @@ -243,8 +249,10 @@ public class WorldGuardFlagHandler { if (flagObj instanceof StateFlag) { RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery(); State result = query.getApplicableRegions(BukkitAdapter.adapt(loc)).queryState(player, (StateFlag) flagObj); + return result != null ? result == State.ALLOW : null; } + return null; } @@ -260,6 +268,7 @@ public class WorldGuardFlagHandler { if (!wgPlugin) { return null; } + Object flagObj = getFlag(flag); // There's a different way to get this in the old version if (legacy_v62 || legacy_v60 || legacy_v5) { @@ -269,19 +278,25 @@ public class WorldGuardFlagHandler { // so, what's up? if (flagObj instanceof StateFlag) { RegionManager worldManager = WorldGuard.getInstance().getPlatform().getRegionContainer().get(BukkitAdapter.adapt(c.getWorld())); + if (worldManager == null) { return null; } + ProtectedCuboidRegion chunkRegion = new ProtectedCuboidRegion("__TEST__", BlockVector3.at(c.getX() << 4, c.getWorld().getMaxHeight(), c.getZ() << 4), BlockVector3.at((c.getX() << 4) + 15, 0, (c.getZ() << 4) + 15)); + ApplicableRegionSet set = worldManager.getApplicableRegions(chunkRegion); State result = set.queryState((RegionAssociable) null, (StateFlag) flagObj); + if (result == null && set.size() == 0) { return null; } + return result == State.ALLOW; } + return null; } @@ -341,15 +356,19 @@ public class WorldGuardFlagHandler { if (legacy5_applicableRegionSet_getFlag == null) { legacy5_applicableRegionSet_getFlag = Class.forName("com.sk89q.worldguard.protection.ApplicableRegionSet").getMethod("getFlag", Flag.class); } + result = (State) legacy5_applicableRegionSet_getFlag.invoke(set, flag); } + if (result == null && set != null && ((Iterable) set).iterator().hasNext()) { return null; } + return result == State.ALLOW; } catch (Exception ex) { Bukkit.getServer().getLogger().log(Level.WARNING, "Could not grab flags from WorldGuard", ex); } + return null; } @@ -399,15 +418,19 @@ public class WorldGuardFlagHandler { if (legacy5_applicableRegionSet_getFlag == null) { legacy5_applicableRegionSet_getFlag = Class.forName("com.sk89q.worldguard.protection.ApplicableRegionSet").getMethod("getFlag", Flag.class); } + result = (State) legacy5_applicableRegionSet_getFlag.invoke(set, flag); } + if (result == null && set != null && ((Iterable) set).iterator().hasNext()) { return null; } + return result == State.ALLOW; } catch (Exception ex) { Bukkit.getServer().getLogger().log(Level.WARNING, "Could not grab flags from WorldGuard", ex); } + return null; } } diff --git a/Core/src/main/java/com/songoda/core/hooks/worldguard/WorldGuardRegionHandler.java b/Core/src/main/java/com/songoda/core/hooks/worldguard/WorldGuardRegionHandler.java index b9528494..963a8d99 100644 --- a/Core/src/main/java/com/songoda/core/hooks/worldguard/WorldGuardRegionHandler.java +++ b/Core/src/main/java/com/songoda/core/hooks/worldguard/WorldGuardRegionHandler.java @@ -19,7 +19,6 @@ import java.util.List; import java.util.logging.Level; public class WorldGuardRegionHandler { - static boolean wgPlugin; static Object worldGuardPlugin; static boolean wg_v7 = false; @@ -37,7 +36,7 @@ public class WorldGuardRegionHandler { static Method legacy_getApplicableRegions_Vector = null; static void init() { - if ((wgPlugin = (worldGuardPlugin = Bukkit.getPluginManager().getPlugin("WorldGuard")) != null)) { + if (wgPlugin = (worldGuardPlugin = Bukkit.getPluginManager().getPlugin("WorldGuard")) != null) { // a number of flags were introduced in 7.x that aren't in 5 or 6 try { // if this class exists, we're on 7.x @@ -96,16 +95,21 @@ public class WorldGuardRegionHandler { if (worldGuardPlugin == null) { init(); } + if (!wgPlugin || c == null) { return Collections.EMPTY_LIST; - } else if (legacy_v62 || legacy_v60 || legacy_v5) { + } + + if (legacy_v62 || legacy_v60 || legacy_v5) { return getRegionNamesLegacy(c); } RegionManager worldManager = WorldGuard.getInstance().getPlatform().getRegionContainer().get(BukkitAdapter.adapt(c.getWorld())); + if (worldManager == null) { return Collections.EMPTY_LIST; } + ProtectedCuboidRegion chunkRegion = new ProtectedCuboidRegion("__TEST__", BlockVector3.at(c.getX() << 4, c.getWorld().getMaxHeight(), c.getZ() << 4), BlockVector3.at((c.getX() << 4) + 15, 0, (c.getZ() << 4) + 15)); @@ -126,6 +130,7 @@ public class WorldGuardRegionHandler { parent = parent.getParent(); } } + regions.removeAll(parentNames); return regions; @@ -135,9 +140,11 @@ public class WorldGuardRegionHandler { try { // grab the applicable manager for this world Object worldManager = (RegionManager) legacy_getRegionManager.invoke(worldGuardPlugin, c.getWorld()); + if (worldManager == null) { return null; } + // Create a legacy ProtectedCuboidRegion Object chunkRegion = legacy_newProtectedCuboidRegion.newInstance("__TEST__", legacy_newblockVector.newInstance(c.getX() << 4, c.getWorld().getMaxHeight(), c.getZ() << 4), @@ -162,12 +169,14 @@ public class WorldGuardRegionHandler { parent = parent.getParent(); } } + regions.removeAll(parentNames); return regions; } catch (Exception ex) { Bukkit.getServer().getLogger().log(Level.WARNING, "Could not grab regions from WorldGuard", ex); } + return Collections.EMPTY_LIST; } @@ -175,9 +184,12 @@ public class WorldGuardRegionHandler { if (worldGuardPlugin == null) { init(); } + if (!wgPlugin || loc == null) { return Collections.EMPTY_LIST; - } else if (legacy_v62 || legacy_v60 || legacy_v5) { + } + + if (legacy_v62 || legacy_v60 || legacy_v5) { return getRegionNamesLegacy(loc); } @@ -203,6 +215,7 @@ public class WorldGuardRegionHandler { parent = parent.getParent(); } } + regions.removeAll(parentNames); return regions; @@ -237,12 +250,14 @@ public class WorldGuardRegionHandler { parent = parent.getParent(); } } + regions.removeAll(parentNames); return regions; } catch (Exception ex) { Bukkit.getServer().getLogger().log(Level.WARNING, "Could not grab regions from WorldGuard", ex); } + return Collections.EMPTY_LIST; } } diff --git a/Core/src/main/java/com/songoda/core/input/ChatPrompt.java b/Core/src/main/java/com/songoda/core/input/ChatPrompt.java index 325b82e4..ce3e3c32 100644 --- a/Core/src/main/java/com/songoda/core/input/ChatPrompt.java +++ b/Core/src/main/java/com/songoda/core/input/ChatPrompt.java @@ -16,7 +16,6 @@ import java.util.UUID; import java.util.logging.Level; public class ChatPrompt implements Listener { - private static final List registered = new ArrayList<>(); private final Plugin plugin; @@ -29,6 +28,7 @@ public class ChatPrompt implements Listener { private ChatPrompt(Plugin plugin, Player player, ChatConfirmHandler hander) { this.plugin = plugin; this.handler = hander; + registered.add(player.getUniqueId()); } @@ -40,8 +40,11 @@ public class ChatPrompt implements Listener { ChatPrompt prompt = new ChatPrompt(plugin, player, hander); prompt.startListener(plugin); player.closeInventory(); - if (message != null) + + if (message != null) { player.sendMessage(message); + } + return prompt; } @@ -69,9 +72,11 @@ public class ChatPrompt implements Listener { plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> onClose.onClose(), 0L); } + HandlerList.unregisterAll(listener); player.sendMessage("Your action has timed out."); }, ticks); + return this; } @@ -80,7 +85,10 @@ public class ChatPrompt implements Listener { @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = false) public void onChat(AsyncPlayerChatEvent event) { Player player = event.getPlayer(); - if (!ChatPrompt.isRegistered(player)) return; + + if (!ChatPrompt.isRegistered(player)) { + return; + } ChatPrompt.unregister(player); event.setCancelled(true); @@ -88,6 +96,7 @@ public class ChatPrompt implements Listener { ChatConfirmEvent chatConfirmEvent = new ChatConfirmEvent(player, event.getMessage()); player.sendMessage("\u00BB " + event.getMessage()); + try { handler.onChat(chatConfirmEvent); } catch (Throwable t) { @@ -95,9 +104,9 @@ public class ChatPrompt implements Listener { } if (onClose != null) { - plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> - onClose.onClose(), 0L); + plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> onClose.onClose(), 0L); } + HandlerList.unregisterAll(listener); Bukkit.getScheduler().cancelTask(taskId); } @@ -105,20 +114,23 @@ public class ChatPrompt implements Listener { @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = false) public void onCancel(PlayerCommandPreprocessEvent event) { Player player = event.getPlayer(); - if (!ChatPrompt.isRegistered(player)) return; + + if (!ChatPrompt.isRegistered(player)) { + return; + } ChatPrompt.unregister(player); - if (event.getMessage().toLowerCase().startsWith("/cancel")) + if (event.getMessage().toLowerCase().startsWith("/cancel")) { event.setCancelled(true); + } if (onCancel != null) { - plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> - onCancel.onCancel(), 0L); + plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> onCancel.onCancel(), 0L); } else if (onClose != null) { - plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> - onClose.onClose(), 0L); + plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> onClose.onClose(), 0L); } + HandlerList.unregisterAll(listener); Bukkit.getScheduler().cancelTask(taskId); } @@ -140,7 +152,6 @@ public class ChatPrompt implements Listener { } public static class ChatConfirmEvent { - private final Player player; private final String message; diff --git a/Core/src/main/java/com/songoda/core/locale/Locale.java b/Core/src/main/java/com/songoda/core/locale/Locale.java index 4c29238b..a1c7c505 100644 --- a/Core/src/main/java/com/songoda/core/locale/Locale.java +++ b/Core/src/main/java/com/songoda/core/locale/Locale.java @@ -37,7 +37,6 @@ import java.util.stream.Collectors; * @author Brianna O'Keefe - Songoda */ public class Locale { - private static final Pattern OLD_NODE_PATTERN = Pattern.compile("^([^ ]+)\\s*=\\s*\"?(.*?)\"?$"); private static final String FILE_EXTENSION = ".lang"; @@ -69,6 +68,7 @@ public class Locale { */ public static Locale loadDefaultLocale(JavaPlugin plugin, String name) { saveDefaultLocale(plugin, name, name); + return loadLocale(plugin, name); } @@ -82,13 +82,24 @@ public class Locale { */ public static Locale loadLocale(JavaPlugin plugin, String name) { File localeFolder = new File(plugin.getDataFolder(), "locales/"); - if (!localeFolder.exists()) return null; + if (!localeFolder.exists()) { + return null; + } + File localeFile = new File(localeFolder, name + FILE_EXTENSION); - if (!localeFolder.exists()) return null; + if (!localeFolder.exists()) { + return null; + } + // found the lang file, now load it in! Locale l = new Locale(plugin, localeFile, name); - if (!l.reloadMessages()) return null; + + if (!l.reloadMessages()) { + return null; + } + plugin.getLogger().info("Loaded locale \"" + name + "\""); + return l; } @@ -102,17 +113,26 @@ public class Locale { public static List loadAllLocales(JavaPlugin plugin) { File localeFolder = new File(plugin.getDataFolder(), "locales/"); List all = new ArrayList<>(); + for (File localeFile : localeFolder.listFiles()) { String fileName = localeFile.getName(); - if (!fileName.endsWith(FILE_EXTENSION)) continue; + if (!fileName.endsWith(FILE_EXTENSION)) { + continue; + } + fileName = fileName.substring(0, fileName.lastIndexOf('.')); - if (fileName.split("_").length != 2) continue; + if (fileName.split("_").length != 2) { + continue; + } + Locale l = new Locale(plugin, localeFile, fileName); + if (l.reloadMessages()) { plugin.getLogger().info("Loaded locale \"" + fileName + "\""); all.add(l); } } + return all; } @@ -124,15 +144,22 @@ public class Locale { public static List getLocales(Plugin plugin) { File localeFolder = new File(plugin.getDataFolder(), "locales/"); List all = new ArrayList(); + for (File localeFile : localeFolder.listFiles()) { String fileName = localeFile.getName(); - if (!fileName.endsWith(FILE_EXTENSION)) continue; + if (!fileName.endsWith(FILE_EXTENSION)) { + continue; + } + fileName = fileName.substring(0, fileName.lastIndexOf('.')); + if (fileName.split("_").length != 2) { continue; } + all.add(fileName); } + return all; } @@ -163,16 +190,21 @@ public class Locale { } private static boolean saveLocale(Plugin plugin, InputStream in, String fileName, boolean builtin) { - if (in == null) return false; + if (in == null) { + return false; + } + File localeFolder = new File(plugin.getDataFolder(), "locales/"); if (!localeFolder.exists()) localeFolder.mkdirs(); - if (!fileName.endsWith(FILE_EXTENSION)) + if (!fileName.endsWith(FILE_EXTENSION)) { fileName = fileName + FILE_EXTENSION; + } File destinationFile = new File(localeFolder, fileName); - if (destinationFile.exists()) + if (destinationFile.exists()) { return updateFiles(plugin, in, destinationFile, builtin); + } try (OutputStream outputStream = new FileOutputStream(destinationFile)) { copy(in, outputStream); @@ -180,14 +212,14 @@ public class Locale { fileName = fileName.substring(0, fileName.lastIndexOf('.')); return fileName.split("_").length == 2; - } catch (IOException e) { - return false; + } catch (IOException ignore) { } + + return false; } // Write new changes to existing files, if any at all private static boolean updateFiles(Plugin plugin, InputStream defaultFile, File existingFile, boolean builtin) { - try (BufferedInputStream defaultIn = new BufferedInputStream(defaultFile); BufferedInputStream existingIn = new BufferedInputStream(new FileInputStream(existingFile))) { @@ -238,17 +270,19 @@ public class Locale { String.join("\n", added) ); } + existingLang.setRootNodeSpacing(0); existingLang.save(); } + existingLang.setRootNodeSpacing(0); existingLang.save(); + return !added.isEmpty(); } catch (InvalidConfigurationException ex) { plugin.getLogger().log(Level.SEVERE, "Error checking config " + existingFile.getName(), ex); } - } catch (IOException e) { - return false; + } catch (IOException ignore) { } return false; @@ -281,25 +315,28 @@ public class Locale { Config lang = new Config(file); lang.load(reader); translateMsgRoot(lang, file, charset); + // load lists as strings with newlines lang.getValues(true).forEach((k, v) -> nodes.put(k, v instanceof List ? (((List) v).stream().map(Object::toString).collect(Collectors.joining("\n")).toString()) : v.toString())); - } catch (IOException e) { - e.printStackTrace(); - return false; + + return true; + } catch (IOException ex) { + ex.printStackTrace(); } catch (InvalidConfigurationException ex) { Logger.getLogger(Locale.class.getName()).log(Level.SEVERE, "Configuration error in language file \"" + file.getName() + "\"", ex); - return false; } - return true; + + return false; } protected static BufferedReader translatePropertyToYAML(BufferedReader source, Charset charset) throws IOException { StringBuilder output = new StringBuilder(); + String line, line1; - for (int lineNumber = 0; (line = source.readLine()) != null; lineNumber++) { + for (int lineNumber = 0; (line = source.readLine()) != null; ++lineNumber) { if (lineNumber == 0) { // remove BOM markers, if any line1 = line; @@ -326,6 +363,7 @@ public class Locale { output.append(matcher.group(1)).append(": \"").append(matcher.group(2)).append("\"\n"); } } + // I hate Java sometimes because of crap like this: return new BufferedReader(new InputStreamReader(new BufferedInputStream(new ByteArrayInputStream(output.toString().getBytes(charset))), charset)); } @@ -335,15 +373,17 @@ public class Locale { .filter(e -> e.getValue() instanceof ConfigSection) .map(Map.Entry::getKey) .collect(Collectors.toList()); + if (!msgs.isEmpty()) { try (FileInputStream stream = new FileInputStream(file); BufferedReader source = new BufferedReader(new InputStreamReader((InputStream) stream, charset))) { String line; - for (int lineNumber = 0; (line = source.readLine()) != null; lineNumber++) { + for (int lineNumber = 0; (line = source.readLine()) != null; ++lineNumber) { if (lineNumber == 0) { // remove BOM markers, if any line = line.replaceAll("[\uFEFF\uFFFE\u200B]", ""); } + Matcher matcher; if (!(line = line.trim()).isEmpty() && !line.startsWith("#") && (matcher = OLD_NODE_PATTERN.matcher(line)).find() @@ -360,15 +400,18 @@ public class Locale { .filter(e -> e.getValue() instanceof ConfigSection) .map(Map.Entry::getKey) .collect(Collectors.toList()); + if (!msgs.isEmpty()) { String[] source = file.split("\n"); + String line; - for (int lineNumber = 0; lineNumber < source.length; lineNumber++) { + for (int lineNumber = 0; lineNumber < source.length; ++lineNumber) { line = source[lineNumber]; if (lineNumber == 0) { // remove BOM markers, if any line = line.replaceAll("[\uFEFF\uFFFE\u200B]", ""); } + Matcher matcher; if (!(line = line.trim()).isEmpty() && !line.startsWith("#") && (matcher = OLD_NODE_PATTERN.matcher(line)).find() @@ -412,6 +455,7 @@ public class Locale { if (this.nodes.containsKey(node + ".message")) { node += ".message"; } + return this.getMessageOrDefault(node, node); } @@ -427,6 +471,7 @@ public class Locale { if (this.nodes.containsKey(node + ".message")) { node += ".message"; } + return supplyPrefix(new Message(this.nodes.getOrDefault(node, defaultValue))); } @@ -447,8 +492,8 @@ public class Locale { while ((n = input.read(buffer)) != -1) { output.write(buffer, 0, n); } - } catch (IOException e) { - e.printStackTrace(); + } catch (IOException ex) { + ex.printStackTrace(); } } } diff --git a/Core/src/main/java/com/songoda/core/locale/Message.java b/Core/src/main/java/com/songoda/core/locale/Message.java index ddfb804f..26057ecd 100644 --- a/Core/src/main/java/com/songoda/core/locale/Message.java +++ b/Core/src/main/java/com/songoda/core/locale/Message.java @@ -17,7 +17,6 @@ import java.util.regex.Matcher; * easily manipulated then deployed */ public class Message { - private static boolean canActionBar = false; static { @@ -25,6 +24,7 @@ public class Message { Class.forName("net.md_5.bungee.api.ChatMessageType"); Class.forName("net.md_5.bungee.api.chat.TextComponent"); Player.Spigot.class.getDeclaredMethod("sendMessage", net.md_5.bungee.api.ChatMessageType.class, net.md_5.bungee.api.chat.TextComponent.class); + canActionBar = true; } catch (Exception ex) { } @@ -41,6 +41,7 @@ public class Message { public Message(String message) { ChatMessage chatMessage = new ChatMessage(); chatMessage.fromText(message); + this.message = chatMessage; } @@ -80,12 +81,15 @@ public class Message { if (sender instanceof Player) { if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_11)) { ((Player) sender).sendTitle("", getMessage(), 10, 30, 10); - } else { - ((Player) sender).sendTitle("", getMessage()); + return; } - } else { - sender.sendMessage(this.getMessage()); + + ((Player) sender).sendTitle("", getMessage()); + + return; } + + sender.sendMessage(this.getMessage()); } /** @@ -96,12 +100,16 @@ public class Message { public void sendActionBar(CommandSender sender) { if (!(sender instanceof Player)) { sender.sendMessage(this.getMessage()); - } else if (!canActionBar) { - sendTitle(sender); - } else { - ((Player) sender).spigot().sendMessage(net.md_5.bungee.api.ChatMessageType.ACTION_BAR, - new net.md_5.bungee.api.chat.TextComponent(getMessage())); + return; } + + if (!canActionBar) { + sendTitle(sender); + return; + } + + ((Player) sender).spigot().sendMessage(net.md_5.bungee.api.ChatMessageType.ACTION_BAR, + new net.md_5.bungee.api.chat.TextComponent(getMessage())); } /** @@ -163,12 +171,14 @@ public class Message { public Message processPlaceholder(String placeholder, Object replacement) { final String place = Matcher.quoteReplacement(placeholder); this.message = message.replaceAll("%" + place + "%|\\{" + place + "\\}", replacement == null ? "" : Matcher.quoteReplacement(replacement.toString())); + return this; } Message setPrefix(String prefix) { this.prefix = new ChatMessage(); this.prefix.fromText(prefix + " "); + return this; } diff --git a/Core/src/main/java/com/songoda/core/lootables/Lootables.java b/Core/src/main/java/com/songoda/core/lootables/Lootables.java index 6813a822..095e67ed 100644 --- a/Core/src/main/java/com/songoda/core/lootables/Lootables.java +++ b/Core/src/main/java/com/songoda/core/lootables/Lootables.java @@ -3,7 +3,6 @@ package com.songoda.core.lootables; import com.songoda.core.lootables.loot.LootManager; public class Lootables { - private final String lootablesDir; private final LootManager lootManager; diff --git a/Core/src/main/java/com/songoda/core/lootables/Modify.java b/Core/src/main/java/com/songoda/core/lootables/Modify.java index 316c2f6a..7e91c115 100644 --- a/Core/src/main/java/com/songoda/core/lootables/Modify.java +++ b/Core/src/main/java/com/songoda/core/lootables/Modify.java @@ -3,6 +3,5 @@ package com.songoda.core.lootables; import com.songoda.core.lootables.loot.Loot; public interface Modify { - Loot Modify(Loot loot); } diff --git a/Core/src/main/java/com/songoda/core/lootables/gui/AbstractGuiListEditor.java b/Core/src/main/java/com/songoda/core/lootables/gui/AbstractGuiListEditor.java index 3f42e085..262308ac 100644 --- a/Core/src/main/java/com/songoda/core/lootables/gui/AbstractGuiListEditor.java +++ b/Core/src/main/java/com/songoda/core/lootables/gui/AbstractGuiListEditor.java @@ -12,7 +12,6 @@ import java.util.Collections; import java.util.List; public abstract class AbstractGuiListEditor extends Gui { - protected final Loot loot; private final Gui returnGui; @@ -20,12 +19,15 @@ public abstract class AbstractGuiListEditor extends Gui { super(1, returnGui); this.returnGui = returnGui; this.loot = loot; + setDefaultItem(null); + paint(); } public void paint() { List lore = getData() == null ? new ArrayList<>() : getData(); + setButton(2, GuiUtils.createButtonItem(CompatibleMaterial.OAK_FENCE_GATE, TextUtils.formatText("&cBack")), (event) -> { diff --git a/Core/src/main/java/com/songoda/core/lootables/gui/GuiEditor.java b/Core/src/main/java/com/songoda/core/lootables/gui/GuiEditor.java index d0fd0fbb..6bc3d3e0 100644 --- a/Core/src/main/java/com/songoda/core/lootables/gui/GuiEditor.java +++ b/Core/src/main/java/com/songoda/core/lootables/gui/GuiEditor.java @@ -13,12 +13,13 @@ import java.util.ArrayList; import java.util.List; public class GuiEditor extends Gui { - private final LootManager lootManager; public GuiEditor(LootManager lootManager) { super(6); + this.lootManager = lootManager; + setDefaultItem(null); setTitle("Lootables Overview"); @@ -26,8 +27,10 @@ public class GuiEditor extends Gui { } private void paint() { - if (inventory != null) + if (inventory != null) { inventory.clear(); + } + setActionForRange(0, 0, 5, 9, null); List lootables = new ArrayList<>(lootManager.getRegisteredLootables().values()); @@ -35,19 +38,21 @@ public class GuiEditor extends Gui { double itemCount = lootables.size(); this.pages = (int) Math.max(1, Math.ceil(itemCount / 36)); - if (page != 1) + if (page != 1) { setButton(5, 2, GuiUtils.createButtonItem(CompatibleMaterial.ARROW, "Back"), (event) -> { page--; paint(); }); + } - if (page != pages) + if (page != pages) { setButton(5, 6, GuiUtils.createButtonItem(CompatibleMaterial.ARROW, "Next"), (event) -> { page++; paint(); }); + } for (int i = 9; i < 45; i++) { int current = ((page - 1) * 36) - 9; @@ -55,8 +60,11 @@ public class GuiEditor extends Gui { setItem(i, null); continue; } + Lootable lootable = lootables.get(current + i); - if (lootable == null) continue; + if (lootable == null) { + continue; + } setButton(i, getIcon(lootable.getKey()), (event) -> guiManager.showGUI(event.player, new GuiLootableEditor(lootManager, lootable, this))); @@ -66,16 +74,23 @@ public class GuiEditor extends Gui { public ItemStack getIcon(String key) { ItemStack stack = null; EntityType type = EntityType.fromName(key); + if (type != null) { CompatibleMaterial material = CompatibleMaterial.getSpawnEgg(type); - if (material != null) + + if (material != null) { stack = material.getItem(); + } } - if (stack == null) + + if (stack == null) { stack = CompatibleMaterial.GHAST_SPAWN_EGG.getItem(); + } + ItemMeta meta = stack.getItemMeta(); meta.setDisplayName(key); stack.setItemMeta(meta); + return stack; } } diff --git a/Core/src/main/java/com/songoda/core/lootables/gui/GuiEnchantEditor.java b/Core/src/main/java/com/songoda/core/lootables/gui/GuiEnchantEditor.java index 63ca6543..bf5fdf41 100644 --- a/Core/src/main/java/com/songoda/core/lootables/gui/GuiEnchantEditor.java +++ b/Core/src/main/java/com/songoda/core/lootables/gui/GuiEnchantEditor.java @@ -15,21 +15,24 @@ import java.util.List; import java.util.Map; public class GuiEnchantEditor extends Gui { - private final Gui returnGui; private final Loot loot; public GuiEnchantEditor(Loot loot, Gui returnGui) { super(1, returnGui); + this.returnGui = returnGui; this.loot = loot; + setDefaultItem(null); setTitle("Enchantment Editor"); + paint(); } public void paint() { Map lore = loot.getEnchants() == null ? new HashMap<>() : new HashMap<>(loot.getEnchants()); + setButton(2, GuiUtils.createButtonItem(CompatibleMaterial.OAK_FENCE_GATE, TextUtils.formatText("&cBack")), (event) -> { @@ -63,6 +66,7 @@ public class GuiEnchantEditor extends Gui { gui1.setTitle("Enter a level"); guiManager.showGUI(event.player, gui1); })); + gui.setTitle("Enter an enchant"); guiManager.showGUI(event.player, gui); })); @@ -71,11 +75,12 @@ public class GuiEnchantEditor extends Gui { String last = null; - if (!lore.isEmpty()) + if (!lore.isEmpty()) { for (Map.Entry entry : lore.entrySet()) { last = entry.getKey(); enchantments.add("&6" + entry.getKey() + " " + entry.getValue()); } + } setItem(4, GuiUtils.createButtonItem(CompatibleMaterial.WRITABLE_BOOK, TextUtils.formatText("&7Enchant Override:"), diff --git a/Core/src/main/java/com/songoda/core/lootables/gui/GuiEntityEditor.java b/Core/src/main/java/com/songoda/core/lootables/gui/GuiEntityEditor.java index 56e2faa2..e7a4c81f 100644 --- a/Core/src/main/java/com/songoda/core/lootables/gui/GuiEntityEditor.java +++ b/Core/src/main/java/com/songoda/core/lootables/gui/GuiEntityEditor.java @@ -8,7 +8,6 @@ import java.util.List; import java.util.stream.Collectors; public class GuiEntityEditor extends AbstractGuiListEditor { - public GuiEntityEditor(Loot loot, Gui returnGui) { super(loot, returnGui); } @@ -26,11 +25,13 @@ public class GuiEntityEditor extends AbstractGuiListEditor { @Override protected String validate(String line) { line = line.toUpperCase().trim(); + try { EntityType.valueOf(line); return line; - } catch (IllegalArgumentException e) { - return null; + } catch (IllegalArgumentException ignore) { } + + return null; } } diff --git a/Core/src/main/java/com/songoda/core/lootables/gui/GuiLootEditor.java b/Core/src/main/java/com/songoda/core/lootables/gui/GuiLootEditor.java index f10fe666..2c236aa8 100644 --- a/Core/src/main/java/com/songoda/core/lootables/gui/GuiLootEditor.java +++ b/Core/src/main/java/com/songoda/core/lootables/gui/GuiLootEditor.java @@ -19,33 +19,35 @@ import java.util.List; import java.util.Map; public class GuiLootEditor extends Gui { - private final LootManager lootManager; private final Loot loot; private final Gui returnGui; public GuiLootEditor(LootManager lootManager, Loot loot, Gui returnGui) { super(6, returnGui); + this.lootManager = lootManager; this.loot = loot; this.returnGui = returnGui; + setDefaultItem(null); setTitle("Loot Editor"); + paint(); + setOnClose((event) -> lootManager.saveLootables(false)); } public void paint() { - if (inventory != null) + if (inventory != null) { inventory.clear(); + } + setActionForRange(0, 0, 5, 9, null); - setButton(8, GuiUtils.createButtonItem(CompatibleMaterial.OAK_DOOR, - TextUtils.formatText("&cBack")), - (event) -> { - guiManager.showGUI(event.player, returnGui); - }); + setButton(8, GuiUtils.createButtonItem(CompatibleMaterial.OAK_DOOR, TextUtils.formatText("&cBack")), + (event) -> guiManager.showGUI(event.player, returnGui)); setButton(9, GuiUtils.createButtonItem(loot.getMaterial() == null ? CompatibleMaterial.BARRIER : loot.getMaterial(), TextUtils.formatText("&7Current Material: &6" + (loot.getMaterial() != null @@ -56,6 +58,7 @@ public class GuiLootEditor extends Gui { )), (event) -> { ItemStack stack = event.player.getInventory().getItemInMainHand(); loot.setMaterial(CompatibleMaterial.getMaterial(stack)); + paint(); }); @@ -65,9 +68,11 @@ public class GuiLootEditor extends Gui { AnvilGui gui = new AnvilGui(event.player, this); gui.setAction((e -> { loot.setName(gui.getInputText().trim()); + paint(); e.player.closeInventory(); })); + guiManager.showGUI(event.player, gui); gui.setInput(GuiUtils.createButtonItem(CompatibleMaterial.PAPER, loot.getName())); }); @@ -79,9 +84,11 @@ public class GuiLootEditor extends Gui { List enchantments = new ArrayList<>(); - if (loot.getEnchants() != null) - for (Map.Entry entry : loot.getEnchants().entrySet()) + if (loot.getEnchants() != null) { + for (Map.Entry entry : loot.getEnchants().entrySet()) { enchantments.add("&6" + entry.getKey() + " " + entry.getValue()); + } + } setButton(12, GuiUtils.createButtonItem(CompatibleMaterial.ENCHANTED_BOOK, TextUtils.formatText("&7Enchantments:"), @@ -103,6 +110,7 @@ public class GuiLootEditor extends Gui { (event) -> { ItemStack stack = event.player.getInventory().getItemInMainHand(); loot.setBurnedMaterial(CompatibleMaterial.getMaterial(stack)); + paint(); }); @@ -115,13 +123,15 @@ public class GuiLootEditor extends Gui { )), (event) -> { AnvilGui gui = new AnvilGui(event.player, this); + gui.setAction((e) -> { loot.setChance(Double.parseDouble(gui.getInputText())); + paint(); e.player.closeInventory(); }); - gui.setInput(GuiUtils.createButtonItem(CompatibleMaterial.PAPER, - String.valueOf(loot.getChance()))); + + gui.setInput(GuiUtils.createButtonItem(CompatibleMaterial.PAPER, String.valueOf(loot.getChance()))); guiManager.showGUI(event.player, gui); }); @@ -129,11 +139,14 @@ public class GuiLootEditor extends Gui { TextUtils.formatText("&7Min Drop Amount: &6" + loot.getMin())), (event) -> { AnvilGui gui = new AnvilGui(event.player, this); + gui.setAction((e) -> { loot.setMin(Integer.parseInt(gui.getInputText())); + paint(); e.player.closeInventory(); }); + gui.setInput(GuiUtils.createButtonItem(CompatibleMaterial.PAPER, String.valueOf(loot.getMin()))); guiManager.showGUI(event.player, gui); @@ -143,13 +156,15 @@ public class GuiLootEditor extends Gui { TextUtils.formatText("&7Max Drop Amount: &6" + loot.getMax())), (event) -> { AnvilGui gui = new AnvilGui(event.player, this); + gui.setAction((e) -> { loot.setMax(Integer.parseInt(gui.getInputText())); + paint(); e.player.closeInventory(); }); - gui.setInput(GuiUtils.createButtonItem(CompatibleMaterial.PAPER, - String.valueOf(loot.getMax()))); + + gui.setInput(GuiUtils.createButtonItem(CompatibleMaterial.PAPER, String.valueOf(loot.getMax()))); guiManager.showGUI(event.player, gui); }); @@ -159,11 +174,12 @@ public class GuiLootEditor extends Gui { AnvilGui gui = new AnvilGui(event.player, this); gui.setAction((e) -> { loot.setDamageMin(Integer.parseInt(gui.getInputText())); + paint(); e.player.closeInventory(); }); - gui.setInput(GuiUtils.createButtonItem(CompatibleMaterial.PAPER, - String.valueOf(loot.getDamageMin()))); + + gui.setInput(GuiUtils.createButtonItem(CompatibleMaterial.PAPER, String.valueOf(loot.getDamageMin()))); guiManager.showGUI(event.player, gui); }); @@ -173,11 +189,12 @@ public class GuiLootEditor extends Gui { AnvilGui gui = new AnvilGui(event.player, this); gui.setAction((e) -> { loot.setDamageMax(Integer.parseInt(gui.getInputText())); + paint(); e.player.closeInventory(); }); - gui.setInput(GuiUtils.createButtonItem(CompatibleMaterial.PAPER, - String.valueOf(loot.getDamageMax()))); + + gui.setInput(GuiUtils.createButtonItem(CompatibleMaterial.PAPER, String.valueOf(loot.getDamageMax()))); guiManager.showGUI(event.player, gui); }); @@ -185,6 +202,7 @@ public class GuiLootEditor extends Gui { TextUtils.formatText("&7Allow Looting Enchantment?: &6" + loot.isAllowLootingEnchant())), (event) -> { loot.setAllowLootingEnchant(!loot.isAllowLootingEnchant()); + paint(); event.player.closeInventory(); }); @@ -193,13 +211,15 @@ public class GuiLootEditor extends Gui { TextUtils.formatText("&7Min Child Loot Min: &6" + loot.getChildDropCountMin())), (event) -> { AnvilGui gui = new AnvilGui(event.player, this); + gui.setAction((e) -> { loot.setChildDropCountMin(Integer.parseInt(gui.getInputText())); + paint(); e.player.closeInventory(); }); - gui.setInput(GuiUtils.createButtonItem(CompatibleMaterial.PAPER, - String.valueOf(loot.getChildDropCountMin()))); + + gui.setInput(GuiUtils.createButtonItem(CompatibleMaterial.PAPER, String.valueOf(loot.getChildDropCountMin()))); guiManager.showGUI(event.player, gui); }); @@ -207,21 +227,25 @@ public class GuiLootEditor extends Gui { TextUtils.formatText("&7Min Child Loot Max: &6" + loot.getChildDropCountMax())), (event) -> { AnvilGui gui = new AnvilGui(event.player, this); + gui.setAction((e) -> { loot.setChildDropCountMax(Integer.parseInt(gui.getInputText())); + paint(); e.player.closeInventory(); }); - gui.setInput(GuiUtils.createButtonItem(CompatibleMaterial.PAPER, - String.valueOf(loot.getChildDropCountMax()))); + + gui.setInput(GuiUtils.createButtonItem(CompatibleMaterial.PAPER, String.valueOf(loot.getChildDropCountMax()))); guiManager.showGUI(event.player, gui); }); List entities = new ArrayList<>(); - if (loot.getOnlyDropFor() != null) - for (EntityType entity : loot.getOnlyDropFor()) + if (loot.getOnlyDropFor() != null) { + for (EntityType entity : loot.getOnlyDropFor()) { entities.add("&6" + entity.name()); + } + } setButton(22, GuiUtils.createButtonItem(CompatibleMaterial.ENCHANTED_BOOK, TextUtils.formatText("&7Only Drop For:"), @@ -231,16 +255,19 @@ public class GuiLootEditor extends Gui { setButton(4, 0, GuiUtils.createButtonItem(CompatibleMaterial.LIME_DYE, TextUtils.formatText("&aCreate new Child Loot")), (event -> { AnvilGui gui = new AnvilGui(event.player, this); + gui.setAction((event1 -> { try { loot.addChildLoots(new LootBuilder().setMaterial(CompatibleMaterial .valueOf(gui.getInputText().trim())).build()); - } catch (IllegalArgumentException e) { + } catch (IllegalArgumentException ignore) { event.player.sendMessage("That is not a valid material."); } + event.player.closeInventory(); paint(); })); + gui.setTitle("Enter a material"); guiManager.showGUI(event.player, gui); })); @@ -262,7 +289,8 @@ public class GuiLootEditor extends Gui { guiManager.showGUI(event.player, new GuiLootEditor(lootManager, loot, this)); } }); - i++; + + ++i; } } } diff --git a/Core/src/main/java/com/songoda/core/lootables/gui/GuiLootableEditor.java b/Core/src/main/java/com/songoda/core/lootables/gui/GuiLootableEditor.java index fb1a0bd9..3a489359 100644 --- a/Core/src/main/java/com/songoda/core/lootables/gui/GuiLootableEditor.java +++ b/Core/src/main/java/com/songoda/core/lootables/gui/GuiLootableEditor.java @@ -13,26 +13,30 @@ import org.bukkit.event.inventory.ClickType; import org.bukkit.inventory.ItemStack; public class GuiLootableEditor extends Gui { - private final LootManager lootManager; private final Lootable lootable; private final Gui returnGui; public GuiLootableEditor(LootManager lootManager, Lootable lootable, Gui returnGui) { super(6); + this.lootManager = lootManager; this.lootable = lootable; this.returnGui = returnGui; + setOnClose((event) -> lootManager.saveLootables(false)); setDefaultItem(null); setTitle("Lootables Editor"); + paint(); } private void paint() { - if (inventory != null) + if (inventory != null) { inventory.clear(); + } + setActionForRange(0, 0, 5, 9, null); setButton(0, GuiUtils.createButtonItem(CompatibleMaterial.LIME_DYE, TextUtils.formatText("&aCreate new Loot")), @@ -42,12 +46,14 @@ public class GuiLootableEditor extends Gui { try { lootable.registerLoot(new LootBuilder().setMaterial(CompatibleMaterial .valueOf(gui.getInputText().trim())).build()); - } catch (IllegalArgumentException e) { + } catch (IllegalArgumentException ex) { event.player.sendMessage("That is not a valid material."); } + event.player.closeInventory(); paint(); })); + gui.setTitle("Enter a material"); guiManager.showGUI(event.player, gui); })); @@ -68,10 +74,15 @@ public class GuiLootableEditor extends Gui { if (event.clickType == ClickType.RIGHT) { lootable.removeLoot(loot); paint(); - } else if (event.clickType == ClickType.LEFT) { + + return; + } + + if (event.clickType == ClickType.LEFT) { guiManager.showGUI(event.player, new GuiLootEditor(lootManager, loot, this)); } }); + i++; } } diff --git a/Core/src/main/java/com/songoda/core/lootables/gui/GuiLoreEditor.java b/Core/src/main/java/com/songoda/core/lootables/gui/GuiLoreEditor.java index 3a938bb4..ebbf6c9b 100644 --- a/Core/src/main/java/com/songoda/core/lootables/gui/GuiLoreEditor.java +++ b/Core/src/main/java/com/songoda/core/lootables/gui/GuiLoreEditor.java @@ -6,7 +6,6 @@ import com.songoda.core.lootables.loot.Loot; import java.util.List; public class GuiLoreEditor extends AbstractGuiListEditor { - public GuiLoreEditor(Loot loot, Gui returnGui) { super(loot, returnGui); } diff --git a/Core/src/main/java/com/songoda/core/lootables/loot/Drop.java b/Core/src/main/java/com/songoda/core/lootables/loot/Drop.java index 7a08f1fe..35cb35ef 100644 --- a/Core/src/main/java/com/songoda/core/lootables/loot/Drop.java +++ b/Core/src/main/java/com/songoda/core/lootables/loot/Drop.java @@ -3,7 +3,6 @@ package com.songoda.core.lootables.loot; import org.bukkit.inventory.ItemStack; public class Drop { - private ItemStack itemStack; private String command; diff --git a/Core/src/main/java/com/songoda/core/lootables/loot/DropUtils.java b/Core/src/main/java/com/songoda/core/lootables/loot/DropUtils.java index ffbb14d0..ebc5d03d 100644 --- a/Core/src/main/java/com/songoda/core/lootables/loot/DropUtils.java +++ b/Core/src/main/java/com/songoda/core/lootables/loot/DropUtils.java @@ -9,12 +9,12 @@ import java.util.ArrayList; import java.util.List; public class DropUtils { - public static void processStackedDrop(LivingEntity entity, List drops, EntityDeathEvent event) { int xpToDrop = event.getDroppedExp(); List items = new ArrayList<>(); List commands = new ArrayList<>(); List xp = new ArrayList<>(); + for (Drop drop : drops) { if (drop == null) continue; @@ -22,47 +22,61 @@ public class DropUtils { if (droppedItem != null) { droppedItem = droppedItem.clone(); boolean success = false; + for (ItemStack item : items) { if (item.getType() != droppedItem.getType() || item.getDurability() != droppedItem.getDurability() || item.getAmount() + droppedItem.getAmount() > droppedItem.getMaxStackSize()) continue; item.setAmount(item.getAmount() + droppedItem.getAmount()); success = true; + break; } - if (!success) - items.add(droppedItem); - } - if (drop.getCommand() != null) - commands.add(drop.getCommand()); - if (drop.getXp() != 0) + if (!success) { + items.add(droppedItem); + } + } + + if (drop.getCommand() != null) { + commands.add(drop.getCommand()); + } + + if (drop.getXp() != 0) { xp.add(drop.getXp()); + } } event.getDrops().clear(); - if (!items.isEmpty()) + if (!items.isEmpty()) { dropItems(items, event); - else if (!commands.isEmpty()) + } else if (!commands.isEmpty()) { runCommands(entity, commands); + } - for (int x : xp) + for (int x : xp) { xpToDrop += x; + } + event.setDroppedExp(xpToDrop); } private static void dropItems(List items, EntityDeathEvent event) { - for (ItemStack item : items) + for (ItemStack item : items) { event.getDrops().add(item); + } } private static void runCommands(LivingEntity entity, List commands) { for (String command : commands) { - if (entity.getKiller() != null) + if (entity.getKiller() != null) { command = command.replace("%player%", entity.getKiller().getName()); - if (!command.contains("%player%")) + } + + if (!command.contains("%player%")) { Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command); + } } } } diff --git a/Core/src/main/java/com/songoda/core/lootables/loot/Loot.java b/Core/src/main/java/com/songoda/core/lootables/loot/Loot.java index 107d89c9..cb13e30e 100644 --- a/Core/src/main/java/com/songoda/core/lootables/loot/Loot.java +++ b/Core/src/main/java/com/songoda/core/lootables/loot/Loot.java @@ -17,7 +17,6 @@ import java.util.Map; import java.util.Random; public class Loot { - // Command ran for this drop. @SerializedName("Command") private String command; @@ -128,10 +127,15 @@ public class Loot { } public List getLore() { - if (lore == null) return null; + if (lore == null) { + return null; + } + List lore = new ArrayList<>(); - for (String line : this.lore) + + for (String line : this.lore) { lore.add(TextUtils.formatText(line)); + } return lore; } @@ -141,19 +145,25 @@ public class Loot { } public ItemStack getEnchants(ItemStack item) { - if (enchants == null) return null; + if (enchants == null) { + return null; + } + Map enchants = new HashMap<>(); for (Map.Entry entry : this.enchants.entrySet()) { - if (entry.getValue() == null) continue; if (entry.getKey().equalsIgnoreCase("RANDOM")) { item = ItemUtils.applyRandomEnchants(item, entry.getValue()); + continue; } + enchants.put(Enchantment.getByName(entry.getKey()), entry.getValue()); } + item.addEnchantments(enchants); + return item; } @@ -187,15 +197,23 @@ public class Loot { public boolean runChance(int looting, ItemStack murderWeapon) { double chance = this.chance; + if (enchantChances != null && murderWeapon != null && enchants != null) { for (Map.Entry entry : murderWeapon.getEnchantments().entrySet()) { String key = entry.getKey().getName() + ":" + entry.getValue(); - if (!enchants.containsKey(key)) continue; + + if (!enchants.containsKey(key)) { + continue; + } + double ch = enchantChances.get(key); - if (ch > chance) + + if (ch > chance) { chance = enchantChances.get(key); + } } } + return (Math.random() * 100) - (chance + (lootingIncrease == null ? 1 : lootingIncrease * looting)) < 0 || chance == 100; } @@ -255,13 +273,19 @@ public class Loot { public void addChildLoots(Loot... loots) { this.childDropCountMin = 1; this.childDropCountMax = 1; - if (childLoot == null) + + if (childLoot == null) { this.childLoot = new ArrayList<>(); + } + this.childLoot.addAll(Arrays.asList(loots)); } public void removeChildLoot(Loot loot) { - if (childLoot == null) return; + if (childLoot == null) { + return; + } + this.childLoot.remove(loot); } @@ -299,7 +323,10 @@ public class Loot { } public int getChildDropCount() { - if (childDropCountMin == null || childDropCountMax == null) return 0; + if (childDropCountMin == null || childDropCountMax == null) { + return 0; + } + return new Random().nextInt(childDropCountMax - childDropCountMin + 1) + childDropCountMin; } diff --git a/Core/src/main/java/com/songoda/core/lootables/loot/LootBuilder.java b/Core/src/main/java/com/songoda/core/lootables/loot/LootBuilder.java index 797bbafd..602e0728 100644 --- a/Core/src/main/java/com/songoda/core/lootables/loot/LootBuilder.java +++ b/Core/src/main/java/com/songoda/core/lootables/loot/LootBuilder.java @@ -9,7 +9,6 @@ import java.util.HashMap; import java.util.Map; public final class LootBuilder { - private final Loot loot; public LootBuilder() { @@ -33,16 +32,22 @@ public final class LootBuilder { public LootBuilder addEnchants(Tuple... tuples) { Map enchants = new HashMap<>(); - for (Tuple tuple : tuples) + + for (Tuple tuple : tuples) { enchants.put((String) tuple.getKey(), (int) tuple.getValue()); + } + this.loot.setEnchants(enchants); return this; } public LootBuilder addEnchantChances(EnchantChance... enchantChances) { Map enchants = new HashMap<>(); - for (EnchantChance chance : enchantChances) + + for (EnchantChance chance : enchantChances) { enchants.put(chance.getEnchantment().getName() + ":" + chance.getLevel(), chance.getChanceOverride()); + } + this.loot.setEnchantChances(enchants); return this; } @@ -100,6 +105,7 @@ public final class LootBuilder { public LootBuilder setChildDropCount(int count) { this.loot.setChildDropCountMin(count); this.loot.setChildDropCountMax(count); + return this; } diff --git a/Core/src/main/java/com/songoda/core/lootables/loot/LootManager.java b/Core/src/main/java/com/songoda/core/lootables/loot/LootManager.java index d701874b..3db354b9 100644 --- a/Core/src/main/java/com/songoda/core/lootables/loot/LootManager.java +++ b/Core/src/main/java/com/songoda/core/lootables/loot/LootManager.java @@ -24,7 +24,6 @@ import java.util.Map; import java.util.Random; public class LootManager { - private final Map registeredLootables = new HashMap<>(); private final Lootables lootables; @@ -39,19 +38,25 @@ public class LootManager { public void removeLootable(String key) { registeredLootables.remove(key); - File file = new File(lootables.getLootablesDir() - + "/" + key.toLowerCase() + ".json"); + + File file = new File(lootables.getLootablesDir() + "/" + key.toLowerCase() + ".json"); file.delete(); } public List runLoot(Modify modify, boolean burning, boolean isCharged, ItemStack murderWeapon, EntityType looter, Loot loot, int rerollChance, int looting) { List toDrop = new ArrayList<>(); - if (modify != null) - loot = modify.Modify(loot); - if (loot == null) return toDrop; - if (loot.runChance(looting, murderWeapon) || ((Math.random() * 100) - rerollChance < 0 || rerollChance == 100) - && loot.runChance(looting, murderWeapon)) { + if (modify != null) { + loot = modify.Modify(loot); + } + + if (loot == null) { + return toDrop; + } + + if (loot.runChance(looting, murderWeapon) || + ((Math.random() * 100) - rerollChance < 0 || rerollChance == 100) && + loot.runChance(looting, murderWeapon)) { if (loot.getOnlyDropFor().size() != 0 && loot.getOnlyDropFor().stream().noneMatch(type -> looter != null && type == looter) @@ -68,10 +73,20 @@ public class LootManager { top: for (int i = 0; i < 100; i++) { for (Loot value : childLoot) { - if (value == null) continue; - if (amt == success) break top; + if (value == null) { + continue; + } + + if (amt == success) { + break top; + } + List drops = runLoot(modify, burning, isCharged, murderWeapon, looter, value, rerollChance, looting); - if (!drops.isEmpty()) success++; + + if (!drops.isEmpty()) { + success++; + } + toDrop.addAll(drops); } } @@ -81,67 +96,87 @@ public class LootManager { String command = loot.getCommand(); int xp = loot.getXp(); - if (material == null && command == null) return toDrop; + if (material == null && command == null) { + return toDrop; + } int amount = loot.getAmountToDrop(looting); - if (amount == 0) return toDrop; + if (amount == 0) { + return toDrop; + } if (material != null) { - ItemStack item = loot.getBurnedMaterial() != null && burning - ? loot.getBurnedMaterial().getItem() : material.getItem(); + ItemStack item = loot.getBurnedMaterial() != null && + burning ? loot.getBurnedMaterial().getItem() : material.getItem(); item.setAmount(amount); ItemMeta meta = item.getItemMeta() == null ? Bukkit.getItemFactory().getItemMeta(loot.getMaterial().getMaterial()) : item.getItemMeta(); - if (loot.getName() != null) + if (loot.getName() != null) { meta.setDisplayName(loot.getName()); + } - if (loot.getLore() != null) + if (loot.getLore() != null) { meta.setLore(loot.getLore()); + } + item.setItemMeta(meta); - if (loot.getEnchants(item) != null) + if (loot.getEnchants(item) != null) { item = loot.getEnchants(item); + } if (loot.getDamageMax() != 0 && loot.getDamageMin() != 0) { short max = item.getType().getMaxDurability(); short min = (short) (max * (10 / 100.0f)); + item.setDurability((short) (new Random().nextInt(max - min + 1) + min)); } toDrop.add(new Drop(item)); } + if (command != null) { - for (int i = 0; i < amount; i++) + for (int i = 0; i < amount; i++) { toDrop.add(new Drop(command)); + } } + if (xp != 0) { - for (int i = 0; i < amount; i++) + for (int i = 0; i < amount; i++) { toDrop.add(new Drop(xp)); + } } } + return toDrop; } public void loadLootables() { registeredLootables.clear(); + File dir = new File(lootables.getLootablesDir()); File[] directoryListing = dir.listFiles(); + if (directoryListing != null) { for (File file : directoryListing) { - if (!file.getName().endsWith(".json")) continue; + if (!file.getName().endsWith(".json")) { + continue; + } + try { Gson gson = new Gson(); JsonReader reader = new JsonReader(new FileReader(file.getPath())); Lootable lootable = gson.fromJson(reader, Lootable.class); - if (lootable.getRegisteredLoot().size() != 0) + if (lootable.getRegisteredLoot().size() != 0) { addLootable(lootable); + } reader.close(); - } catch (IOException e) { - e.printStackTrace(); + } catch (IOException ex) { + ex.printStackTrace(); } } } @@ -154,22 +189,25 @@ public class LootManager { // Save to file for (Lootable lootable : registeredLootables.values()) { try { - File file = new File(lootables.getLootablesDir() + "/" + lootable.getKey().toLowerCase() + ".json"); - if (file.exists() && defaults) continue; + + if (file.exists() && defaults) { + continue; + } try (Writer writer = new FileWriter(file.getPath())) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); gson.toJson(lootable, writer); } - } catch (IOException e) { - e.printStackTrace(); + } catch (IOException ex) { + ex.printStackTrace(); } } - if (defaults) + if (defaults) { registeredLootables.clear(); + } } public Map getRegisteredLootables() { diff --git a/Core/src/main/java/com/songoda/core/lootables/loot/Lootable.java b/Core/src/main/java/com/songoda/core/lootables/loot/Lootable.java index 9640b409..0b151e56 100644 --- a/Core/src/main/java/com/songoda/core/lootables/loot/Lootable.java +++ b/Core/src/main/java/com/songoda/core/lootables/loot/Lootable.java @@ -7,7 +7,6 @@ import java.util.Arrays; import java.util.List; public class Lootable { - // The key applicable to this lootable. @SerializedName("Type") private final String type; @@ -22,6 +21,7 @@ public class Lootable { public Lootable(String key, Loot... loots) { this.type = key; + registeredLoot.addAll(Arrays.asList(loots)); } diff --git a/Core/src/main/java/com/songoda/core/lootables/loot/objects/EnchantChance.java b/Core/src/main/java/com/songoda/core/lootables/loot/objects/EnchantChance.java index 915453ed..bb46dabc 100644 --- a/Core/src/main/java/com/songoda/core/lootables/loot/objects/EnchantChance.java +++ b/Core/src/main/java/com/songoda/core/lootables/loot/objects/EnchantChance.java @@ -3,7 +3,6 @@ package com.songoda.core.lootables.loot.objects; import org.bukkit.enchantments.Enchantment; public class EnchantChance { - private final Enchantment enchantment; private final int level; private final double chanceOverride; diff --git a/Core/src/main/java/com/songoda/core/math/Eval.java b/Core/src/main/java/com/songoda/core/math/Eval.java index a68b51c8..6931dff7 100644 --- a/Core/src/main/java/com/songoda/core/math/Eval.java +++ b/Core/src/main/java/com/songoda/core/math/Eval.java @@ -1,7 +1,6 @@ package com.songoda.core.math; public class Eval { - private int pos = -1, ch; private final String toParse; private final String warningMessage; @@ -16,18 +15,26 @@ public class Eval { } private boolean eat(int charToEat) { - while (ch == ' ') nextChar(); + while (ch == ' ') { + nextChar(); + } + if (ch == charToEat) { nextChar(); return true; } + return false; } public double parse() { nextChar(); + double x = parseExpression(); - if (pos < toParse.length()) throw new RuntimeException(warningMessage + "Unexpected: " + (char) ch); + if (pos < toParse.length()) { + throw new RuntimeException(warningMessage + "Unexpected: " + (char) ch); + } + return x; } @@ -39,25 +46,39 @@ public class Eval { private double parseExpression() { double x = parseTerm(); + for (; ; ) { - if (eat('+')) x += parseTerm(); // addition - else if (eat('-')) x -= parseTerm(); // subtraction - else return x; + if (eat('+')) { // addition + x += parseTerm(); + } else if (eat('-')) { // subtraction + x -= parseTerm(); + } else { + return x; + } } } private double parseTerm() { double x = parseFactor(); + for (; ; ) { - if (eat('*')) x *= parseFactor(); // multiplication - else if (eat('/')) x /= parseFactor(); // division - else return x; + if (eat('*')) { // multiplication + x *= parseFactor(); + } else if (eat('/')) { // division + x /= parseFactor(); + } else { + return x; + } } } private double parseFactor() { - if (eat('+')) return parseFactor(); // unary plus - if (eat('-')) return -parseFactor(); // unary minus + if (eat('+')) { + return parseFactor(); // unary plus + } + if (eat('-')) { + return -parseFactor(); // unary minus + } double x; int startPos = this.pos; @@ -65,22 +86,37 @@ public class Eval { x = parseExpression(); eat(')'); } else if ((ch >= '0' && ch <= '9') || ch == '.') { // numbers - while ((ch >= '0' && ch <= '9') || ch == '.') nextChar(); + while ((ch >= '0' && ch <= '9') || ch == '.') { + nextChar(); + } + x = Double.parseDouble(toParse.substring(startPos, this.pos)); } else if (ch >= 'a' && ch <= 'z') { // functions - while (ch >= 'a' && ch <= 'z') nextChar(); + while (ch >= 'a' && ch <= 'z') { + nextChar(); + } + String func = toParse.substring(startPos, this.pos); x = parseFactor(); - if (func.equals("sqrt")) x = Math.sqrt(x); - else if (func.equals("sin")) x = Math.sin(Math.toRadians(x)); - else if (func.equals("cos")) x = Math.cos(Math.toRadians(x)); - else if (func.equals("tan")) x = Math.tan(Math.toRadians(x)); - else throw new RuntimeException(warningMessage + "Unknown function: " + func); + + if (func.equals("sqrt")) { + x = Math.sqrt(x); + } else if (func.equals("sin")) { + x = Math.sin(Math.toRadians(x)); + } else if (func.equals("cos")) { + x = Math.cos(Math.toRadians(x)); + } else if (func.equals("tan")) { + x = Math.tan(Math.toRadians(x)); + } else { + throw new RuntimeException(warningMessage + "Unknown function: " + func); + } } else { throw new RuntimeException(warningMessage + "Unexpected: " + (char) ch); } - if (eat('^')) x = Math.pow(x, parseFactor()); // exponentiation + if (eat('^')) { + x = Math.pow(x, parseFactor()); // exponentiation + } return x; } diff --git a/Core/src/main/java/com/songoda/core/math/MathUtils.java b/Core/src/main/java/com/songoda/core/math/MathUtils.java index 4b174229..2c3a5d4d 100644 --- a/Core/src/main/java/com/songoda/core/math/MathUtils.java +++ b/Core/src/main/java/com/songoda/core/math/MathUtils.java @@ -4,7 +4,6 @@ import java.util.HashMap; import java.util.Map; public class MathUtils { - private static final Map cache = new HashMap<>(); public static double eval(String toParse) { diff --git a/Core/src/main/java/com/songoda/core/nms/NmsManager.java b/Core/src/main/java/com/songoda/core/nms/NmsManager.java index 7b22fde3..32d87954 100644 --- a/Core/src/main/java/com/songoda/core/nms/NmsManager.java +++ b/Core/src/main/java/com/songoda/core/nms/NmsManager.java @@ -1,133 +1,133 @@ -package com.songoda.core.nms; - -import com.songoda.core.nms.anvil.AnvilCore; -import com.songoda.core.nms.nbt.NBTCore; -import com.songoda.core.nms.world.WorldCore; -import org.bukkit.Bukkit; - -import java.util.logging.Level; -import java.util.logging.Logger; - -public class NmsManager { - - private final static String serverPackagePath = Bukkit.getServer().getClass().getPackage().getName(); - private final static String serverPackageVersion = serverPackagePath.substring(serverPackagePath.lastIndexOf('.') + 1); - private final static AnvilCore anvil; - private final static NBTCore nbt; - private final static WorldCore world; - - static { - switch (serverPackageVersion) { - case "v1_8_R1": - anvil = new com.songoda.core.nms.v1_8_R1.anvil.AnvilCore(); - nbt = new com.songoda.core.nms.v1_8_R1.nbt.NBTCoreImpl(); - world = new com.songoda.core.nms.v1_8_R1.world.WorldCoreImpl(); - break; - case "v1_8_R2": - anvil = new com.songoda.core.nms.v1_8_R2.anvil.AnvilCore(); - nbt = new com.songoda.core.nms.v1_8_R2.nbt.NBTCoreImpl(); - world = new com.songoda.core.nms.v1_8_R2.world.WorldCoreImpl(); - break; - case "v1_8_R3": - anvil = new com.songoda.core.nms.v1_8_R3.anvil.AnvilCore(); - nbt = new com.songoda.core.nms.v1_8_R3.nbt.NBTCoreImpl(); - world = new com.songoda.core.nms.v1_8_R3.world.WorldCoreImpl(); - break; - case "v1_9_R1": - anvil = new com.songoda.core.nms.v1_9_R1.anvil.AnvilCore(); - nbt = new com.songoda.core.nms.v1_9_R1.nbt.NBTCoreImpl(); - world = new com.songoda.core.nms.v1_9_R1.world.WorldCoreImpl(); - break; - case "v1_9_R2": - anvil = new com.songoda.core.nms.v1_9_R2.anvil.AnvilCore(); - nbt = new com.songoda.core.nms.v1_9_R2.nbt.NBTCoreImpl(); - world = new com.songoda.core.nms.v1_9_R2.world.WorldCoreImpl(); - break; - case "v1_10_R1": - anvil = new com.songoda.core.nms.v1_10_R1.anvil.AnvilCore(); - nbt = new com.songoda.core.nms.v1_10_R1.nbt.NBTCoreImpl(); - world = new com.songoda.core.nms.v1_10_R1.world.WorldCoreImpl(); - break; - case "v1_11_R1": - anvil = new com.songoda.core.nms.v1_11_R1.anvil.AnvilCore(); - nbt = new com.songoda.core.nms.v1_11_R1.nbt.NBTCoreImpl(); - world = new com.songoda.core.nms.v1_11_R1.world.WorldCoreImpl(); - break; - case "v1_12_R1": - anvil = new com.songoda.core.nms.v1_12_R1.anvil.AnvilCore(); - nbt = new com.songoda.core.nms.v1_12_R1.nbt.NBTCoreImpl(); - world = new com.songoda.core.nms.v1_12_R1.world.WorldCoreImpl(); - break; - case "v1_13_R1": - anvil = new com.songoda.core.nms.v1_13_R1.anvil.AnvilCore(); - nbt = new com.songoda.core.nms.v1_13_R1.nbt.NBTCoreImpl(); - world = new com.songoda.core.nms.v1_13_R1.world.WorldCoreImpl(); - break; - case "v1_13_R2": - anvil = new com.songoda.core.nms.v1_13_R2.anvil.AnvilCore(); - nbt = new com.songoda.core.nms.v1_13_R2.nbt.NBTCoreImpl(); - world = new com.songoda.core.nms.v1_13_R2.world.WorldCoreImpl(); - break; - case "v1_14_R1": - anvil = new com.songoda.core.nms.v1_14_R1.anvil.AnvilCore(); - nbt = new com.songoda.core.nms.v1_14_R1.nbt.NBTCoreImpl(); - world = new com.songoda.core.nms.v1_14_R1.world.WorldCoreImpl(); - break; - case "v1_15_R1": - anvil = new com.songoda.core.nms.v1_15_R1.anvil.AnvilCore(); - nbt = new com.songoda.core.nms.v1_15_R1.nbt.NBTCoreImpl(); - world = new com.songoda.core.nms.v1_15_R1.world.WorldCoreImpl(); - break; - case "v1_16_R1": - anvil = new com.songoda.core.nms.v1_16_R1.anvil.AnvilCore(); - nbt = new com.songoda.core.nms.v1_16_R1.nbt.NBTCoreImpl(); - world = new com.songoda.core.nms.v1_16_R1.world.WorldCoreImpl(); - break; - case "v1_16_R2": - anvil = new com.songoda.core.nms.v1_16_R2.anvil.AnvilCore(); - nbt = new com.songoda.core.nms.v1_16_R2.nbt.NBTCoreImpl(); - world = new com.songoda.core.nms.v1_16_R2.world.WorldCoreImpl(); - break; - case "v1_16_R3": - anvil = new com.songoda.core.nms.v1_16_R3.anvil.AnvilCore(); - nbt = new com.songoda.core.nms.v1_16_R3.nbt.NBTCoreImpl(); - world = new com.songoda.core.nms.v1_16_R3.world.WorldCoreImpl(); - break; - case "v1_17_R1": - anvil = new com.songoda.core.nms.v1_17_R1.anvil.AnvilCore(); - nbt = new com.songoda.core.nms.v1_17_R1.nbt.NBTCoreImpl(); - world = new com.songoda.core.nms.v1_17_R1.world.WorldCoreImpl(); - break; - default: - Logger.getLogger(NmsManager.class.getName()).log(Level.SEVERE, "Failed to load NMS for this server version: version {0} not found", serverPackageVersion); - anvil = null; - nbt = null; - world = null; - break; - } - } - - public static AnvilCore getAnvil() { - return anvil; - } - - public static boolean hasAnvil() { - return anvil != null; - } - - public static NBTCore getNbt() { - return nbt; - } - - public static boolean hasNbt() { - return nbt != null; - } - - public static WorldCore getWorld() { - return world; - } - - public static boolean hasWorld() { - return world != null; - } -} +package com.songoda.core.nms; + +import com.songoda.core.nms.anvil.AnvilCore; +import com.songoda.core.nms.nbt.NBTCore; +import com.songoda.core.nms.world.WorldCore; +import org.bukkit.Bukkit; + +import java.util.logging.Level; +import java.util.logging.Logger; + +public class NmsManager { + private final static String serverPackagePath = Bukkit.getServer().getClass().getPackage().getName(); + private final static String serverPackageVersion = serverPackagePath.substring(serverPackagePath.lastIndexOf('.') + 1); + private final static AnvilCore anvil; + private final static NBTCore nbt; + private final static WorldCore world; + + static { + switch (serverPackageVersion) { + case "v1_8_R1": + anvil = new com.songoda.core.nms.v1_8_R1.anvil.AnvilCore(); + nbt = new com.songoda.core.nms.v1_8_R1.nbt.NBTCoreImpl(); + world = new com.songoda.core.nms.v1_8_R1.world.WorldCoreImpl(); + break; + case "v1_8_R2": + anvil = new com.songoda.core.nms.v1_8_R2.anvil.AnvilCore(); + nbt = new com.songoda.core.nms.v1_8_R2.nbt.NBTCoreImpl(); + world = new com.songoda.core.nms.v1_8_R2.world.WorldCoreImpl(); + break; + case "v1_8_R3": + anvil = new com.songoda.core.nms.v1_8_R3.anvil.AnvilCore(); + nbt = new com.songoda.core.nms.v1_8_R3.nbt.NBTCoreImpl(); + world = new com.songoda.core.nms.v1_8_R3.world.WorldCoreImpl(); + break; + case "v1_9_R1": + anvil = new com.songoda.core.nms.v1_9_R1.anvil.AnvilCore(); + nbt = new com.songoda.core.nms.v1_9_R1.nbt.NBTCoreImpl(); + world = new com.songoda.core.nms.v1_9_R1.world.WorldCoreImpl(); + break; + case "v1_9_R2": + anvil = new com.songoda.core.nms.v1_9_R2.anvil.AnvilCore(); + nbt = new com.songoda.core.nms.v1_9_R2.nbt.NBTCoreImpl(); + world = new com.songoda.core.nms.v1_9_R2.world.WorldCoreImpl(); + break; + case "v1_10_R1": + anvil = new com.songoda.core.nms.v1_10_R1.anvil.AnvilCore(); + nbt = new com.songoda.core.nms.v1_10_R1.nbt.NBTCoreImpl(); + world = new com.songoda.core.nms.v1_10_R1.world.WorldCoreImpl(); + break; + case "v1_11_R1": + anvil = new com.songoda.core.nms.v1_11_R1.anvil.AnvilCore(); + nbt = new com.songoda.core.nms.v1_11_R1.nbt.NBTCoreImpl(); + world = new com.songoda.core.nms.v1_11_R1.world.WorldCoreImpl(); + break; + case "v1_12_R1": + anvil = new com.songoda.core.nms.v1_12_R1.anvil.AnvilCore(); + nbt = new com.songoda.core.nms.v1_12_R1.nbt.NBTCoreImpl(); + world = new com.songoda.core.nms.v1_12_R1.world.WorldCoreImpl(); + break; + case "v1_13_R1": + anvil = new com.songoda.core.nms.v1_13_R1.anvil.AnvilCore(); + nbt = new com.songoda.core.nms.v1_13_R1.nbt.NBTCoreImpl(); + world = new com.songoda.core.nms.v1_13_R1.world.WorldCoreImpl(); + break; + case "v1_13_R2": + anvil = new com.songoda.core.nms.v1_13_R2.anvil.AnvilCore(); + nbt = new com.songoda.core.nms.v1_13_R2.nbt.NBTCoreImpl(); + world = new com.songoda.core.nms.v1_13_R2.world.WorldCoreImpl(); + break; + case "v1_14_R1": + anvil = new com.songoda.core.nms.v1_14_R1.anvil.AnvilCore(); + nbt = new com.songoda.core.nms.v1_14_R1.nbt.NBTCoreImpl(); + world = new com.songoda.core.nms.v1_14_R1.world.WorldCoreImpl(); + break; + case "v1_15_R1": + anvil = new com.songoda.core.nms.v1_15_R1.anvil.AnvilCore(); + nbt = new com.songoda.core.nms.v1_15_R1.nbt.NBTCoreImpl(); + world = new com.songoda.core.nms.v1_15_R1.world.WorldCoreImpl(); + break; + case "v1_16_R1": + anvil = new com.songoda.core.nms.v1_16_R1.anvil.AnvilCore(); + nbt = new com.songoda.core.nms.v1_16_R1.nbt.NBTCoreImpl(); + world = new com.songoda.core.nms.v1_16_R1.world.WorldCoreImpl(); + break; + case "v1_16_R2": + anvil = new com.songoda.core.nms.v1_16_R2.anvil.AnvilCore(); + nbt = new com.songoda.core.nms.v1_16_R2.nbt.NBTCoreImpl(); + world = new com.songoda.core.nms.v1_16_R2.world.WorldCoreImpl(); + break; + case "v1_16_R3": + anvil = new com.songoda.core.nms.v1_16_R3.anvil.AnvilCore(); + nbt = new com.songoda.core.nms.v1_16_R3.nbt.NBTCoreImpl(); + world = new com.songoda.core.nms.v1_16_R3.world.WorldCoreImpl(); + break; + case "v1_17_R1": + anvil = new com.songoda.core.nms.v1_17_R1.anvil.AnvilCore(); + nbt = new com.songoda.core.nms.v1_17_R1.nbt.NBTCoreImpl(); + world = new com.songoda.core.nms.v1_17_R1.world.WorldCoreImpl(); + break; + default: + Logger.getLogger(NmsManager.class.getName()).log(Level.SEVERE, "Failed to load NMS for this server version: version {0} not found", serverPackageVersion); + + anvil = null; + nbt = null; + world = null; + break; + } + } + + public static AnvilCore getAnvil() { + return anvil; + } + + public static boolean hasAnvil() { + return anvil != null; + } + + public static NBTCore getNbt() { + return nbt; + } + + public static boolean hasNbt() { + return nbt != null; + } + + public static WorldCore getWorld() { + return world; + } + + public static boolean hasWorld() { + return world != null; + } +} diff --git a/Core/src/main/java/com/songoda/core/utils/BlockUtils.java b/Core/src/main/java/com/songoda/core/utils/BlockUtils.java index 7c5221b7..cd2d69e8 100644 --- a/Core/src/main/java/com/songoda/core/utils/BlockUtils.java +++ b/Core/src/main/java/com/songoda/core/utils/BlockUtils.java @@ -18,7 +18,6 @@ import java.util.logging.Level; import java.util.logging.Logger; public class BlockUtils { - protected static final Set DOORS; protected static final Set PRESSURE_PLATES; protected static final Set FENCE_GATES; @@ -52,7 +51,7 @@ public class BlockUtils { try { //legacyUpdateBlockData = Block.class.getDeclaredMethod("update"); legacySetBlockData = Block.class.getDeclaredMethod("setData", byte.class); - } catch (NoSuchMethodException ex) { + } catch (NoSuchMethodException ignore) { } } } @@ -66,6 +65,7 @@ public class BlockUtils { */ public static boolean tryInteract(Block b) { final Material bType = b.getType(); + if (isOpenable(bType)) { toggleDoorStates(true, b); return true; @@ -96,6 +96,7 @@ public class BlockUtils { private static void _updatePressurePlateLegacy(Block plate, int power) { final Material m = plate.getType(); + try { if (m.name().equals("GOLD_PLATE") || m.name().equals("IRON_PLATE")) { legacySetBlockData.invoke(plate, (byte) (power & 0x15)); @@ -125,7 +126,11 @@ public class BlockUtils { private static void _pressButtonLegacy(Block button) { final Material m = button.getType(); - if (!m.name().endsWith("_BUTTON")) return; + + if (!m.name().endsWith("_BUTTON")) { + return; + } + try { legacySetBlockData.invoke(button, (byte) (button.getData() | (31 & 0x8))); button.getState().update(); @@ -136,7 +141,11 @@ public class BlockUtils { private static void _releaseButtonLegacy(Block button) { final Material m = button.getType(); - if (!m.name().endsWith("_BUTTON")) return; + + if (!m.name().endsWith("_BUTTON")) { + return; + } + try { legacySetBlockData.invoke(button, (byte) (button.getData() & ~0x8)); button.getState().update(); @@ -155,7 +164,11 @@ public class BlockUtils { private static void _toggleLeverLegacy(Block lever) { final Material m = lever.getType(); - if (m != Material.LEVER) return; + + if (m != Material.LEVER) { + return; + } + try { legacySetBlockData.invoke(lever, (byte) (lever.getData() ^ 0x8)); lever.getState().update(); @@ -243,10 +256,6 @@ public class BlockUtils { /** * Get the double door for the given block - * - * @param block - * - * @return */ public static Block getDoubleDoor(Block block) { // TODO? if legacy, just search N/S/E/W to see if there's another door nearby @@ -258,9 +267,9 @@ public class BlockUtils { } public static boolean isOpenable(Material m) { - return DOORS.contains(m) - || FENCE_GATES.contains(m) - || TRAP_DOORS.contains(m); + return DOORS.contains(m) || + FENCE_GATES.contains(m) || + TRAP_DOORS.contains(m); } public static BlockFace getDoorClosedDirection(Block door) { @@ -269,8 +278,10 @@ public class BlockUtils { private static BlockFace _getDoorClosedDirectionLegacy(Block door) { final Material type = door.getType(); + if (DOORS.contains(type)) { boolean isTop = (door.getData() & 0x8) != 0; + if (isTop) { // The lower half of the door contains the direction & open/close state door = door.getRelative(BlockFace.DOWN); @@ -278,7 +289,9 @@ public class BlockUtils { return null; } } + boolean isOpen = (door.getData() & 0x4) != 0; + //int facing = (door.getData() & 0x3); // [east, south, west, north] boolean facingNS = (door.getData() & 0x1) != 0; @@ -289,6 +302,7 @@ public class BlockUtils { } } else if (FENCE_GATES.contains(door.getType())) { boolean isOpen = (door.getData() & 0x4) != 0; + //int facing = (door.getData() & 0x3); // so fence gate orientations are [south, west, north, east] boolean facingNS = (door.getData() & 0x1) == 0; @@ -299,6 +313,7 @@ public class BlockUtils { } } else if (TRAP_DOORS.contains(door.getType())) { boolean isOpen = (door.getData() & 0x4) != 0; + // [south, north, east, west] boolean facingNS = (door.getData() & 0x3) <= 1; if (facingNS) { @@ -307,6 +322,7 @@ public class BlockUtils { return isOpen ? BlockFace.SOUTH : BlockFace.EAST; } } + return null; } @@ -319,7 +335,10 @@ public class BlockUtils { * @param location location of the container */ public static void updateAdjacentComparators(Location location) { - if (location == null || location.getWorld() == null) return; + if (location == null || location.getWorld() == null) { + return; + } + try { // Cache reflection. if (clazzCraftWorld == null) { @@ -347,8 +366,8 @@ public class BlockUtils { .invoke(world, clazzBlockPosition.getConstructor(double.class, double.class, double.class) .newInstance(location.getX(), location.getY(), location.getZ()), nmsBlockData_getBlock.invoke(craftBlock_getNMS.invoke(craftBlock))); - } catch (ReflectiveOperationException e) { - e.printStackTrace(); + } catch (ReflectiveOperationException ex) { + ex.printStackTrace(); } } @@ -361,13 +380,6 @@ public class BlockUtils { *

* The chunk must be loaded and players must relog if they have the * chunk loaded in order to use this method. - * - * @param world - * @param x - * @param y - * @param z - * @param material - * @param data */ public static void setBlockFast(World world, int x, int y, int z, Material material, byte data) { try { @@ -408,8 +420,8 @@ public class BlockUtils { Object IBlockData = getByCombinedId.invoke(null, material.getId() + (data << 12)); setType.invoke(chunk, blockPosition, IBlockData); } - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } } @@ -427,16 +439,19 @@ public class BlockUtils { public static boolean isCropFullyGrown(Block block) { if (block == null) { return false; - } else if (!useLegacy) { + } + + if (!useLegacy) { return BlockUtilsModern._isCropFullyGrown(block); } + CompatibleMaterial mat = CompatibleMaterial.getBlockMaterial(block.getType()); if (mat == null || !mat.isCrop()) { return false; - } else { - return block.getData() >= (mat == CompatibleMaterial.BEETROOTS - || mat == CompatibleMaterial.NETHER_WART ? 3 : 7); } + + return block.getData() >= (mat == CompatibleMaterial.BEETROOTS + || mat == CompatibleMaterial.NETHER_WART ? 3 : 7); } /** @@ -449,16 +464,19 @@ public class BlockUtils { public static int getMaxGrowthStage(Block block) { if (block == null) { return -1; - } else if (!useLegacy) { + } + + if (!useLegacy) { return BlockUtilsModern._getMaxGrowthStage(block); } + CompatibleMaterial mat = CompatibleMaterial.getBlockMaterial(block.getType()); if (mat == null || !mat.isCrop()) { return -1; - } else { - return (mat == CompatibleMaterial.BEETROOTS - || mat == CompatibleMaterial.NETHER_WART ? 3 : 7); } + + return (mat == CompatibleMaterial.BEETROOTS + || mat == CompatibleMaterial.NETHER_WART ? 3 : 7); } /** @@ -471,16 +489,19 @@ public class BlockUtils { public static int getMaxGrowthStage(Material material) { if (material == null) { return -1; - } else if (!useLegacy) { + } + + if (!useLegacy) { return BlockUtilsModern._getMaxGrowthStage(material); } + CompatibleMaterial mat = CompatibleMaterial.getBlockMaterial(material); if (mat == null || !mat.isCrop()) { return -1; - } else { - return (mat == CompatibleMaterial.BEETROOTS - || mat == CompatibleMaterial.NETHER_WART ? 3 : 7); } + + return (mat == CompatibleMaterial.BEETROOTS + || mat == CompatibleMaterial.NETHER_WART ? 3 : 7); } /** @@ -517,8 +538,9 @@ public class BlockUtils { BlockUtilsModern._incrementGrowthStage(block); } else { CompatibleMaterial mat = CompatibleMaterial.getBlockMaterial(block.getType()); - if (mat != null && mat.isCrop() && block.getData() < (mat == CompatibleMaterial.BEETROOTS - || mat == CompatibleMaterial.NETHER_WART ? 3 : 7)) { + + if (mat != null && mat.isCrop() && + block.getData() < (mat == CompatibleMaterial.BEETROOTS || mat == CompatibleMaterial.NETHER_WART ? 3 : 7)) { try { legacySetBlockData.invoke(block, (byte) (block.getData() + 1)); } catch (Exception ex) { @@ -539,6 +561,7 @@ public class BlockUtils { BlockUtilsModern._resetGrowthStage(block); } else { CompatibleMaterial mat = CompatibleMaterial.getBlockMaterial(block.getType()); + if (mat != null && mat.isCrop()) { try { legacySetBlockData.invoke(block, (byte) 0); @@ -557,7 +580,6 @@ public class BlockUtils { * @return true if this material doesn't have a solid hitbox */ public static boolean canPassThrough(Material m) { - switch (m.name()) { case "ACACIA_BUTTON": case "ACACIA_PRESSURE_PLATE": @@ -731,6 +753,7 @@ public class BlockUtils { case "BEETROOT_BLOCK": return true; } + return false; } @@ -1064,6 +1087,7 @@ public class BlockUtils { case "BEETROOT_BLOCK": return true; } + return false; } } diff --git a/Core/src/main/java/com/songoda/core/utils/BlockUtilsModern.java b/Core/src/main/java/com/songoda/core/utils/BlockUtilsModern.java index a604845a..2bfbb371 100644 --- a/Core/src/main/java/com/songoda/core/utils/BlockUtilsModern.java +++ b/Core/src/main/java/com/songoda/core/utils/BlockUtilsModern.java @@ -22,24 +22,27 @@ import java.util.logging.Level; import java.util.logging.Logger; public class BlockUtilsModern { - protected static void _updatePressurePlateModern(Block plate, int power) { BlockData blockData = plate.getBlockData(); boolean update = false; + if (blockData instanceof AnaloguePowerable) { AnaloguePowerable a = (AnaloguePowerable) blockData; int toPower = Math.min(a.getMaximumPower(), power); + if ((update = toPower != a.getPower())) { a.setPower(toPower); plate.setBlockData(a); } } else if (blockData instanceof Powerable) { Powerable p = (Powerable) blockData; + if ((update = p.isPowered() != (power != 0))) { p.setPowered(power != 0); plate.setBlockData(p); } } + if (update) { _updateRedstoneNeighbours(plate); } @@ -47,6 +50,7 @@ public class BlockUtilsModern { protected static void _toggleLeverModern(Block lever) { BlockData blockData = lever.getBlockData(); + if (blockData instanceof Switch) { Switch s = (Switch) blockData; s.setPowered(!s.isPowered()); @@ -57,6 +61,7 @@ public class BlockUtilsModern { protected static void _pressButtonModern(Block button) { BlockData blockData = button.getBlockData(); + if (blockData instanceof Switch) { Switch s = (Switch) blockData; s.setPowered(true); @@ -67,6 +72,7 @@ public class BlockUtilsModern { static void _releaseButtonModern(Block button) { BlockData blockData = button.getBlockData(); + if (blockData instanceof Switch) { Switch s = (Switch) blockData; s.setPowered(false); @@ -86,7 +92,6 @@ public class BlockUtilsModern { static { try { // Cache reflection. - clazzCraftWorld = ClassMapping.CRAFT_WORLD.getClazz(); clazzCraftBlock = ClassMapping.CRAFT_BLOCK.getClazz(); @@ -198,6 +203,7 @@ public class BlockUtilsModern { // The lower half of the door contains the open/close state if (data.getHalf() == Bisected.Half.TOP) { Block lowerHalf = door.getRelative(BlockFace.DOWN); + if (lowerHalf.getBlockData() instanceof Door) { Door lowerData = (Door) lowerHalf.getBlockData(); lowerData.setOpen(!data.isOpen()); @@ -216,9 +222,11 @@ public class BlockUtilsModern { protected static Block _getDoubleDoorModern(Block block) { BlockData bd = block.getBlockData(); Block door = null; + if (bd instanceof Door) { final Door d = (Door) bd; final BlockFace face = d.getFacing(); + if (face.getModX() == 0) { if (d.getHinge() == Door.Hinge.RIGHT) { door = block.getRelative(face.getModZ(), 0, 0); @@ -233,6 +241,7 @@ public class BlockUtilsModern { } } } + return door != null && door.getBlockData() instanceof Door && ((Door) door.getBlockData()).getHinge() != ((Door) bd).getHinge() ? door : null; } @@ -240,12 +249,14 @@ public class BlockUtilsModern { protected static BlockFace _getDoorClosedDirectionModern(Block door) { if (BlockUtils.DOORS.contains(door.getType())) { BlockData bd = door.getBlockData(); + if (bd instanceof Door) { Door d = (Door) bd; // The lower half of the door contains the open/close state if (d.getHalf() == Bisected.Half.TOP) { door = door.getRelative(BlockFace.DOWN); + if (door.getBlockData() instanceof Door) { d = (Door) door.getBlockData(); } else { @@ -254,6 +265,7 @@ public class BlockUtilsModern { } final BlockFace face = d.getFacing(); + // now we /could/ also correct for the hinge (top block), it's not needed information if (face.getModX() == 0) { return d.isOpen() ? BlockFace.EAST : BlockFace.SOUTH; @@ -263,9 +275,11 @@ public class BlockUtilsModern { } } else if (BlockUtils.FENCE_GATES.contains(door.getType())) { BlockData bd = door.getBlockData(); + if (bd instanceof Gate) { Gate g = (Gate) bd; final BlockFace face = g.getFacing(); + if (face.getModX() == 0) { return g.isOpen() ? BlockFace.EAST : BlockFace.SOUTH; } else { @@ -274,8 +288,10 @@ public class BlockUtilsModern { } } else if (BlockUtils.TRAP_DOORS.contains(door.getType())) { BlockData bd = door.getBlockData(); + if (bd instanceof TrapDoor) { TrapDoor t = (TrapDoor) bd; + if (!t.isOpen()) { return BlockFace.UP; } else { @@ -283,35 +299,43 @@ public class BlockUtilsModern { } } } + return null; } protected static boolean _isCropFullyGrown(Block block) { BlockData data = block.getBlockData(); + if (data instanceof Ageable) { return ((Ageable) data).getAge() == ((Ageable) data).getMaximumAge(); } + return false; } protected static int _getMaxGrowthStage(Block block) { BlockData data = block.getBlockData(); + if (data instanceof Ageable) { return ((Ageable) data).getMaximumAge(); } + return -1; } protected static int _getMaxGrowthStage(Material material) { BlockData data = material.createBlockData(); + if (data instanceof Ageable) { return ((Ageable) data).getMaximumAge(); } + return -1; } public static void _setGrowthStage(Block block, int stage) { BlockData data = block.getBlockData(); + if (data instanceof Ageable) { ((Ageable) data).setAge(Math.max(0, Math.min(stage, ((Ageable) data).getMaximumAge()))); block.setBlockData(data); @@ -320,9 +344,11 @@ public class BlockUtilsModern { public static void _incrementGrowthStage(Block block) { BlockData data = block.getBlockData(); + if (data instanceof Ageable) { final int max = ((Ageable) data).getMaximumAge(); final int age = ((Ageable) data).getAge(); + if (age < max) { ((Ageable) data).setAge(age + 1); block.setBlockData(data); @@ -332,6 +358,7 @@ public class BlockUtilsModern { public static void _resetGrowthStage(Block block) { BlockData data = block.getBlockData(); + if (data instanceof Ageable) { ((Ageable) data).setAge(0); block.setBlockData(data); diff --git a/Core/src/main/java/com/songoda/core/utils/ColorUtils.java b/Core/src/main/java/com/songoda/core/utils/ColorUtils.java index 8c7455f1..dafebb9f 100644 --- a/Core/src/main/java/com/songoda/core/utils/ColorUtils.java +++ b/Core/src/main/java/com/songoda/core/utils/ColorUtils.java @@ -7,7 +7,6 @@ import java.util.Map; import java.util.TreeMap; public class ColorUtils { - private static Map> colorMap = new HashMap<>(); static { @@ -61,6 +60,7 @@ public class ColorUtils { int blue = Math.abs(b - set.getBlue()); closest.put(red + green + blue, color); }); + return closest.firstEntry().getValue(); } } diff --git a/Core/src/main/java/com/songoda/core/utils/EntityUtils.java b/Core/src/main/java/com/songoda/core/utils/EntityUtils.java index 904de5ec..4eb8abe2 100644 --- a/Core/src/main/java/com/songoda/core/utils/EntityUtils.java +++ b/Core/src/main/java/com/songoda/core/utils/EntityUtils.java @@ -14,7 +14,6 @@ import java.util.Collections; import java.util.List; public class EntityUtils { - private static Class clazzEntityInsentient, clazzEntity, clazzCraftEntity; private static Field aware, fromMobSpawner; @@ -27,17 +26,17 @@ public class EntityUtils { clazzEntity = ClassMapping.ENTITY.getClazz(); clazzCraftEntity = ClassMapping.CRAFT_ENTITY.getClazz(); methodGetHandle = clazzCraftEntity.getDeclaredMethod("getHandle"); - } catch (NoSuchMethodException e) { - e.printStackTrace(); + } catch (NoSuchMethodException ex) { + ex.printStackTrace(); } try { aware = clazzEntityInsentient.getField("aware"); - } catch (NoSuchFieldException e) { + } catch (NoSuchFieldException ex) { try { fromMobSpawner = clazzEntity.getField("fromMobSpawner"); - } catch (NoSuchFieldException ee) { - ee.printStackTrace(); + } catch (NoSuchFieldException ex2) { + ex2.printStackTrace(); } } } @@ -45,40 +44,44 @@ public class EntityUtils { public static void setUnaware(LivingEntity entity) { try { setUnaware(methodGetHandle.invoke(clazzCraftEntity.cast(entity))); - } catch (IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); + } catch (IllegalAccessException | InvocationTargetException ex) { + ex.printStackTrace(); } } public static void setUnaware(Object entity) { try { - if (aware != null) + if (aware != null) { aware.setBoolean(entity, false); - else + } else { fromMobSpawner.setBoolean(entity, true); - } catch (IllegalAccessException ee) { - ee.printStackTrace(); + } + } catch (IllegalAccessException ex) { + ex.printStackTrace(); } } public static boolean isAware(LivingEntity entity) { try { return isAware(methodGetHandle.invoke(clazzCraftEntity.cast(entity))); - } catch (IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); + } catch (IllegalAccessException | InvocationTargetException ex) { + ex.printStackTrace(); } + return false; } public static boolean isAware(Object entity) { try { - if (aware != null) + if (aware != null) { return aware.getBoolean(entity); - else + } else { return fromMobSpawner.getBoolean(entity); - } catch (IllegalAccessException ee) { - ee.printStackTrace(); + } + } catch (IllegalAccessException ex) { + ex.printStackTrace(); } + return false; } diff --git a/Core/src/main/java/com/songoda/core/utils/ItemSerializer.java b/Core/src/main/java/com/songoda/core/utils/ItemSerializer.java index 5384a465..d3bf6fc4 100644 --- a/Core/src/main/java/com/songoda/core/utils/ItemSerializer.java +++ b/Core/src/main/java/com/songoda/core/utils/ItemSerializer.java @@ -15,7 +15,6 @@ import java.util.List; * Class based off of https://gist.github.com/graywolf336/8153678 */ public class ItemSerializer { - /** * A method to serialize an {@link ItemStack} list to Base64 String. * @@ -32,14 +31,15 @@ public class ItemSerializer { dataOutput.writeInt(items.size()); // Save every element in the list - for (ItemStack item : items) + for (ItemStack item : items) { dataOutput.writeObject(item); + } // Serialize that array dataOutput.close(); return Base64Coder.encodeLines(outputStream.toByteArray()); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } return null; @@ -60,13 +60,15 @@ public class ItemSerializer { List items = new ArrayList<>(); // Read the serialized itemstack list - for (int i = 0; i < length; i++) + for (int i = 0; i < length; ++i) { items.add((ItemStack) dataInput.readObject()); + } dataInput.close(); + return items; - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } return null; @@ -81,10 +83,11 @@ public class ItemSerializer { */ public static ItemStack deserializeItem(byte[] data) { ItemStack item = null; + try (BukkitObjectInputStream stream = new BukkitObjectInputStream(new ByteArrayInputStream(data))) { item = (ItemStack) stream.readObject(); - } catch (IOException | ClassNotFoundException e) { - e.printStackTrace(); + } catch (IOException | ClassNotFoundException ex) { + ex.printStackTrace(); } return item; @@ -100,9 +103,10 @@ public class ItemSerializer { public static byte[] serializeItem(ItemStack item) { try (ByteArrayOutputStream stream = new ByteArrayOutputStream(); BukkitObjectOutputStream bukkitStream = new BukkitObjectOutputStream(stream)) { bukkitStream.writeObject(item); + return stream.toByteArray(); - } catch (IOException e) { - e.printStackTrace(); + } catch (IOException ex) { + ex.printStackTrace(); } return null; diff --git a/Core/src/main/java/com/songoda/core/utils/ItemUtils.java b/Core/src/main/java/com/songoda/core/utils/ItemUtils.java index f0c48bba..19507cd3 100644 --- a/Core/src/main/java/com/songoda/core/utils/ItemUtils.java +++ b/Core/src/main/java/com/songoda/core/utils/ItemUtils.java @@ -41,7 +41,6 @@ import java.util.logging.Logger; import java.util.stream.Stream; public class ItemUtils { - static boolean can_getI18NDisplayName = true; static { @@ -55,9 +54,9 @@ public class ItemUtils { public static String getItemName(ItemStack it) { if (it == null) { return null; - } else { - return itemName(it.getType()); } + + return itemName(it.getType()); } static String itemName(Material mat) { @@ -66,10 +65,12 @@ public class ItemUtils { Stream.of(matName.split(" ")).forEach(s -> { s = s.toLowerCase(); + if (s.equals("of")) { titleCase.append(s).append(" "); } else { char[] str = s.toCharArray(); + str[0] = Character.toUpperCase(str[0]); titleCase.append(new String(str)).append(" "); } @@ -89,12 +90,13 @@ public class ItemUtils { methodAsBukkitCopy = clazzCraftItemStack.getMethod("asBukkitCopy", clazzItemStack); methodAsNMSCopy = clazzCraftItemStack.getMethod("asNMSCopy", ItemStack.class); - if (ServerVersion.isServerVersion(ServerVersion.V1_8)) + if (ServerVersion.isServerVersion(ServerVersion.V1_8)) { methodA = clazzEnchantmentManager.getMethod("a", Random.class, clazzItemStack, int.class); - else + } else { methodA = clazzEnchantmentManager.getMethod("a", Random.class, clazzItemStack, int.class, boolean.class); - } catch (NoSuchMethodException e) { - e.printStackTrace(); + } + } catch (NoSuchMethodException ex) { + ex.printStackTrace(); } } @@ -102,15 +104,17 @@ public class ItemUtils { try { Object nmsItemStack = methodAsNMSCopy.invoke(null, item); - if (ServerVersion.isServerVersion(ServerVersion.V1_8)) + if (ServerVersion.isServerVersion(ServerVersion.V1_8)) { nmsItemStack = methodA.invoke(null, new Random(), nmsItemStack, level); - else + } else { nmsItemStack = methodA.invoke(null, new Random(), nmsItemStack, level, false); + } item = (ItemStack) methodAsBukkitCopy.invoke(null, nmsItemStack); - } catch (IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); + } catch (IllegalAccessException | InvocationTargetException ex) { + ex.printStackTrace(); } + return item; } @@ -119,12 +123,18 @@ public class ItemUtils { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); dataOutput.writeInt(items.length); - for (ItemStack item : items) dataOutput.writeObject(item); + + for (ItemStack item : items) { + dataOutput.writeObject(item); + } + dataOutput.close(); + return Base64Coder.encodeLines(outputStream.toByteArray()); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } + return null; } @@ -133,13 +143,18 @@ public class ItemUtils { ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); ItemStack[] items = new ItemStack[dataInput.readInt()]; - for (int i = 0; i < items.length; i++) + + for (int i = 0; i < items.length; i++) { items[i] = (ItemStack) dataInput.readObject(); + } + dataInput.close(); + return items; - } catch (ClassNotFoundException | IOException e) { - e.printStackTrace(); + } catch (ClassNotFoundException | IOException ex) { + ex.printStackTrace(); } + return null; } @@ -154,22 +169,27 @@ public class ItemUtils { public static ItemStack getAsCopy(ItemStack item, int qty) { ItemStack clone = item.clone(); clone.setAmount(qty); + return clone; } public static boolean hasEnoughDurability(ItemStack tool, int requiredAmount) { - if (tool.getType().getMaxDurability() <= 1) + if (tool.getType().getMaxDurability() <= 1) { return true; + } + if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_13)) { - if (!tool.hasItemMeta() || !(tool.getItemMeta() instanceof Damageable)) + if (!tool.hasItemMeta() || !(tool.getItemMeta() instanceof Damageable)) { return true; + } Damageable damageable = (Damageable) tool.getItemMeta(); int durabilityRemaining = tool.getType().getMaxDurability() - damageable.getDamage(); + return durabilityRemaining > requiredAmount; - } else { - return tool.getDurability() + requiredAmount <= tool.getType().getMaxDurability(); } + + return tool.getDurability() + requiredAmount <= tool.getType().getMaxDurability(); } static Class cb_ItemStack = NMSUtils.getCraftClass("inventory.CraftItemStack"); @@ -225,42 +245,44 @@ public class ItemUtils { ItemMeta m = item.getItemMeta(); m.addItemFlags(ItemFlag.HIDE_ENCHANTS); item.setItemMeta(m); + return item; - } else { - // hack a fake enchant onto the item - // Confirmed works on 1.8, 1.9, 1.10 - // Does not work 1.11+ (minecraft ignores the glitched enchantment) - if (item != null && item.getType() != Material.AIR && cb_CraftItemStack_asCraftMirror != null) { - try { - Object nmsStack = cb_CraftItemStack_asNMSCopy.invoke(null, item); - Object tag = mc_ItemStack_getTag.invoke(nmsStack); - if (tag == null) { - tag = mc_NBTTagCompound.newInstance(); - } - // set to have a fake enchantment - Object enchantmentList = mc_NBTTagList.newInstance(); - /* - if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_13)) { - // Servers from 1.13 and up change the id to a string - Object fakeEnchantment = mc_NBTTagCompound.newInstance(); - mc_NBTTagCompound_setString.invoke(fakeEnchantment, "id", "glow:glow"); - mc_NBTTagCompound_setShort.invoke(fakeEnchantment, "lvl", (short) 0); - mc_NBTTagList_add.invoke(enchantmentList, fakeEnchantment); - } else if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_11)) { - // Servers from 1.11 and up require *something* in the enchantment field - Object fakeEnchantment = mc_NBTTagCompound.newInstance(); - mc_NBTTagCompound_setShort.invoke(fakeEnchantment, "id", (short) 245); - mc_NBTTagCompound_setShort.invoke(fakeEnchantment, "lvl", (short) 1); - mc_NBTTagList_add.invoke(enchantmentList, fakeEnchantment); - }//*/ - mc_NBTTagCompound_set.invoke(tag, "ench", enchantmentList); - mc_ItemStack_setTag.invoke(nmsStack, tag); - item = (ItemStack) cb_CraftItemStack_asCraftMirror.invoke(null, nmsStack); - } catch (Exception ex) { - Bukkit.getLogger().log(Level.SEVERE, "Failed to set glow enchantment on item: " + item, ex); + } + + // hack a fake enchant onto the item + // Confirmed works on 1.8, 1.9, 1.10 + // Does not work 1.11+ (minecraft ignores the glitched enchantment) + if (item != null && item.getType() != Material.AIR && cb_CraftItemStack_asCraftMirror != null) { + try { + Object nmsStack = cb_CraftItemStack_asNMSCopy.invoke(null, item); + Object tag = mc_ItemStack_getTag.invoke(nmsStack); + if (tag == null) { + tag = mc_NBTTagCompound.newInstance(); } + // set to have a fake enchantment + Object enchantmentList = mc_NBTTagList.newInstance(); + /* + if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_13)) { + // Servers from 1.13 and up change the id to a string + Object fakeEnchantment = mc_NBTTagCompound.newInstance(); + mc_NBTTagCompound_setString.invoke(fakeEnchantment, "id", "glow:glow"); + mc_NBTTagCompound_setShort.invoke(fakeEnchantment, "lvl", (short) 0); + mc_NBTTagList_add.invoke(enchantmentList, fakeEnchantment); + } else if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_11)) { + // Servers from 1.11 and up require *something* in the enchantment field + Object fakeEnchantment = mc_NBTTagCompound.newInstance(); + mc_NBTTagCompound_setShort.invoke(fakeEnchantment, "id", (short) 245); + mc_NBTTagCompound_setShort.invoke(fakeEnchantment, "lvl", (short) 1); + mc_NBTTagList_add.invoke(enchantmentList, fakeEnchantment); + }//*/ + mc_NBTTagCompound_set.invoke(tag, "ench", enchantmentList); + mc_ItemStack_setTag.invoke(nmsStack, tag); + item = (ItemStack) cb_CraftItemStack_asCraftMirror.invoke(null, nmsStack); + } catch (Exception ex) { + Bukkit.getLogger().log(Level.SEVERE, "Failed to set glow enchantment on item: " + item, ex); } } + return item; } @@ -274,12 +296,14 @@ public class ItemUtils { public static ItemStack removeGlow(ItemStack item) { if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_11)) { item.removeEnchantment(Enchantment.DURABILITY); + return item; } else { if (item != null && item.getType() != Material.AIR && cb_CraftItemStack_asCraftMirror != null) { try { Object nmsStack = cb_CraftItemStack_asNMSCopy.invoke(null, item); Object tag = mc_ItemStack_getTag.invoke(nmsStack); + if (tag != null) { // remove enchantment list mc_NBTTagCompound_remove.invoke(tag, "ench"); @@ -291,6 +315,7 @@ public class ItemUtils { } } } + return item; } @@ -304,7 +329,7 @@ public class ItemUtils { mc_Item_getItem = mc_ItemStack.getDeclaredMethod("getItem"); mc_Item_maxStackSize = mc_Item.getDeclaredField("maxStackSize"); mc_Item_maxStackSize.setAccessible(true); - } catch (Exception ex) { + } catch (Exception ignore) { } } } @@ -314,10 +339,11 @@ public class ItemUtils { try { Object objItemStack = mc_Item_getItem.invoke(cb_CraftItemStack_asNMSCopy.invoke(null, item)); mc_Item_maxStackSize.set(objItemStack, max); - } catch (ReflectiveOperationException e) { - Bukkit.getLogger().log(Level.SEVERE, "Failed to set max stack size on item " + item, e); + } catch (ReflectiveOperationException ex) { + Bukkit.getLogger().log(Level.SEVERE, "Failed to set max stack size on item " + item, ex); } } + return item; } @@ -328,12 +354,15 @@ public class ItemUtils { } SkullMeta meta = (SkullMeta) head.getItemMeta(); + if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_13)) { meta.setOwningPlayer(player); } else { meta.setOwner(player.getName()); } + head.setItemMeta(meta); + return head; } @@ -341,7 +370,9 @@ public class ItemUtils { if (ServerVersion.isServerVersionBelow(ServerVersion.V1_8) || head == null || !CompatibleMaterial.PLAYER_HEAD.matches(head)) { return; } + SkullMeta meta = (SkullMeta) head.getItemMeta(); + if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_13)) { meta.setOwningPlayer(player); } else { @@ -355,17 +386,21 @@ public class ItemUtils { public static ItemStack getCustomHead(String signature, String texture) { ItemStack skullItem = CompatibleMaterial.PLAYER_HEAD.getItem(); - if (ServerVersion.isServerVersionBelow(ServerVersion.V1_8)) + + if (ServerVersion.isServerVersionBelow(ServerVersion.V1_8)) { return skullItem; + } SkullMeta sm = (SkullMeta) skullItem.getItemMeta(); GameProfile gm; if (texture.endsWith("=")) { gm = new GameProfile(UUID.nameUUIDFromBytes(texture.getBytes()), "CustomHead"); - if (signature == null) + + if (signature == null) { gm.getProperties().put("textures", new Property("texture", texture.replaceAll("=", ""))); - else + } else { gm.getProperties().put("textures", new Property("textures", texture, signature)); + } } else { gm = new GameProfile(UUID.nameUUIDFromBytes(texture.getBytes()), "CustomHead"); byte[] encodedData = Base64.getEncoder().encode(String.format("{textures:{SKIN:{url:\"http://textures.minecraft.net/texture/%s\"}}}", texture).getBytes()); @@ -378,6 +413,7 @@ public class ItemUtils { profileField.setAccessible(true); profileField.set(sm, gm); skullItem.setItemMeta(sm); + return skullItem; } catch (NoSuchFieldException | IllegalAccessException | SecurityException ex) { throw new RuntimeException("Reflection error while setting head texture", ex); @@ -390,7 +426,7 @@ public class ItemUtils { static { try { cb_CraftPlayer_getProfile = cb_CraftPlayer.getMethod("getProfile"); - } catch (Exception ex) { + } catch (Exception ignore) { } } @@ -398,35 +434,40 @@ public class ItemUtils { if (player == null || ServerVersion.isServerVersionBelow(ServerVersion.V1_8)) { return null; } - try { + try { Object craftPlayer = cb_CraftPlayer.cast(player); Iterator iterator = ((GameProfile) cb_CraftPlayer_getProfile.invoke(craftPlayer)).getProperties().get("textures").iterator(); return iterator.hasNext() ? iterator.next().getValue() : null; - } catch (IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); - return null; + } catch (IllegalAccessException | InvocationTargetException ex) { + ex.printStackTrace(); } + + return null; } public static String getSkullTexture(ItemStack item) { if (!CompatibleMaterial.PLAYER_HEAD.matches(item) || ServerVersion.isServerVersionBelow(ServerVersion.V1_8)) { return null; } + try { SkullMeta localSkullMeta = (SkullMeta) item.getItemMeta(); Field cb_SkullMeta_profile = localSkullMeta.getClass().getDeclaredField("profile"); - if (cb_SkullMeta_profile == null) return null; + if (cb_SkullMeta_profile == null) { + return null; + } cb_SkullMeta_profile.setAccessible(true); GameProfile profile = (GameProfile) cb_SkullMeta_profile.get(localSkullMeta); Iterator iterator = profile.getProperties().get("textures").iterator(); return iterator.hasNext() ? iterator.next().getValue() : null; - } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException ex) { + } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException ignore) { } + return null; } @@ -468,6 +509,7 @@ public class ItemUtils { */ public static boolean isSimilarMaterial(ItemStack is1, ItemStack is2) { CompatibleMaterial mat1 = CompatibleMaterial.getMaterial(is1); + return mat1 != null && mat1 == CompatibleMaterial.getMaterial(is2); } @@ -491,12 +533,14 @@ public class ItemUtils { final ItemMeta itemMeta = item.getItemMeta(); for (ItemStack stack : inventory) { final ItemMeta stackMeta; + if (isSimilarMaterial(stack, item) && (stack.getAmount() + item.getAmount()) < stack.getMaxStackSize() && ((itemMeta == null) == ((stackMeta = stack.getItemMeta()) == null)) && (itemMeta == null || Bukkit.getItemFactory().equals(itemMeta, stackMeta))) { return true; } } + return false; } @@ -514,11 +558,13 @@ public class ItemUtils { */ public static boolean canMove(ItemStack[] contents, ItemStack item) { final ItemMeta itemMeta = item.getItemMeta(); - for (int i = 0; i < contents.length; i++) { + + for (int i = 0; i < contents.length; ++i) { final ItemStack stack = contents[i]; if (stack == null || stack.getAmount() == 0) { return true; } + final ItemMeta stackMeta; if (isSimilarMaterial(stack, item) && (stack.getAmount() + item.getAmount()) < stack.getMaxStackSize() && ((itemMeta == null) == ((stackMeta = stack.getItemMeta()) == null)) @@ -526,6 +572,7 @@ public class ItemUtils { return true; } } + return false; } @@ -545,12 +592,15 @@ public class ItemUtils { public static boolean canMoveReserved(Inventory inventory, ItemStack item, int reserved) { final ItemMeta itemMeta = item.getItemMeta(); final ItemStack[] contents = inventory.getContents(); - for (int i = 0; i < contents.length; i++) { + + for (int i = 0; i < contents.length; ++i) { if (i == reserved) { continue; } + final ItemStack stack = contents[i]; final ItemMeta stackMeta; + if (stack == null || stack.getAmount() == 0 || (isSimilarMaterial(stack, item) && (stack.getAmount() + item.getAmount()) < stack.getMaxStackSize() && ((itemMeta == null) == ((stackMeta = stack.getItemMeta()) == null)) @@ -558,6 +608,7 @@ public class ItemUtils { return true; } } + return false; } @@ -576,14 +627,18 @@ public class ItemUtils { */ public static boolean canMoveReserved(ItemStack[] contents, ItemStack item, int reserved) { final ItemMeta itemMeta = item.getItemMeta(); - for (int i = 0; i < contents.length; i++) { + + for (int i = 0; i < contents.length; ++i) { if (i == reserved) { continue; } + final ItemStack stack = contents[i]; + if (stack == null || stack.getAmount() == 0) { return true; } + final ItemMeta stackMeta; if (isSimilarMaterial(stack, item) && (stack.getAmount() + item.getAmount()) < stack.getMaxStackSize() && ((itemMeta == null) == ((stackMeta = stack.getItemMeta()) == null)) @@ -591,6 +646,7 @@ public class ItemUtils { return true; } } + return false; } @@ -621,34 +677,42 @@ public class ItemUtils { */ public static int addAny(ItemStack item, int amountToAdd, List inventory, int maxSize, int reserved) { int totalAdded = 0; + if (inventory != null && item != null && amountToAdd > 0) { final int maxStack = item.getMaxStackSize(); - for (int i = 0; amountToAdd > 0 && i < maxSize; i++) { + + for (int i = 0; amountToAdd > 0 && i < maxSize; ++i) { if (i == reserved) { continue; } + final ItemStack cacheItem = i >= inventory.size() ? null : inventory.get(i); if (cacheItem == null || cacheItem.getAmount() == 0) { // free slot! int toAdd = Math.min(maxStack, amountToAdd); ItemStack item2 = item.clone(); item2.setAmount(toAdd); + if (i >= inventory.size()) { inventory.add(item2); } else { inventory.set(i, item2); } + totalAdded += toAdd; amountToAdd -= toAdd; } else if (maxStack > cacheItem.getAmount() && item.isSimilar(cacheItem)) { // free space! int toAdd = Math.min(maxStack - cacheItem.getAmount(), amountToAdd); + inventory.get(i).setAmount(toAdd + cacheItem.getAmount()); + totalAdded += toAdd; amountToAdd -= toAdd; } } } + return totalAdded; } @@ -666,6 +730,7 @@ public class ItemUtils { if (inventory == null || item == null || item.getAmount() <= 0 || containerSize <= 0) { return false; } + return addItem(item, item.getAmount(), inventory, containerSize); } @@ -684,6 +749,7 @@ public class ItemUtils { if (inventory == null || item == null || item.getAmount() <= 0 || containerSize <= 0) { return false; } + return addItem(item, item.getAmount(), inventory, containerSize, reserved); } @@ -719,6 +785,7 @@ public class ItemUtils { if (inventory == null || item == null || amount <= 0 || inventorySource == null) { return false; } + boolean[] check = null; if (inventorySource != null && inventorySource != Material.AIR) { @@ -730,14 +797,15 @@ public class ItemUtils { // some destination containers have special conditions switch (inventorySource.name()) { case "BREWING_STAND": { - // first compile a list of what slots to check check = new boolean[5]; String typeStr = item.getType().name().toUpperCase(); + if (typeStr.contains("POTION") || typeStr.contains("BOTTLE")) { // potion bottles are the first three slots check[0] = check[1] = check[2] = true; } + // fuel in 5th position, input in 4th if (item.getType() == Material.BLAZE_POWDER) { check[4] = true; @@ -749,13 +817,12 @@ public class ItemUtils { case "BLAST_FURNACE": case "BURNING_FURNACE": case "FURNACE": { - check = new boolean[3]; boolean isFuel = !item.getType().name().contains("LOG") && CompatibleMaterial.getMaterial(item.getType()).isFuel(); + // fuel is 2nd slot, input is first if (isFuel) { - check[1] = true; } else { check[0] = true; @@ -771,18 +838,20 @@ public class ItemUtils { // we can reduce calls to ItemStack.isSimilar() by caching what cells to look at if (check == null) { check = new boolean[containerSize]; - for (int i = 0; toAdd > 0 && i < check.length; i++) { + for (int i = 0; toAdd > 0 && i < check.length; ++i) { check[i] = true; } } + if (reserved >= 0 && check.length < reserved) { check[reserved] = false; } // first verify that we can add this item - for (int i = 0; toAdd > 0 && i < containerSize; i++) { + for (int i = 0; toAdd > 0 && i < containerSize; ++i) { if (check[i]) { final ItemStack cacheItem = i >= inventory.size() ? null : inventory.get(i); + if (cacheItem == null || cacheItem.getAmount() == 0) { // free slot! toAdd -= Math.min(maxStack, toAdd); @@ -796,35 +865,44 @@ public class ItemUtils { } } } + if (toAdd <= 0) { // all good to add! toAdd = item.getAmount(); + for (int i = 0; toAdd > 0 && i < containerSize; i++) { if (!check[i]) { continue; } + final ItemStack cacheItem = i >= inventory.size() ? null : inventory.get(i); + if (cacheItem == null || cacheItem.getAmount() == 0) { // free slot! int adding = Math.min(maxStack, toAdd); ItemStack item2 = item.clone(); item2.setAmount(adding); + if (i >= inventory.size()) { inventory.add(item2); } else { inventory.set(i, item2); } + toAdd -= adding; } else if (maxStack > cacheItem.getAmount()) { // free space! // (no need to check item.isSimilar(cacheItem), since we have that cached in check[]) int adding = Math.min(maxStack - cacheItem.getAmount(), toAdd); + inventory.get(i).setAmount(adding + cacheItem.getAmount()); toAdd -= adding; } } + return true; } + return false; } @@ -839,28 +917,35 @@ public class ItemUtils { */ public static int addAny(ItemStack item, int amountToAdd, Inventory inventory) { int totalAdded = 0; + if (inventory != null && item != null && amountToAdd > 0) { final int containerSize = inventory.getSize(); final int maxStack = item.getMaxStackSize(); - for (int i = 0; amountToAdd > 0 && i < containerSize; i++) { + + for (int i = 0; amountToAdd > 0 && i < containerSize; ++i) { final ItemStack cacheItem = inventory.getItem(i); if (cacheItem == null || cacheItem.getAmount() == 0) { // free slot! int toAdd = Math.min(maxStack, amountToAdd); + ItemStack item2 = item.clone(); item2.setAmount(toAdd); inventory.setItem(i, item2); + totalAdded += toAdd; amountToAdd -= toAdd; } else if (maxStack > cacheItem.getAmount() && item.isSimilar(cacheItem)) { // free space! int toAdd = Math.min(maxStack - cacheItem.getAmount(), amountToAdd); + cacheItem.setAmount(toAdd + cacheItem.getAmount()); + totalAdded += toAdd; amountToAdd -= toAdd; } } } + return totalAdded; } @@ -876,6 +961,7 @@ public class ItemUtils { if (inventory == null || item == null || item.getAmount() <= 0) { return false; } + return addItem(item, item.getAmount(), inventory, -1, null); } @@ -908,10 +994,10 @@ public class ItemUtils { if (inventory == null || item == null || amount <= 0 || inventorySource == null) { return false; } + boolean[] check = null; if (inventorySource != null && inventorySource != Material.AIR) { - // Don't transfer shulker boxes into other shulker boxes, that's a bad idea. if (inventorySource.name().contains("SHULKER_BOX") && item.getType().name().contains("SHULKER_BOX")) { return false; @@ -920,14 +1006,15 @@ public class ItemUtils { // some destination containers have special conditions switch (inventorySource.name()) { case "BREWING_STAND": { - // first compile a list of what slots to check check = new boolean[5]; String typeStr = item.getType().name().toUpperCase(); + if (typeStr.contains("POTION") || typeStr.contains("BOTTLE")) { // potion bottles are the first three slots check[0] = check[1] = check[2] = true; } + // fuel in 5th position, input in 4th if (item.getType() == Material.BLAZE_POWDER) { check[4] = true; @@ -939,13 +1026,11 @@ public class ItemUtils { case "BLAST_FURNACE": case "BURNING_FURNACE": case "FURNACE": { - check = new boolean[3]; boolean isFuel = !item.getType().name().contains("LOG") && CompatibleMaterial.getMaterial(item.getType()).isFuel(); // fuel is 2nd slot, input is first if (isFuel) { - check[1] = true; } else { check[0] = true; @@ -953,6 +1038,7 @@ public class ItemUtils { } } } + // grab the amount to move and the max item stack size int toAdd = item.getAmount(); final int maxStack = item.getMaxStackSize(); @@ -961,7 +1047,8 @@ public class ItemUtils { // we can reduce calls to ItemStack.isSimilar() by caching what cells to look at if (check == null) { check = new boolean[containerSize]; - for (int i = 0; toAdd > 0 && i < check.length; i++) { + + for (int i = 0; toAdd > 0 && i < check.length; ++i) { check[i] = true; } } @@ -970,6 +1057,7 @@ public class ItemUtils { for (int i = 0; toAdd > 0 && i < containerSize; i++) { if (check[i]) { final ItemStack cacheItem = inventory.getItem(i); + if (cacheItem == null || cacheItem.getAmount() == 0) { // free slot! toAdd -= Math.min(maxStack, toAdd); @@ -983,13 +1071,15 @@ public class ItemUtils { } } } + if (toAdd <= 0) { // all good to add! toAdd = item.getAmount(); - for (int i = 0; toAdd > 0 && i < containerSize; i++) { + for (int i = 0; toAdd > 0 && i < containerSize; ++i) { if (!check[i]) { continue; } + final ItemStack cacheItem = inventory.getItem(i); if (cacheItem == null || cacheItem.getAmount() == 0) { // free slot! @@ -1006,8 +1096,10 @@ public class ItemUtils { toAdd -= adding; } } + return true; } + return false; } @@ -1044,6 +1136,7 @@ public class ItemUtils { case 'f': return CompatibleMaterial.WHITE_DYE; } + return CompatibleMaterial.STONE; } @@ -1101,17 +1194,20 @@ public class ItemUtils { if (!check[i]) { continue; } + final ItemStack cacheItem = i >= inventory.size() ? null : inventory.get(i); if (cacheItem == null || cacheItem.getAmount() == 0) { // free slot! int adding = Math.min(maxStack, toAdd); ItemStack item2 = item.clone(); item2.setAmount(adding); + if (i >= inventory.size()) { inventory.add(item2); } else { inventory.set(i, item2); } + toAdd -= adding; } else if (maxStack > cacheItem.getAmount()) { // free space! @@ -1121,8 +1217,10 @@ public class ItemUtils { toAdd -= adding; } } + return true; } + return false; } } diff --git a/Core/src/main/java/com/songoda/core/utils/LocationUtils.java b/Core/src/main/java/com/songoda/core/utils/LocationUtils.java index e80d0428..23e3ad3f 100644 --- a/Core/src/main/java/com/songoda/core/utils/LocationUtils.java +++ b/Core/src/main/java/com/songoda/core/utils/LocationUtils.java @@ -3,7 +3,6 @@ package com.songoda.core.utils; import org.bukkit.Location; public class LocationUtils { - public static boolean isLocationMatching(Location location1, Location location2) { return location1.getBlockX() == location2.getBlockX() && location1.getBlockY() == location2.getBlockY() && location1.getBlockZ() == location2.getBlockZ(); } diff --git a/Core/src/main/java/com/songoda/core/utils/Metrics.java b/Core/src/main/java/com/songoda/core/utils/Metrics.java index c403db19..f28cc90d 100644 --- a/Core/src/main/java/com/songoda/core/utils/Metrics.java +++ b/Core/src/main/java/com/songoda/core/utils/Metrics.java @@ -39,7 +39,6 @@ import java.util.zip.GZIPOutputStream; */ @SuppressWarnings({"WeakerAccess", "unused"}) public class Metrics { - static { // You can use the property to disable the check in your test environment if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) { diff --git a/Core/src/main/java/com/songoda/core/utils/NMSUtils.java b/Core/src/main/java/com/songoda/core/utils/NMSUtils.java index d8534a16..90f9fed0 100644 --- a/Core/src/main/java/com/songoda/core/utils/NMSUtils.java +++ b/Core/src/main/java/com/songoda/core/utils/NMSUtils.java @@ -8,21 +8,21 @@ import java.lang.reflect.Field; import java.lang.reflect.Method; public class NMSUtils { - public static Class getCraftClass(String className) { try { String fullName = "org.bukkit.craftbukkit." + ServerVersion.getServerVersionString() + "." + className; - Class clazz = Class.forName(fullName); - return clazz; - } catch (Exception e) { - e.printStackTrace(); - return null; + return Class.forName(fullName); + } catch (Exception ex) { + ex.printStackTrace(); } + + return null; } public static Method getPrivateMethod(Class c, String methodName, Class... parameters) throws Exception { Method m = c.getDeclaredMethod(methodName, parameters); m.setAccessible(true); + return m; } @@ -38,28 +38,31 @@ public class NMSUtils { field.setAccessible(true); return field; - } catch (Exception e) { - e.printStackTrace(); - return null; + } catch (Exception ex) { + ex.printStackTrace(); } + + return null; } public static Object getFieldObject(Object object, Field field) { try { return field.get(object); - } catch (Exception e) { - e.printStackTrace(); - return null; + } catch (Exception ex) { + ex.printStackTrace(); } + + return null; } public static void setField(Object object, String fieldName, Object fieldValue, boolean declared) { try { Field field = declared ? object.getClass().getDeclaredField(fieldName) : object.getClass().getField(fieldName); field.setAccessible(true); + field.set(object, fieldValue); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } } @@ -67,9 +70,10 @@ public class NMSUtils { try { Object handle = player.getClass().getMethod("getHandle").invoke(player); Object playerConnection = handle.getClass().getField(ServerVersion.isServerVersionAtLeast(ServerVersion.V1_17) ? "b" : "playerConnection").get(handle); + playerConnection.getClass().getMethod("sendPacket", ClassMapping.PACKET.getClazz()).invoke(playerConnection, packet); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } } } diff --git a/Core/src/main/java/com/songoda/core/utils/NumberUtils.java b/Core/src/main/java/com/songoda/core/utils/NumberUtils.java index d1e610fc..18805764 100644 --- a/Core/src/main/java/com/songoda/core/utils/NumberUtils.java +++ b/Core/src/main/java/com/songoda/core/utils/NumberUtils.java @@ -4,7 +4,6 @@ import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; public class NumberUtils { - public static String formatEconomy(char currencySymbol, double number) { return currencySymbol + formatNumber(number); } @@ -18,30 +17,40 @@ public class NumberUtils { symbols.setDecimalSeparator('.'); decimalFormatter.setDecimalFormatSymbols(symbols); + return decimalFormatter.format(number); } public static String formatWithSuffix(long count) { - if (count < 1000) return String.valueOf(count); + if (count < 1000) { + return String.valueOf(count); + } + int exp = (int) (Math.log(count) / Math.log(1000)); + return String.format("%.1f%c", count / Math.pow(1000, exp), "kMGTPE".charAt(exp - 1)).replace(".0", ""); } public static boolean isInt(String number) { - if (number == null || number.equals("")) - return false; - try { - Integer.parseInt(number); - } catch (NumberFormatException e) { + if (number == null || number.equals("")) { return false; } - return true; + + try { + Integer.parseInt(number); + return true; + } catch (NumberFormatException ignore) { + } + + return false; } public static boolean isNumeric(String s) { - if (s == null || s.equals("")) + if (s == null || s.equals("")) { return false; + } + return s.matches("[-+]?\\d*\\.?\\d+"); } } diff --git a/Core/src/main/java/com/songoda/core/utils/PlayerUtils.java b/Core/src/main/java/com/songoda/core/utils/PlayerUtils.java index 83d50118..17b20fbd 100644 --- a/Core/src/main/java/com/songoda/core/utils/PlayerUtils.java +++ b/Core/src/main/java/com/songoda/core/utils/PlayerUtils.java @@ -17,21 +17,22 @@ import java.util.Set; import java.util.stream.Collectors; public class PlayerUtils { - static Random random = new Random(); public static void sendMessages(Player player, String... messages) { - for (String message : messages) + for (String message : messages) { player.sendMessage(message); + } } public static void sendMessages(Player player, List messages) { - for (String message : messages) + for (String message : messages) { player.sendMessage(message); + } } /** - * Get a list of all of the players that this player can "see" + * Get a list of all the players that this player can "see" * * @param sender user to check against, or null for all players * @param startingWith optional query to test: only players whose game names @@ -42,6 +43,7 @@ public class PlayerUtils { public static List getVisiblePlayerNames(CommandSender sender, String startingWith) { Player player = sender instanceof Player ? (Player) sender : null; final String startsWith = startingWith == null || startingWith.isEmpty() ? null : startingWith.toLowerCase(); + return Bukkit.getOnlinePlayers().stream() .filter(p -> p != player) .filter(p -> startsWith == null || p.getName().toLowerCase().startsWith(startsWith)) @@ -62,6 +64,7 @@ public class PlayerUtils { public static List getVisiblePlayerDisplayNames(CommandSender sender, String startingWith) { Player player = sender instanceof Player ? (Player) sender : null; final String startsWith = startingWith == null || startingWith.isEmpty() ? null : startingWith.replaceAll("[^a-zA-Z]", "").toLowerCase(); + return Bukkit.getOnlinePlayers().stream() .filter(p -> p != player) .filter(p -> startsWith == null || p.getDisplayName().replaceAll("[^a-zA-Z]", "").toLowerCase().startsWith(startsWith)) @@ -71,7 +74,7 @@ public class PlayerUtils { } /** - * Get a list of all of the players that this player can "see" + * Get a list of all the players that this player can "see" * * @param sender user to check against, or null for all players * @param startingWith optional query to test: only players whose game names @@ -82,6 +85,7 @@ public class PlayerUtils { public static List getVisiblePlayers(CommandSender sender, String startingWith) { Player player = sender instanceof Player ? (Player) sender : null; final String startsWith = startingWith == null || startingWith.isEmpty() ? null : startingWith.toLowerCase(); + return Bukkit.getOnlinePlayers().stream() .filter(p -> p != player) .filter(p -> startsWith == null || p.getName().toLowerCase().startsWith(startsWith)) @@ -100,6 +104,7 @@ public class PlayerUtils { */ public static List getAllPlayers(CommandSender us, String startsWith) { final String arg = startsWith.toLowerCase(); + return Bukkit.getOnlinePlayers().stream() .filter(p -> us != p && p.getName().startsWith(arg)) .map(Player::getName) @@ -116,6 +121,7 @@ public class PlayerUtils { */ public static List getAllPlayersDisplay(CommandSender us, String startsWith) { final String arg = startsWith.replaceAll("[^a-zA-Z]", "").toLowerCase(); + return Bukkit.getOnlinePlayers().stream() .filter(p -> us != p && p.getDisplayName().replaceAll("[^a-zA-Z]", "").startsWith(arg)) .map(Player::getDisplayName) @@ -132,14 +138,17 @@ public class PlayerUtils { */ public static Player findPlayer(String player) { Player found = Bukkit.getServer().getPlayer(player); + if (found == null) { final String searchName = player.toLowerCase(); final String searchDisplayName = player.replaceAll("[^a-zA-Z]", "").toLowerCase(); int d = 999; + for (Player p2 : Bukkit.getOnlinePlayers()) { final String test; if (p2.getName().toLowerCase().startsWith(searchName)) { int d2 = p2.getName().length() - searchName.length(); + if (d2 < d) { found = p2; d = d2; @@ -148,6 +157,7 @@ public class PlayerUtils { } } else if ((test = p2.getDisplayName().replaceAll("[^a-zA-Z]", "")).toLowerCase().startsWith(searchDisplayName)) { int d2 = test.length() - searchDisplayName.length(); + if (d2 < d) { found = p2; d = d2; @@ -157,6 +167,7 @@ public class PlayerUtils { } } } + return found; } @@ -169,6 +180,7 @@ public class PlayerUtils { final Iterator alli = all.iterator(); int pick = random.nextInt(all.size()); + for (; pick > 0; --pick) { alli.next(); } @@ -180,7 +192,9 @@ public class PlayerUtils { if (player == null || !player.isOnline() || item == null) { return; } + Map leftover = player.getInventory().addItem(item); + if (!leftover.isEmpty()) { leftover.values().stream().forEach(it -> player.getWorld().dropItemNaturally(player.getLocation(), it)); } @@ -190,10 +204,12 @@ public class PlayerUtils { if (player == null || !player.isOnline() || items == null || items.length == 0) { return; } + Map leftover = player.getInventory().addItem(items); if (!leftover.isEmpty()) { final World world = player.getWorld(); final Location location = player.getLocation(); + leftover.values().stream().forEach(it -> world.dropItemNaturally(location, it)); } } @@ -202,7 +218,9 @@ public class PlayerUtils { if (player == null || !player.isOnline() || items == null || items.isEmpty()) { return; } + Map leftover = player.getInventory().addItem(items.toArray(new ItemStack[items.size()])); + if (!leftover.isEmpty()) { final World world = player.getWorld(); final Location location = player.getLocation(); @@ -217,17 +235,22 @@ public class PlayerUtils { int highest = 0; for (PermissionAttachmentInfo info : permissions) { - final String perm = info.getPermission(); - if (!perm.startsWith(permission)) continue; + if (!perm.startsWith(permission)) { + continue; + } final int index = perm.lastIndexOf('.'); - if (index == -1 || index == perm.length()) continue; + if (index == -1 || index == perm.length()) { + continue; + } String numStr = perm.substring(perm.lastIndexOf('.') + 1); - if (numStr.equals("*")) return def; + if (numStr.equals("*")) { + return def; + } final int number = Integer.parseInt(numStr); diff --git a/Core/src/main/java/com/songoda/core/utils/ReflectionUtils.java b/Core/src/main/java/com/songoda/core/utils/ReflectionUtils.java index e6b38c7a..61542a3c 100644 --- a/Core/src/main/java/com/songoda/core/utils/ReflectionUtils.java +++ b/Core/src/main/java/com/songoda/core/utils/ReflectionUtils.java @@ -30,16 +30,17 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class ReflectionUtils { - public final static double JAVA_VERSION = getVersion(); private static String system_os = System.getProperty("os.name").toLowerCase(); private static double getVersion() { String version = System.getProperty("java.version"); int i = version.indexOf('.'); + if (i != -1 && (i = version.indexOf('.', i + 1)) != -1) { return Double.parseDouble(version.substring(0, i)); } + return Double.NaN; } @@ -51,18 +52,21 @@ public class ReflectionUtils { public static void setPrivateField(Class c, Object handle, String fieldName, Object value) throws Exception { Field f = c.getDeclaredField(fieldName); f.setAccessible(true); + f.set(handle, value); } public static Object getPrivateField(Class c, Object handle, String fieldName) throws Exception { Field field = c.getDeclaredField(fieldName); field.setAccessible(true); + return field.get(handle); } public static Object invokePrivateMethod(Class c, String methodName, Object handle, Class[] types, Object[] parameters) throws Exception { Method m = c.getDeclaredMethod(methodName, types); m.setAccessible(true); + return m.invoke(handle, parameters); } @@ -83,6 +87,7 @@ public class ReflectionUtils { } catch (Exception ex) { j7getStackTraceElementMethod = j7getStackTraceDepthMethod = null; } + try { j8getJavaLangAccess = Class.forName("sun.misc.SharedSecrets").getDeclaredMethod("getStackTraceElement"); j8getJavaLangAccess.setAccessible(true); @@ -104,33 +109,39 @@ public class ReflectionUtils { if (j8getStackTraceElementMethod != null) { return (StackTraceElement) j8getStackTraceElementMethod.invoke(j8getJavaLangAccess.invoke(null), dummy, index); -// } else if (JAVA_VERSION >= 9) { + } + +// if (JAVA_VERSION >= 9) { // return StackWalker.getInstance(Collections.emptySet(), index + 1) // .walk(s -> s.skip(index).findFirst()) // .orElse(null); - } else if (j7getStackTraceElementMethod == null) { +// } + + if (j7getStackTraceElementMethod == null) { // better than nothing, right? :/ return (new Throwable()).getStackTrace()[index]; - } else { - if (index < (Integer) j7getStackTraceDepthMethod.invoke(dummy)) { - return (StackTraceElement) j7getStackTraceElementMethod.invoke(new Throwable(), index); - } else { - return null; - } } - } catch (Throwable t) { + + if (index < (Integer) j7getStackTraceDepthMethod.invoke(dummy)) { + return (StackTraceElement) j7getStackTraceElementMethod.invoke(new Throwable(), index); + } + } catch (Throwable ignore) { } + return null; } public static Map, T> getClassesInClassPackageByAnnotation(Class clazz, Class annotation) throws IOException { final Map, T> foundClasses = new HashMap<>(); + for (Class c : getAllClassesInClassPackage(clazz, false)) { T t = c.getAnnotation(annotation); + if (t != null) { foundClasses.put(c, t); } } + return foundClasses; } @@ -139,16 +150,20 @@ public class ReflectionUtils { final String clazzPackageName = clazz.getPackage().getName(); URL dot = clazz.getResource("."); + if (dot == null) { // jar file String packagePath = clazzPackageName.replace('.', '/'); CodeSource src = clazz.getProtectionDomain().getCodeSource(); + if (src != null) { URL jar = src.getLocation(); ZipInputStream zip = new ZipInputStream(jar.openStream()); + ZipEntry e; while ((e = zip.getNextEntry()) != null) { String name = e.getName(); + if (!name.endsWith("/") && name.startsWith(packagePath + "/")) { if (recursive || name.indexOf('/', packagePath.length() + 1) == -1) { try { @@ -161,46 +176,49 @@ public class ReflectionUtils { } } } - } else { - String clazzPath = clazz.getResource(".").getPath(); - if (clazzPath.startsWith("/") && system_os.contains("win")) { - clazzPath = clazzPath.substring(1); - } - Path packagePath = Paths.get(clazzPath); - Files.walkFileTree(packagePath, new SimpleFileVisitor() { - @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - String filename = file.getName(file.getNameCount() - 1).toString(); - - if (filename.endsWith(".class")) { - String className = filename.replace(".class", ""); - - try { - Class loadedClazz = Class.forName( - clazzPackageName + "." + className); - - packageClasses.add(loadedClazz); - } catch (ClassNotFoundException e) { - SongodaCore.getLogger().log(Level.FINE, "class not found: " + e.getMessage()); - } - } - return super.visitFile(file, attrs); - } - }); + return packageClasses; } + String clazzPath = clazz.getResource(".").getPath(); + if (clazzPath.startsWith("/") && system_os.contains("win")) { + clazzPath = clazzPath.substring(1); + } + Path packagePath = Paths.get(clazzPath); + + Files.walkFileTree(packagePath, new SimpleFileVisitor() { + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + String filename = file.getName(file.getNameCount() - 1).toString(); + + if (filename.endsWith(".class")) { + String className = filename.replace(".class", ""); + + try { + Class loadedClazz = Class.forName( + clazzPackageName + "." + className); + + packageClasses.add(loadedClazz); + } catch (ClassNotFoundException e) { + SongodaCore.getLogger().log(Level.FINE, "class not found: " + e.getMessage()); + } + } + + return super.visitFile(file, attrs); + } + }); + return packageClasses; } public static enum ITERATION { - NONE, CLASS, PACKAGE, FULL } public static List getClassNamesFromPackage(Class classInPackage) throws IOException, URISyntaxException, ClassNotFoundException { String classPath = classInPackage.getName(); int packageDelim = classPath.lastIndexOf('.'); + return getClassNamesFromPackage(getJarFile(classInPackage), classPath.substring(0, packageDelim), ITERATION.NONE); } @@ -264,29 +282,34 @@ public class ReflectionUtils { jf = new JarFile(jarFileName); jarEntries = jf.entries(); + // in case of multiple sub-classes, keep track of what classes have been searched ArrayList loaded = new ArrayList(); + while (jarEntries.hasMoreElements()) { entryName = jarEntries.nextElement().getName(); + if (entryName.startsWith(packageName) && entryName.length() > packageName.length() && entryName.toLowerCase().endsWith(".class")) { if (entryName.contains(".")) { entryName = entryName.substring(packageName.length() + 1, entryName.lastIndexOf('.')); } + // iteration test if (!entryName.contains("/") || (iterate == ITERATION.PACKAGE || iterate == ITERATION.FULL)) { - if (entryName.contains("$")) { // added - sub-package test // added - iteration if (iterate == ITERATION.CLASS || iterate == ITERATION.FULL) { entryName = entryName.substring(0, entryName.indexOf('$')).replace('/', '.'); if (!loaded.contains(entryName)) { loaded.add(entryName); + try { Class c = Class.forName(packageName.replace('/', '.') + "." + entryName); + for (Class c2 : c.getDeclaredClasses()) { names.add(entryName + "." + c2.getSimpleName()); } - } catch (Throwable t) { + } catch (Throwable ignore) { } } } @@ -302,22 +325,27 @@ public class ReflectionUtils { // loop through files in classpath URI uri = new URI(packageURL.toString()); File folder = new File(uri.getPath()); + // won't work with path which contains blank (%20) // File folder = new File(packageURL.getFile()); File[] contenuti = folder.listFiles(); + // in case of multiple sub-classes, keep track of what classes have been searched ArrayList loaded = new ArrayList(); + String entryName; for (File actual : contenuti) { entryName = actual.getName(); if (entryName.contains(".")) { // added - folder check entryName = entryName.substring(0, entryName.lastIndexOf('.')); + if (entryName.contains("$")) { // added - sub-package test // added - iteration if (iterate == ITERATION.CLASS || iterate == ITERATION.FULL) { entryName = entryName.substring(0, entryName.indexOf('$')); if (!loaded.contains(entryName)) { loaded.add(entryName); + Class c = Class.forName(packageName.replace('/', '.') + "." + entryName); for (Class c2 : c.getDeclaredClasses()) { names.add(entryName + "." + c2.getSimpleName()); @@ -335,6 +363,7 @@ public class ReflectionUtils { } } } + return names; } } diff --git a/Core/src/main/java/com/songoda/core/utils/RotationUtils.java b/Core/src/main/java/com/songoda/core/utils/RotationUtils.java index 33c80401..ec06c932 100644 --- a/Core/src/main/java/com/songoda/core/utils/RotationUtils.java +++ b/Core/src/main/java/com/songoda/core/utils/RotationUtils.java @@ -3,7 +3,6 @@ package com.songoda.core.utils; import org.bukkit.block.BlockFace; public class RotationUtils { - public static float faceToYaw(BlockFace face) { switch (face) { case NORTH: @@ -15,6 +14,7 @@ public class RotationUtils { case WEST: return 90F; } + return 0F; } @@ -33,6 +33,7 @@ public class RotationUtils { case 450: return BlockFace.WEST; } + // idk return BlockFace.SOUTH; } diff --git a/Core/src/main/java/com/songoda/core/utils/TextUtils.java b/Core/src/main/java/com/songoda/core/utils/TextUtils.java index ffabc10c..f604e4d8 100644 --- a/Core/src/main/java/com/songoda/core/utils/TextUtils.java +++ b/Core/src/main/java/com/songoda/core/utils/TextUtils.java @@ -40,19 +40,27 @@ public class TextUtils { } public static String formatText(String text, boolean capitalize) { - if (text == null || text.equals("")) + if (text == null || text.equals("")) { return ""; - if (capitalize) + } + + if (capitalize) { text = text.substring(0, 1).toUpperCase() + text.substring(1); + } + return ChatColor.translateAlternateColorCodes('&', text); } public static List formatText(List list) { - return list.stream().map(TextUtils::formatText).collect(Collectors.toList()); + return list.stream() + .map(TextUtils::formatText) + .collect(Collectors.toList()); } public static List formatText(String... list) { - return Arrays.stream(list).map(TextUtils::formatText).collect(Collectors.toList()); + return Arrays.stream(list) + .map(TextUtils::formatText) + .collect(Collectors.toList()); } public static List wrap(String line) { @@ -60,16 +68,18 @@ public class TextUtils { } public static List wrap(String color, String line) { - if (color != null) + if (color != null) { color = "&" + color; - else + } else { color = ""; + } List lore = new ArrayList<>(); int lastIndex = 0; - for (int n = 0; n < line.length(); n++) { - if (n - lastIndex < 25) + for (int n = 0; n < line.length(); ++n) { + if (n - lastIndex < 25) { continue; + } if (line.charAt(n) == ' ') { lore.add(TextUtils.formatText(color + TextUtils.formatText(line.substring(lastIndex, n)))); @@ -77,8 +87,10 @@ public class TextUtils { } } - if (lastIndex - line.length() < 25) + if (lastIndex - line.length() < 25) { lore.add(TextUtils.formatText(color + TextUtils.formatText(line.substring(lastIndex)))); + } + return lore; } @@ -92,11 +104,16 @@ public class TextUtils { * @return encoded string */ public static String convertToInvisibleLoreString(String s) { - if (s == null || s.equals("")) + if (s == null || s.equals("")) { return ""; + } + StringBuilder hidden = new StringBuilder(); - for (char c : s.toCharArray()) + + for (char c : s.toCharArray()) { hidden.append(ChatColor.COLOR_CHAR).append(';').append(ChatColor.COLOR_CHAR).append(c); + } + return hidden.toString(); } @@ -110,10 +127,15 @@ public class TextUtils { * @return encoded string */ public static String convertToInvisibleString(String s) { - if (s == null || s.equals("")) + if (s == null || s.equals("")) { return ""; + } + StringBuilder hidden = new StringBuilder(); - for (char c : s.toCharArray()) hidden.append(ChatColor.COLOR_CHAR).append(c); + for (char c : s.toCharArray()) { + hidden.append(ChatColor.COLOR_CHAR).append(c); + } + return hidden.toString(); } @@ -128,6 +150,7 @@ public class TextUtils { if (s == null || s.equals("")) { return ""; } + return s.replaceAll(ChatColor.COLOR_CHAR + ";" + ChatColor.COLOR_CHAR + "|" + ChatColor.COLOR_CHAR, ""); } @@ -153,6 +176,7 @@ public class TextUtils { try { reader.mark(2048); len = reader.read(buffer); + reader.reset(); } catch (Exception ex) { return null; diff --git a/Core/src/main/java/com/songoda/core/utils/TimeUtils.java b/Core/src/main/java/com/songoda/core/utils/TimeUtils.java index f270e452..369ad9c8 100644 --- a/Core/src/main/java/com/songoda/core/utils/TimeUtils.java +++ b/Core/src/main/java/com/songoda/core/utils/TimeUtils.java @@ -3,10 +3,10 @@ package com.songoda.core.utils; import java.util.concurrent.TimeUnit; public class TimeUtils { - public static String makeReadable(Long time) { - if (time == null) + if (time == null) { return ""; + } StringBuilder sb = new StringBuilder(); @@ -15,22 +15,40 @@ public class TimeUtils { long minutes = TimeUnit.MILLISECONDS.toMinutes(time) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(time)); long seconds = TimeUnit.MILLISECONDS.toSeconds(time) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time)); - if (days != 0L) - sb.append(" ").append(days).append("d"); - if (hours != 0L) - sb.append(" ").append(hours).append("h"); - if (minutes != 0L) - sb.append(" ").append(minutes).append("m"); - if (seconds != 0L) - sb.append(" ").append(seconds).append("s"); + if (days != 0L) { + sb.append(" ") + .append(days) + .append("d"); + } + + if (hours != 0L) { + sb.append(" ") + .append(hours) + .append("h"); + } + + if (minutes != 0L) { + sb.append(" ") + .append(minutes) + .append("m"); + } + + if (seconds != 0L) { + sb.append(" ") + .append(seconds) + .append("s"); + } + return sb.toString().trim(); } public static long parseTime(String input) { long result = 0; StringBuilder number = new StringBuilder(); - for (int i = 0; i < input.length(); i++) { + + for (int i = 0; i < input.length(); ++i) { char c = input.charAt(i); + if (Character.isDigit(c)) { number.append(c); } else if (Character.isLetter(c) && (number.length() > 0)) { @@ -38,6 +56,7 @@ public class TimeUtils { number = new StringBuilder(); } } + return result; } @@ -51,7 +70,8 @@ public class TimeUtils { return value * 1000 * 60; case 's': return value * 1000; + default: + return 0; } - return 0; } } diff --git a/Core/src/main/java/com/songoda/core/world/SItemStack.java b/Core/src/main/java/com/songoda/core/world/SItemStack.java index d04bad70..e90ccf80 100644 --- a/Core/src/main/java/com/songoda/core/world/SItemStack.java +++ b/Core/src/main/java/com/songoda/core/world/SItemStack.java @@ -13,7 +13,6 @@ import org.bukkit.inventory.meta.Damageable; import org.bukkit.inventory.meta.ItemMeta; public class SItemStack { - protected final com.songoda.core.nms.world.SItemStack sItem; protected final ItemStack item; @@ -38,11 +37,13 @@ public class SItemStack { * @param damage the amount of damage to apply to the item */ public ItemStack addDamage(Player player, int damage, boolean respectVanillaUnbreakingEnchantments) { - if (item == null) + if (item == null) { return null; + } - if (item.getItemMeta() == null) + if (item.getItemMeta() == null) { return item; + } int maxDurability = item.getType().getMaxDurability(); int durability; @@ -75,8 +76,10 @@ public class SItemStack { item.setDurability((short) Math.max(0, item.getDurability() + damage)); durability = item.getDurability(); } - if (durability >= maxDurability && player != null) + + if (durability >= maxDurability && player != null) { destroy(player); + } return item; } @@ -88,6 +91,7 @@ public class SItemStack { public void destroy(Player player, int amount) { PlayerItemBreakEvent breakEvent = new PlayerItemBreakEvent(player, item); Bukkit.getServer().getPluginManager().callEvent(breakEvent); + sItem.breakItem(player, amount); CompatibleSound.ENTITY_ITEM_BREAK.play(player); } @@ -109,7 +113,9 @@ public class SItemStack { } private static boolean shouldApplyDamage(int unbreakingEnchantLevel) { - if (unbreakingEnchantLevel <= 0) return true; + if (unbreakingEnchantLevel <= 0) { + return true; + } return Math.random() <= 1.0 / (unbreakingEnchantLevel + 1); } diff --git a/Core/src/main/java/com/songoda/core/world/SSpawner.java b/Core/src/main/java/com/songoda/core/world/SSpawner.java index 2f892009..a5b652a5 100644 --- a/Core/src/main/java/com/songoda/core/world/SSpawner.java +++ b/Core/src/main/java/com/songoda/core/world/SSpawner.java @@ -15,7 +15,6 @@ import java.util.Set; import java.util.concurrent.ThreadLocalRandom; public class SSpawner { - protected final com.songoda.core.nms.world.SSpawner sSpawner; protected final Location location; @@ -42,13 +41,17 @@ public class SSpawner { */ public int spawn(int amountToSpawn, String particle, Set canSpawnOn, SpawnedEntity spawned, EntityType... types) { - if (location.getWorld() == null) return 0; + if (location.getWorld() == null) { + return 0; + } - if (canSpawnOn == null) + if (canSpawnOn == null) { canSpawnOn = new HashSet<>(); + } - if (canSpawnOn.isEmpty()) + if (canSpawnOn.isEmpty()) { canSpawnOn.addAll(EntityUtils.getSpawnBlocks(types[0])); + } boolean useStackPlugin = EntityStackerManager.isEnabled(); @@ -58,16 +61,20 @@ public class SSpawner { while (spawnCountUsed-- > 0) { EntityType type = types[ThreadLocalRandom.current().nextInt(types.length)]; LivingEntity entity = sSpawner.spawnEntity(type, particle, spawned, canSpawnOn); + if (entity != null) { // If this entity is indeed stackable then spawn a single stack with the desired stack size. if (useStackPlugin && amountToSpawn >= EntityStackerManager.getMinStackSize(type)) { EntityStackerManager.add(entity, amountToSpawn); amountSpawned = amountToSpawn; + break; } + amountSpawned++; } } + return amountSpawned; } diff --git a/Core/src/main/java/com/songoda/core/world/SWorld.java b/Core/src/main/java/com/songoda/core/world/SWorld.java index e7102f3f..61df4a94 100644 --- a/Core/src/main/java/com/songoda/core/world/SWorld.java +++ b/Core/src/main/java/com/songoda/core/world/SWorld.java @@ -10,7 +10,6 @@ import org.bukkit.entity.LivingEntity; import java.util.List; public class SWorld { - protected final com.songoda.core.nms.world.SWorld sWorld; protected final World world; @@ -21,6 +20,7 @@ public class SWorld { public Entity[] getEntitiesFromChunk(int x, int z) { Location location = new Location(null, 0.0D, 0.0D, 0.0D); + return getLivingEntities().stream().filter((entity) -> { entity.getLocation(location); return location.getBlockX() >> 4 == x && location.getBlockZ() >> 4 == z; @@ -28,8 +28,10 @@ public class SWorld { } public List getLivingEntities() { - if (ServerVersion.isServerVersionBelow(ServerVersion.V1_17)) + if (ServerVersion.isServerVersionBelow(ServerVersion.V1_17)) { return world.getLivingEntities(); + } + return sWorld.getLivingEntities(); } diff --git a/Core/src/main/java/com/songoda/core/world/SWorldBorder.java b/Core/src/main/java/com/songoda/core/world/SWorldBorder.java index c4d3eebf..a858c443 100644 --- a/Core/src/main/java/com/songoda/core/world/SWorldBorder.java +++ b/Core/src/main/java/com/songoda/core/world/SWorldBorder.java @@ -11,7 +11,6 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class SWorldBorder { - private static Class packetPlayOutWorldBorderEnumClass; private static Class worldBorderClass; private static Class craftWorldClass; @@ -40,15 +39,16 @@ public class SWorldBorder { packetPlayOutWorldBorderEnumClass); } } - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } } public static void send(Player player, Color color, double size, Location centerLocation) { try { - if (centerLocation == null || centerLocation.getWorld() == null) + if (centerLocation == null || centerLocation.getWorld() == null) { return; + } Object worldBorder = worldBorderClass.getConstructor().newInstance(); @@ -89,13 +89,12 @@ public class SWorldBorder { Enum.valueOf((Class) packetPlayOutWorldBorderEnumClass, "INITIALIZE")); NMSUtils.sendPacket(player, packet); } - } catch (InstantiationException | InvocationTargetException | NoSuchMethodException | IllegalAccessException e) { - e.printStackTrace(); + } catch (InstantiationException | InvocationTargetException | NoSuchMethodException | IllegalAccessException ex) { + ex.printStackTrace(); } } public enum Color { - Blue, Green, Red } } diff --git a/NMS/NMS-API/src/main/java/com/songoda/core/nms/anvil/CustomAnvil.java b/NMS/NMS-API/src/main/java/com/songoda/core/nms/anvil/CustomAnvil.java index efb7bc58..a2792370 100644 --- a/NMS/NMS-API/src/main/java/com/songoda/core/nms/anvil/CustomAnvil.java +++ b/NMS/NMS-API/src/main/java/com/songoda/core/nms/anvil/CustomAnvil.java @@ -11,7 +11,6 @@ import org.bukkit.inventory.ItemStack; * @since 2019-09-13 */ public interface CustomAnvil { - public void setLevelCost(int cost); public int getLevelCost(); diff --git a/NMS/NMS-API/src/main/java/com/songoda/core/nms/anvil/methods/AnvilTextChange.java b/NMS/NMS-API/src/main/java/com/songoda/core/nms/anvil/methods/AnvilTextChange.java index 4e6af753..70737939 100644 --- a/NMS/NMS-API/src/main/java/com/songoda/core/nms/anvil/methods/AnvilTextChange.java +++ b/NMS/NMS-API/src/main/java/com/songoda/core/nms/anvil/methods/AnvilTextChange.java @@ -1,6 +1,5 @@ package com.songoda.core.nms.anvil.methods; public interface AnvilTextChange { - void onChange(); } diff --git a/NMS/NMS-API/src/main/java/com/songoda/core/nms/nbt/NBTCompound.java b/NMS/NMS-API/src/main/java/com/songoda/core/nms/nbt/NBTCompound.java index 90231ae4..f09c7a24 100644 --- a/NMS/NMS-API/src/main/java/com/songoda/core/nms/nbt/NBTCompound.java +++ b/NMS/NMS-API/src/main/java/com/songoda/core/nms/nbt/NBTCompound.java @@ -4,7 +4,6 @@ import java.util.Set; import java.util.UUID; public interface NBTCompound { - NBTCompound set(String tag, String s); NBTCompound set(String tag, boolean b); diff --git a/NMS/NMS-API/src/main/java/com/songoda/core/nms/nbt/NBTCore.java b/NMS/NMS-API/src/main/java/com/songoda/core/nms/nbt/NBTCore.java index 465d05b8..fca20e34 100644 --- a/NMS/NMS-API/src/main/java/com/songoda/core/nms/nbt/NBTCore.java +++ b/NMS/NMS-API/src/main/java/com/songoda/core/nms/nbt/NBTCore.java @@ -4,7 +4,6 @@ import org.bukkit.entity.Entity; import org.bukkit.inventory.ItemStack; public interface NBTCore { - NBTItem of(ItemStack item); NBTItem newItem(); diff --git a/NMS/NMS-API/src/main/java/com/songoda/core/nms/nbt/NBTEntity.java b/NMS/NMS-API/src/main/java/com/songoda/core/nms/nbt/NBTEntity.java index fdec3a41..77ebbef1 100644 --- a/NMS/NMS-API/src/main/java/com/songoda/core/nms/nbt/NBTEntity.java +++ b/NMS/NMS-API/src/main/java/com/songoda/core/nms/nbt/NBTEntity.java @@ -4,7 +4,6 @@ import org.bukkit.Location; import org.bukkit.entity.Entity; public interface NBTEntity extends NBTCompound { - Entity spawn(Location location); Entity reSpawn(Location location); diff --git a/NMS/NMS-API/src/main/java/com/songoda/core/nms/nbt/NBTItem.java b/NMS/NMS-API/src/main/java/com/songoda/core/nms/nbt/NBTItem.java index f45d8edb..968df307 100644 --- a/NMS/NMS-API/src/main/java/com/songoda/core/nms/nbt/NBTItem.java +++ b/NMS/NMS-API/src/main/java/com/songoda/core/nms/nbt/NBTItem.java @@ -3,6 +3,5 @@ package com.songoda.core.nms.nbt; import org.bukkit.inventory.ItemStack; public interface NBTItem extends NBTCompound { - ItemStack finish(); } diff --git a/NMS/NMS-API/src/main/java/com/songoda/core/nms/nbt/NBTObject.java b/NMS/NMS-API/src/main/java/com/songoda/core/nms/nbt/NBTObject.java index c43b12c1..cec6ebfc 100644 --- a/NMS/NMS-API/src/main/java/com/songoda/core/nms/nbt/NBTObject.java +++ b/NMS/NMS-API/src/main/java/com/songoda/core/nms/nbt/NBTObject.java @@ -3,7 +3,6 @@ package com.songoda.core.nms.nbt; import java.util.Set; public interface NBTObject { - String asString(); boolean asBoolean(); diff --git a/NMS/NMS-API/src/main/java/com/songoda/core/nms/world/SItemStack.java b/NMS/NMS-API/src/main/java/com/songoda/core/nms/world/SItemStack.java index 35cda3b1..e3b4c1ed 100644 --- a/NMS/NMS-API/src/main/java/com/songoda/core/nms/world/SItemStack.java +++ b/NMS/NMS-API/src/main/java/com/songoda/core/nms/world/SItemStack.java @@ -5,7 +5,6 @@ import org.bukkit.entity.Player; import java.util.Random; public interface SItemStack { - Random random = new Random(); void breakItem(Player player, int amount); diff --git a/NMS/NMS-API/src/main/java/com/songoda/core/nms/world/SSpawner.java b/NMS/NMS-API/src/main/java/com/songoda/core/nms/world/SSpawner.java index 7378e318..398b7c7f 100644 --- a/NMS/NMS-API/src/main/java/com/songoda/core/nms/world/SSpawner.java +++ b/NMS/NMS-API/src/main/java/com/songoda/core/nms/world/SSpawner.java @@ -9,7 +9,6 @@ import org.bukkit.entity.LivingEntity; import java.util.Set; public interface SSpawner { - LivingEntity spawnEntity(EntityType type, Location spawnerLocation); LivingEntity spawnEntity(EntityType type, String particleType, SpawnedEntity spawned, @@ -42,18 +41,20 @@ public interface SSpawner { try { TypeTranslations typeTranslation = valueOf(type.name()); return typeTranslation.lower; - } catch (Exception e) { - return type.name().toLowerCase(); + } catch (Exception ignore) { } + + return type.name().toLowerCase(); } public static String getUpperFromType(EntityType type) { try { TypeTranslations typeTranslation = valueOf(type.name()); return typeTranslation.upper; - } catch (Exception e) { - return WordUtils.capitalize(type.name().toLowerCase()).replace(" ", ""); + } catch (Exception ignore) { } + + return WordUtils.capitalize(type.name().toLowerCase()).replace(" ", ""); } } } diff --git a/NMS/NMS-API/src/main/java/com/songoda/core/nms/world/SWorld.java b/NMS/NMS-API/src/main/java/com/songoda/core/nms/world/SWorld.java index 63affe2a..cbb03732 100644 --- a/NMS/NMS-API/src/main/java/com/songoda/core/nms/world/SWorld.java +++ b/NMS/NMS-API/src/main/java/com/songoda/core/nms/world/SWorld.java @@ -5,6 +5,5 @@ import org.bukkit.entity.LivingEntity; import java.util.List; public interface SWorld { - List getLivingEntities(); } diff --git a/NMS/NMS-API/src/main/java/com/songoda/core/nms/world/SpawnedEntity.java b/NMS/NMS-API/src/main/java/com/songoda/core/nms/world/SpawnedEntity.java index ad6996ed..8db0992d 100644 --- a/NMS/NMS-API/src/main/java/com/songoda/core/nms/world/SpawnedEntity.java +++ b/NMS/NMS-API/src/main/java/com/songoda/core/nms/world/SpawnedEntity.java @@ -3,6 +3,5 @@ package com.songoda.core.nms.world; import org.bukkit.entity.LivingEntity; public interface SpawnedEntity { - boolean onSpawn(LivingEntity entity); } diff --git a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/anvil/AnvilCore.java b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/anvil/AnvilCore.java index d1379dfe..732dde45 100644 --- a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/anvil/AnvilCore.java +++ b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/anvil/AnvilCore.java @@ -6,7 +6,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; public class AnvilCore implements com.songoda.core.nms.anvil.AnvilCore { - @Override public CustomAnvil createAnvil(Player player) { return new AnvilView(((CraftPlayer) player).getHandle(), null); diff --git a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/anvil/AnvilInventoryCustom.java b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/anvil/AnvilInventoryCustom.java index 386f4f47..54958693 100644 --- a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/anvil/AnvilInventoryCustom.java +++ b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/anvil/AnvilInventoryCustom.java @@ -6,11 +6,11 @@ import org.bukkit.craftbukkit.v1_10_R1.inventory.CraftInventoryAnvil; import org.bukkit.inventory.InventoryHolder; public class AnvilInventoryCustom extends CraftInventoryAnvil { - final InventoryHolder holder; public AnvilInventoryCustom(InventoryHolder holder, Location location, IInventory inventory, IInventory resultInventory) { super(location, inventory, resultInventory); + this.holder = holder; } diff --git a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/anvil/AnvilView.java b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/anvil/AnvilView.java index 55746a3d..ddb0db74 100644 --- a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/anvil/AnvilView.java +++ b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/anvil/AnvilView.java @@ -20,7 +20,6 @@ import java.util.logging.Level; import java.util.logging.Logger; public class AnvilView extends ContainerAnvil implements CustomAnvil { - private final EntityPlayer entity; private final Inventory inventory; private String title = "Repairing"; @@ -37,8 +36,10 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { try { mc_ContainerAnvil_repairInventory = ContainerAnvil.class.getDeclaredField("h"); mc_ContainerAnvil_repairInventory.setAccessible(true); + mc_ContainerAnvil_resultInventory = ContainerAnvil.class.getDeclaredField("g"); mc_ContainerAnvil_resultInventory.setAccessible(true); + mc_ContainerAnvil_bukkitEntity = ContainerAnvil.class.getDeclaredField("bukkitEntity"); mc_ContainerAnvil_bukkitEntity.setAccessible(true); } catch (Exception ex) { @@ -61,11 +62,13 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { public AnvilView(EntityPlayer entity, InventoryHolder holder) { super(entity.inventory, entity.world, new BlockPosition(0, 0, 0), entity); this.entity = entity; + if (holder != null) { this.inventory = getBukkitView(entity, holder).getTopInventory(); - } else { - this.inventory = getBukkitView().getTopInventory(); + return; } + + this.inventory = getBukkitView().getTopInventory(); } public CraftInventoryView getBukkitView(EntityHuman player, InventoryHolder holder) { @@ -76,10 +79,12 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { (IInventory) mc_ContainerAnvil_resultInventory.get(this)); CraftInventoryView view = new CraftInventoryView(player.getBukkitEntity(), craftInventory, this); mc_ContainerAnvil_bukkitEntity.set(this, view); + return view; } catch (Exception ex) { Logger.getLogger(AnvilView.class.getName()).log(Level.SEVERE, "Anvil Setup Error", ex); } + return getBukkitView(); } @@ -91,6 +96,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void e() { super.e(); + if (cost >= 0) { this.a = cost; } @@ -109,6 +115,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { } catch (Exception ex) { Logger.getLogger(AnvilView.class.getName()).log(Level.SEVERE, "Anvil Error", ex); } + return null; } @@ -184,7 +191,6 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void open() { - // Counter stuff that the game uses to keep track of inventories int id = entity.nextContainerCounter(); diff --git a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/nbt/NBTCompoundImpl.java b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/nbt/NBTCompoundImpl.java index 84eb4d76..cca17d07 100644 --- a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/nbt/NBTCompoundImpl.java +++ b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/nbt/NBTCompoundImpl.java @@ -15,7 +15,6 @@ import java.util.Set; import java.util.UUID; public class NBTCompoundImpl implements NBTCompound { - protected NBTTagCompound compound; protected NBTCompoundImpl(NBTTagCompound compound) { @@ -151,11 +150,11 @@ public class NBTCompoundImpl implements NBTCompound { public NBTCompound getCompound(String tag) { if (has(tag)) { return getNBTObject(tag).asCompound(); - } else { - NBTTagCompound newCompound = new NBTTagCompound(); - compound.set(tag, newCompound); - return new NBTCompoundImpl(newCompound); } + + NBTTagCompound newCompound = new NBTTagCompound(); + compound.set(tag, newCompound); + return new NBTCompoundImpl(newCompound); } @Override @@ -175,15 +174,17 @@ public class NBTCompoundImpl implements NBTCompound { addExtras(); NBTTagCompound compound = this.compound.g(); // Changed in 1.12 - for (String exclusion : exclusions) + for (String exclusion : exclusions) { compound.remove(exclusion); + } NBTCompressedStreamTools.a(compound, (OutputStream) dataOutput); return outputStream.toByteArray(); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } + return null; } @@ -192,8 +193,8 @@ public class NBTCompoundImpl implements NBTCompound { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(serialized); ObjectInputStream dataInput = new ObjectInputStream(inputStream)) { compound = NBTCompressedStreamTools.a((InputStream) dataInput); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } } diff --git a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/nbt/NBTCoreImpl.java b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/nbt/NBTCoreImpl.java index 66444a53..7d44721d 100644 --- a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/nbt/NBTCoreImpl.java +++ b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/nbt/NBTCoreImpl.java @@ -10,7 +10,6 @@ import org.bukkit.entity.Entity; import org.bukkit.inventory.ItemStack; public class NBTCoreImpl implements NBTCore { - @Override public NBTItem of(ItemStack item) { return new NBTItemImpl(CraftItemStack.asNMSCopy(item)); @@ -26,6 +25,7 @@ public class NBTCoreImpl implements NBTCore { net.minecraft.server.v1_10_R1.Entity nmsEntity = ((CraftEntity) entity).getHandle(); NBTTagCompound nbt = new NBTTagCompound(); nmsEntity.e(nbt); // Method name changed in 1.11 + return new NBTEntityImpl(nbt, nmsEntity); } diff --git a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/nbt/NBTEntityImpl.java b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/nbt/NBTEntityImpl.java index 0e63a4b6..101ea777 100644 --- a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/nbt/NBTEntityImpl.java +++ b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/nbt/NBTEntityImpl.java @@ -10,11 +10,11 @@ import org.bukkit.craftbukkit.v1_10_R1.CraftWorld; import org.bukkit.event.entity.CreatureSpawnEvent; public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { - private Entity nmsEntity; public NBTEntityImpl(NBTTagCompound entityNBT, Entity nmsEntity) { super(entityNBT); + this.nmsEntity = nmsEntity; } @@ -35,21 +35,26 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { spawned.setLocation(location.getX(), location.getY(), location.getZ(), location.getPitch(), location.getYaw()); nmsEntity = spawned; + return entity; } + return null; } @Override public org.bukkit.entity.Entity reSpawn(Location location) { nmsEntity.dead = true; + return spawn(location); } @Override public void addExtras() { String key = EntityTypes.b(nmsEntity); // Changed in 1.12 - if (key != null) + + if (key != null) { compound.setString("entity_type", key); // Changed in 1.13 + } } } diff --git a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/nbt/NBTItemImpl.java b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/nbt/NBTItemImpl.java index c4fb4426..3312766d 100644 --- a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/nbt/NBTItemImpl.java @@ -6,20 +6,20 @@ import org.bukkit.craftbukkit.v1_10_R1.inventory.CraftItemStack; import org.bukkit.inventory.ItemStack; public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { - private final net.minecraft.server.v1_10_R1.ItemStack nmsItem; public NBTItemImpl(net.minecraft.server.v1_10_R1.ItemStack nmsItem) { super(nmsItem != null && nmsItem.hasTag() ? nmsItem.getTag() : new NBTTagCompound()); + this.nmsItem = nmsItem; } public ItemStack finish() { if (nmsItem == null) { return CraftItemStack.asBukkitCopy(net.minecraft.server.v1_10_R1.ItemStack.createStack(compound)); - } else { - return CraftItemStack.asBukkitCopy(nmsItem); } + + return CraftItemStack.asBukkitCopy(nmsItem); } @Override diff --git a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/nbt/NBTObjectImpl.java b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/nbt/NBTObjectImpl.java index 6df4ab6f..eb457272 100644 --- a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/nbt/NBTObjectImpl.java +++ b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/nbt/NBTObjectImpl.java @@ -7,7 +7,6 @@ import net.minecraft.server.v1_10_R1.NBTTagCompound; import java.util.Set; public class NBTObjectImpl implements NBTObject { - private final NBTTagCompound compound; private final String tag; diff --git a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/world/SItemStackImpl.java b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/world/SItemStackImpl.java index cf3178ad..13942c7b 100644 --- a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/world/SItemStackImpl.java +++ b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/world/SItemStackImpl.java @@ -11,7 +11,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public class SItemStackImpl implements SItemStack { - private final ItemStack item; public SItemStackImpl(ItemStack item) { @@ -25,7 +24,9 @@ public class SItemStackImpl implements SItemStack { Vec3D vec3d = new Vec3D(((double) random.nextFloat() - 0.5D) * 0.1D, Math.random() * 0.1D + 0.1D, 0.0D); vec3d = vec3d.a(-entityPlayer.pitch * 0.017453292F); vec3d = vec3d.b(-entityPlayer.yaw * 0.017453292F); + double d0 = (double) (-random.nextFloat()) * 0.6D - 0.3D; + Vec3D vec3d1 = new Vec3D(((double) random.nextFloat() - 0.5D) * 0.3D, d0, 0.6D); vec3d1 = vec3d1.a(-entityPlayer.pitch * 0.017453292F); vec3d1 = vec3d1.b(-entityPlayer.yaw * 0.017453292F); diff --git a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/world/SSpawnerImpl.java b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/world/SSpawnerImpl.java index c1bbb1c5..af1726cd 100644 --- a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/world/SSpawnerImpl.java +++ b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/world/SSpawnerImpl.java @@ -23,7 +23,6 @@ import java.util.Random; import java.util.Set; public class SSpawnerImpl implements SSpawner { - private final Location spawnerLocation; public SSpawnerImpl(Location location) { @@ -38,7 +37,6 @@ public class SSpawnerImpl implements SSpawner { @Override public LivingEntity spawnEntity(EntityType type, String particleType, SpawnedEntity spawned, Set canSpawnOn) { - MobSpawnerData data = new MobSpawnerData(); NBTTagCompound compound = data.b(); @@ -58,27 +56,30 @@ public class SSpawnerImpl implements SSpawner { BlockPosition position = entity.getChunkCoordinates(); DifficultyDamageScaler damageScaler = world.D(position); - if (!(entity instanceof EntityInsentient)) + if (!(entity instanceof EntityInsentient)) { continue; + } EntityInsentient entityInsentient = (EntityInsentient) entity; Location spot = new Location(spawnerLocation.getWorld(), x, y, z); - if (!canSpawn(entityInsentient, spot, canSpawnOn)) + if (!canSpawn(entityInsentient, spot, canSpawnOn)) { continue; + } entityInsentient.prepare(damageScaler, null); LivingEntity craftEntity = (LivingEntity) entity.getBukkitEntity(); - if (spawned != null) - if (!spawned.onSpawn(craftEntity)) - return null; + if (spawned != null && !spawned.onSpawn(craftEntity)) { + return null; + } if (particleType != null) { float xx = (float) (0 + (Math.random() * 1)); float yy = (float) (0 + (Math.random() * 2)); float zz = (float) (0 + (Math.random() * 1)); + CompatibleParticleHandler.spawnParticles(CompatibleParticleHandler.ParticleType.getParticle(particleType), spot, 5, xx, yy, zz, 0); } @@ -90,32 +91,37 @@ public class SSpawnerImpl implements SSpawner { return craftEntity; } + return null; } private boolean canSpawn(EntityInsentient entityInsentient, Location location, Set canSpawnOn) { - if (!entityInsentient.canSpawn()) + if (!entityInsentient.canSpawn()) { return false; + } CompatibleMaterial spawnedIn = CompatibleMaterial.getMaterial(location.getBlock()); CompatibleMaterial spawnedOn = CompatibleMaterial.getMaterial(location.getBlock().getRelative(BlockFace.DOWN)); - if (spawnedIn == null || spawnedOn == null) + if (spawnedIn == null || spawnedOn == null) { return false; + } - if (!spawnedIn.isAir() - && spawnedIn != CompatibleMaterial.WATER - && !spawnedIn.name().contains("PRESSURE") - && !spawnedIn.name().contains("SLAB")) { + if (!spawnedIn.isAir() && + spawnedIn != CompatibleMaterial.WATER && + !spawnedIn.name().contains("PRESSURE") && + !spawnedIn.name().contains("SLAB")) { return false; } for (CompatibleMaterial material : canSpawnOn) { if (material == null) continue; - if (spawnedOn.equals(material) || material.isAir()) + if (spawnedOn.equals(material) || material.isAir()) { return true; + } } + return false; } } diff --git a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/world/SWorldImpl.java b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/world/SWorldImpl.java index 64d2e82c..04f7ea34 100644 --- a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/world/SWorldImpl.java +++ b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/world/SWorldImpl.java @@ -7,7 +7,6 @@ import java.util.ArrayList; import java.util.List; public class SWorldImpl implements SWorld { - public SWorldImpl() { } diff --git a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/world/WorldCoreImpl.java b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/world/WorldCoreImpl.java index 1304d868..25d93b42 100644 --- a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/world/WorldCoreImpl.java +++ b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/world/WorldCoreImpl.java @@ -56,28 +56,30 @@ public class WorldCoreImpl implements WorldCore { public void randomTickChunk(org.bukkit.Chunk bukkitChunk, int tickAmount) throws NoSuchFieldException, IllegalAccessException { Chunk chunk = ((CraftChunk) bukkitChunk).getHandle(); - if (tickAmount > 0) { - int j = chunk.locX * 16; - int k = chunk.locZ * 16; + if (tickAmount <= 0) { + return; + } - for (ChunkSection chunksection : chunk.getSections()) { - if (chunksection != net.minecraft.server.v1_10_R1.Chunk.a && chunksection.shouldTick()) { - for (int i = 0; i < tickAmount; ++i) { - int worldL = (int) ReflectionUtils.getFieldValue(chunk.world, "l"); - worldL = worldL * 3 + 1013904223; - ReflectionUtils.setFieldValue(chunk.world, "l", worldL); + int j = chunk.locX * 16; + int k = chunk.locZ * 16; - int l1 = worldL >> 2; - int i2 = l1 & 15; - int j2 = l1 >> 8 & 15; - int k2 = l1 >> 16 & 15; + for (ChunkSection chunksection : chunk.getSections()) { + if (chunksection != net.minecraft.server.v1_10_R1.Chunk.a && chunksection.shouldTick()) { + for (int i = 0; i < tickAmount; ++i) { + int worldL = (int) ReflectionUtils.getFieldValue(chunk.world, "l"); + worldL = worldL * 3 + 1013904223; + ReflectionUtils.setFieldValue(chunk.world, "l", worldL); - IBlockData iblockdata = chunksection.getType(i2, k2, j2); - Block block = iblockdata.getBlock(); + int l1 = worldL >> 2; + int i2 = l1 & 15; + int j2 = l1 >> 8 & 15; + int k2 = l1 >> 16 & 15; - if (block.isTicking()) { - block.a(chunk.world, new BlockPosition(i2 + j, k2 + chunksection.getYPosition(), j2 + k), iblockdata, chunk.world.random); - } + IBlockData iblockdata = chunksection.getType(i2, k2, j2); + Block block = iblockdata.getBlock(); + + if (block.isTicking()) { + block.a(chunk.world, new BlockPosition(i2 + j, k2 + chunksection.getYPosition(), j2 + k), iblockdata, chunk.world.random); } } } diff --git a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/world/spawner/BBaseSpawnerImpl.java b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/world/spawner/BBaseSpawnerImpl.java index 18e7a641..fa75cfa3 100644 --- a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/world/spawner/BBaseSpawnerImpl.java +++ b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/world/spawner/BBaseSpawnerImpl.java @@ -71,87 +71,88 @@ public class BBaseSpawnerImpl implements BBaseSpawner { ReflectionUtils.setFieldValue(spawner, "e", spawnerD); ReflectionUtils.setFieldValue(spawner, "d", (spawnerD + (double) (1000F / ((float) spawner.spawnDelay + 200F))) % 360D); - } else { - if (spawner.spawnDelay == -1) { - delay(spawner); + return; + } + + if (spawner.spawnDelay == -1) { + delay(spawner); + } + + if (spawner.spawnDelay > 0) { + --spawner.spawnDelay; + return; + } + + boolean flag = false; + int i = 0; + + int spawnCount = (int) ReflectionUtils.getFieldValue(spawner, "spawnCount"); + int spawnRange = (int) ReflectionUtils.getFieldValue(spawner, "spawnRange"); + int maxNearbyEntities = (int) ReflectionUtils.getFieldValue(spawner, "maxNearbyEntities"); + MobSpawnerData spawnData = (MobSpawnerData) ReflectionUtils.getFieldValue(spawner, "spawnData"); + + while (true) { + if (i >= spawnCount) { + if (flag) { + delay(spawner); + } + + break; } - if (spawner.spawnDelay > 0) { - --spawner.spawnDelay; + NBTTagCompound nbttagcompound = spawnData.b(); + NBTTagList nbttaglist = nbttagcompound.getList("Pos", 6); + + net.minecraft.server.v1_10_R1.World world = spawner.a(); + + int j = nbttaglist.size(); + double d3 = j >= 1 ? nbttaglist.e(0) : (double) blockposition.getX() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawnRange + .5D; + double d4 = j >= 2 ? nbttaglist.e(1) : (double) (blockposition.getY() + world.random.nextInt(3) - 1); + double d5 = j >= 3 ? nbttaglist.e(2) : (double) blockposition.getZ() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawnRange + .5D; + + Entity entity = ChunkRegionLoader.a(nbttagcompound, world, d3, d4, d5, false); + + if (entity == null) { return; } - boolean flag = false; - int i = 0; + int k = world.a(entity.getClass(), (new AxisAlignedBB(blockposition.getX(), + blockposition.getY(), + blockposition.getZ(), + blockposition.getX() + 1, + blockposition.getY() + 1, + blockposition.getZ() + 1)) + .g(spawnRange)).size(); - int spawnCount = (int) ReflectionUtils.getFieldValue(spawner, "spawnCount"); - int spawnRange = (int) ReflectionUtils.getFieldValue(spawner, "spawnRange"); - int maxNearbyEntities = (int) ReflectionUtils.getFieldValue(spawner, "maxNearbyEntities"); - MobSpawnerData spawnData = (MobSpawnerData) ReflectionUtils.getFieldValue(spawner, "spawnData"); - - while (true) { - if (i >= spawnCount) { - if (flag) { - delay(spawner); - } - - break; - } - - NBTTagCompound nbttagcompound = spawnData.b(); - NBTTagList nbttaglist = nbttagcompound.getList("Pos", 6); - - net.minecraft.server.v1_10_R1.World world = spawner.a(); - - int j = nbttaglist.size(); - double d3 = j >= 1 ? nbttaglist.e(0) : (double) blockposition.getX() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawnRange + .5D; - double d4 = j >= 2 ? nbttaglist.e(1) : (double) (blockposition.getY() + world.random.nextInt(3) - 1); - double d5 = j >= 3 ? nbttaglist.e(2) : (double) blockposition.getZ() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawnRange + .5D; - - Entity entity = ChunkRegionLoader.a(nbttagcompound, world, d3, d4, d5, false); - - if (entity == null) { - return; - } - - int k = world.a(entity.getClass(), (new AxisAlignedBB(blockposition.getX(), - blockposition.getY(), - blockposition.getZ(), - blockposition.getX() + 1, - blockposition.getY() + 1, - blockposition.getZ() + 1)) - .g(spawnRange)).size(); - - if (k >= maxNearbyEntities) { - delay(spawner); - return; - } - - EntityInsentient entityinsentient = entity instanceof EntityInsentient ? (EntityInsentient) entity : null; - entity.setPositionRotation(entity.locX, entity.locY, entity.locZ, world.random.nextFloat() * 360.0F, 0.0F); - - if (entityinsentient == null || entityinsentient.cK() && entityinsentient.canSpawn()) { - if (spawnData.b().d() == 1 && spawnData.b().hasKeyOfType("id", 8) && entity instanceof EntityInsentient) { - ((EntityInsentient) entity).prepare(world.D(new BlockPosition(entity)), null); - } - - if (entity.world.spigotConfig.nerfSpawnerMobs) { - entity.fromMobSpawner = true; - } - - if (!CraftEventFactory.callSpawnerSpawnEvent(entity, blockposition).isCancelled()) { - ChunkRegionLoader.a(entity, world, CreatureSpawnEvent.SpawnReason.SPAWNER); - world.triggerEffect(2004, blockposition, 0); - if (entityinsentient != null) { - entityinsentient.doSpawnEffect(); - } - - flag = true; - } - } - - ++i; + if (k >= maxNearbyEntities) { + delay(spawner); + return; } + + EntityInsentient entityinsentient = entity instanceof EntityInsentient ? (EntityInsentient) entity : null; + entity.setPositionRotation(entity.locX, entity.locY, entity.locZ, world.random.nextFloat() * 360.0F, 0.0F); + + if (entityinsentient == null || entityinsentient.cK() && entityinsentient.canSpawn()) { + if (spawnData.b().d() == 1 && spawnData.b().hasKeyOfType("id", 8) && entity instanceof EntityInsentient) { + ((EntityInsentient) entity).prepare(world.D(new BlockPosition(entity)), null); + } + + if (entity.world.spigotConfig.nerfSpawnerMobs) { + entity.fromMobSpawner = true; + } + + if (!CraftEventFactory.callSpawnerSpawnEvent(entity, blockposition).isCancelled()) { + ChunkRegionLoader.a(entity, world, CreatureSpawnEvent.SpawnReason.SPAWNER); + world.triggerEffect(2004, blockposition, 0); + if (entityinsentient != null) { + entityinsentient.doSpawnEffect(); + } + + flag = true; + } + } + + ++i; } } @@ -162,4 +163,4 @@ public class BBaseSpawnerImpl implements BBaseSpawner { private void delay(MobSpawnerAbstract spawner) throws InvocationTargetException, IllegalAccessException { iMethod.invoke(spawner); } -} \ No newline at end of file +} diff --git a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/anvil/AnvilCore.java b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/anvil/AnvilCore.java index 3c76bdf0..a9ab341e 100644 --- a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/anvil/AnvilCore.java +++ b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/anvil/AnvilCore.java @@ -6,7 +6,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; public class AnvilCore implements com.songoda.core.nms.anvil.AnvilCore { - @Override public CustomAnvil createAnvil(Player player) { return new AnvilView(((CraftPlayer) player).getHandle(), null); diff --git a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/anvil/AnvilInventoryCustom.java b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/anvil/AnvilInventoryCustom.java index 5e224773..aff36331 100644 --- a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/anvil/AnvilInventoryCustom.java +++ b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/anvil/AnvilInventoryCustom.java @@ -7,11 +7,11 @@ import org.bukkit.craftbukkit.v1_11_R1.inventory.CraftInventoryAnvil; import org.bukkit.inventory.InventoryHolder; public class AnvilInventoryCustom extends CraftInventoryAnvil { - final InventoryHolder holder; public AnvilInventoryCustom(InventoryHolder holder, Location location, IInventory inventory, IInventory resultInventory, ContainerAnvil container) { super(location, inventory, resultInventory, container); + this.holder = holder; } diff --git a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/anvil/AnvilView.java b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/anvil/AnvilView.java index 41793bcf..711bd6fa 100644 --- a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/anvil/AnvilView.java +++ b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/anvil/AnvilView.java @@ -20,7 +20,6 @@ import java.util.logging.Level; import java.util.logging.Logger; public class AnvilView extends ContainerAnvil implements CustomAnvil { - private final EntityPlayer entity; private final Inventory inventory; private String title = "Repairing"; @@ -37,8 +36,10 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { try { mc_ContainerAnvil_repairInventory = ContainerAnvil.class.getDeclaredField("h"); mc_ContainerAnvil_repairInventory.setAccessible(true); + mc_ContainerAnvil_resultInventory = ContainerAnvil.class.getDeclaredField("g"); mc_ContainerAnvil_resultInventory.setAccessible(true); + mc_ContainerAnvil_bukkitEntity = ContainerAnvil.class.getDeclaredField("bukkitEntity"); mc_ContainerAnvil_bukkitEntity.setAccessible(true); } catch (Exception ex) { @@ -61,6 +62,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { public AnvilView(EntityPlayer entity, InventoryHolder holder) { super(entity.inventory, entity.world, new BlockPosition(0, 0, 0), entity); this.entity = entity; + if (holder != null) { this.inventory = getBukkitView(entity, holder).getTopInventory(); } else { @@ -76,10 +78,12 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { (IInventory) mc_ContainerAnvil_resultInventory.get(this), this); CraftInventoryView view = new CraftInventoryView(player.getBukkitEntity(), craftInventory, this); mc_ContainerAnvil_bukkitEntity.set(this, view); + return view; } catch (Exception ex) { Logger.getLogger(AnvilView.class.getName()).log(Level.SEVERE, "Anvil Setup Error", ex); } + return getBukkitView(); } @@ -91,6 +95,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void e() { super.e(); + if (cost >= 0) { this.a = cost; } @@ -109,6 +114,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { } catch (Exception ex) { Logger.getLogger(AnvilView.class.getName()).log(Level.SEVERE, "Anvil Error", ex); } + return null; } @@ -184,7 +190,6 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void open() { - // Counter stuff that the game uses to keep track of inventories int id = entity.nextContainerCounter(); diff --git a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/nbt/NBTCompoundImpl.java b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/nbt/NBTCompoundImpl.java index df9139fb..78dbb5f2 100644 --- a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/nbt/NBTCompoundImpl.java +++ b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/nbt/NBTCompoundImpl.java @@ -15,7 +15,6 @@ import java.util.Set; import java.util.UUID; public class NBTCompoundImpl implements NBTCompound { - protected NBTTagCompound compound; protected NBTCompoundImpl(NBTTagCompound compound) { @@ -151,11 +150,12 @@ public class NBTCompoundImpl implements NBTCompound { public NBTCompound getCompound(String tag) { if (has(tag)) { return getNBTObject(tag).asCompound(); - } else { - NBTTagCompound newCompound = new NBTTagCompound(); - compound.set(tag, newCompound); - return new NBTCompoundImpl(newCompound); } + + NBTTagCompound newCompound = new NBTTagCompound(); + compound.set(tag, newCompound); + + return new NBTCompoundImpl(newCompound); } @Override @@ -175,15 +175,17 @@ public class NBTCompoundImpl implements NBTCompound { addExtras(); NBTTagCompound compound = this.compound.g(); // Changed in 1.12 - for (String exclusion : exclusions) + for (String exclusion : exclusions) { compound.remove(exclusion); + } NBTCompressedStreamTools.a(compound, (OutputStream) dataOutput); return outputStream.toByteArray(); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } + return null; } @@ -192,8 +194,8 @@ public class NBTCompoundImpl implements NBTCompound { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(serialized); ObjectInputStream dataInput = new ObjectInputStream(inputStream)) { compound = NBTCompressedStreamTools.a((InputStream) dataInput); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } } diff --git a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/nbt/NBTCoreImpl.java b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/nbt/NBTCoreImpl.java index 0432c755..fe6a9d51 100644 --- a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/nbt/NBTCoreImpl.java +++ b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/nbt/NBTCoreImpl.java @@ -10,7 +10,6 @@ import org.bukkit.entity.Entity; import org.bukkit.inventory.ItemStack; public class NBTCoreImpl implements NBTCore { - @Override public NBTItem of(ItemStack item) { return new NBTItemImpl(CraftItemStack.asNMSCopy(item)); @@ -26,6 +25,7 @@ public class NBTCoreImpl implements NBTCore { net.minecraft.server.v1_11_R1.Entity nmsEntity = ((CraftEntity) entity).getHandle(); NBTTagCompound nbt = new NBTTagCompound(); nmsEntity.e(nbt); // Method name changed in 1.11 + return new NBTEntityImpl(nbt, nmsEntity); } diff --git a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/nbt/NBTEntityImpl.java b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/nbt/NBTEntityImpl.java index a3002566..59dce207 100644 --- a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/nbt/NBTEntityImpl.java +++ b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/nbt/NBTEntityImpl.java @@ -11,11 +11,11 @@ import org.bukkit.craftbukkit.v1_11_R1.CraftWorld; import org.bukkit.event.entity.CreatureSpawnEvent; public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { - private Entity nmsEntity; public NBTEntityImpl(NBTTagCompound entityNBT, Entity nmsEntity) { super(entityNBT); + this.nmsEntity = nmsEntity; } @@ -36,8 +36,10 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { spawned.setLocation(location.getX(), location.getY(), location.getZ(), location.getPitch(), location.getYaw()); nmsEntity = spawned; + return entity; } + return null; } @@ -50,7 +52,9 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { @Override public void addExtras() { String key = EntityTypes.b(nmsEntity); // Changed in 1.12 - if (key != null) + + if (key != null) { compound.setString("entity_type", key); // Changed in 1.13 + } } } diff --git a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/nbt/NBTItemImpl.java b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/nbt/NBTItemImpl.java index 0712745b..02d82b3b 100644 --- a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/nbt/NBTItemImpl.java @@ -7,20 +7,20 @@ import org.bukkit.craftbukkit.v1_11_R1.inventory.CraftItemStack; import org.bukkit.inventory.ItemStack; public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { - private final net.minecraft.server.v1_11_R1.ItemStack nmsItem; public NBTItemImpl(net.minecraft.server.v1_11_R1.ItemStack nmsItem) { super(nmsItem != null && nmsItem.hasTag() ? nmsItem.getTag() : new NBTTagCompound()); + this.nmsItem = nmsItem; } public ItemStack finish() { if (nmsItem == null) { return CraftItemStack.asBukkitCopy(new net.minecraft.server.v1_11_R1.ItemStack(compound)); - } else { - return CraftItemStack.asBukkitCopy(nmsItem); } + + return CraftItemStack.asBukkitCopy(nmsItem); } @Override diff --git a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/nbt/NBTObjectImpl.java b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/nbt/NBTObjectImpl.java index c6075963..bdcad43b 100644 --- a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/nbt/NBTObjectImpl.java +++ b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/nbt/NBTObjectImpl.java @@ -7,7 +7,6 @@ import net.minecraft.server.v1_11_R1.NBTTagCompound; import java.util.Set; public class NBTObjectImpl implements NBTObject { - private final NBTTagCompound compound; private final String tag; diff --git a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/world/SItemStackImpl.java b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/world/SItemStackImpl.java index 75acfd73..4112b12b 100644 --- a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/world/SItemStackImpl.java +++ b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/world/SItemStackImpl.java @@ -11,7 +11,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public class SItemStackImpl implements SItemStack { - private final ItemStack item; public SItemStackImpl(ItemStack item) { @@ -21,11 +20,14 @@ public class SItemStackImpl implements SItemStack { @Override public void breakItem(Player player, int amount) { EntityPlayer entityPlayer = ((CraftPlayer) player).getHandle(); + for (int i = 0; i < 5; ++i) { Vec3D vec3d = new Vec3D(((double) random.nextFloat() - 0.5D) * 0.1D, Math.random() * 0.1D + 0.1D, 0.0D); vec3d = vec3d.a(-entityPlayer.pitch * 0.017453292F); vec3d = vec3d.b(-entityPlayer.yaw * 0.017453292F); + double d0 = (double) (-random.nextFloat()) * 0.6D - 0.3D; + Vec3D vec3d1 = new Vec3D(((double) random.nextFloat() - 0.5D) * 0.3D, d0, 0.6D); vec3d1 = vec3d1.a(-entityPlayer.pitch * 0.017453292F); vec3d1 = vec3d1.b(-entityPlayer.yaw * 0.017453292F); diff --git a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/world/SSpawnerImpl.java b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/world/SSpawnerImpl.java index 566058b7..b8fc4bf8 100644 --- a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/world/SSpawnerImpl.java +++ b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/world/SSpawnerImpl.java @@ -23,7 +23,6 @@ import java.util.Random; import java.util.Set; public class SSpawnerImpl implements SSpawner { - private final Location spawnerLocation; public SSpawnerImpl(Location location) { @@ -38,7 +37,6 @@ public class SSpawnerImpl implements SSpawner { @Override public LivingEntity spawnEntity(EntityType type, String particleType, SpawnedEntity spawned, Set canSpawnOn) { - MobSpawnerData data = new MobSpawnerData(); NBTTagCompound compound = data.b(); @@ -60,27 +58,30 @@ public class SSpawnerImpl implements SSpawner { BlockPosition position = entity.getChunkCoordinates(); DifficultyDamageScaler damageScaler = world.D(position); - if (!(entity instanceof EntityInsentient)) + if (!(entity instanceof EntityInsentient)) { continue; + } EntityInsentient entityInsentient = (EntityInsentient) entity; Location spot = new Location(spawnerLocation.getWorld(), x, y, z); - if (!canSpawn(entityInsentient, spot, canSpawnOn)) + if (!canSpawn(entityInsentient, spot, canSpawnOn)) { continue; + } entityInsentient.prepare(damageScaler, null); LivingEntity craftEntity = (LivingEntity) entity.getBukkitEntity(); - if (spawned != null) - if (!spawned.onSpawn(craftEntity)) - return null; + if (spawned != null && !spawned.onSpawn(craftEntity)) { + return null; + } if (particleType != null) { float xx = (float) (0 + (Math.random() * 1)); float yy = (float) (0 + (Math.random() * 2)); float zz = (float) (0 + (Math.random() * 1)); + CompatibleParticleHandler.spawnParticles(CompatibleParticleHandler.ParticleType.getParticle(particleType), spot, 5, xx, yy, zz, 0); } @@ -92,32 +93,37 @@ public class SSpawnerImpl implements SSpawner { return craftEntity; } + return null; } private boolean canSpawn(EntityInsentient entityInsentient, Location location, Set canSpawnOn) { - if (!entityInsentient.canSpawn()) + if (!entityInsentient.canSpawn()) { return false; + } CompatibleMaterial spawnedIn = CompatibleMaterial.getMaterial(location.getBlock()); CompatibleMaterial spawnedOn = CompatibleMaterial.getMaterial(location.getBlock().getRelative(BlockFace.DOWN)); - if (spawnedIn == null || spawnedOn == null) + if (spawnedIn == null || spawnedOn == null) { return false; + } - if (!spawnedIn.isAir() - && spawnedIn != CompatibleMaterial.WATER - && !spawnedIn.name().contains("PRESSURE") - && !spawnedIn.name().contains("SLAB")) { + if (!spawnedIn.isAir() && + spawnedIn != CompatibleMaterial.WATER && + !spawnedIn.name().contains("PRESSURE") && + !spawnedIn.name().contains("SLAB")) { return false; } for (CompatibleMaterial material : canSpawnOn) { if (material == null) continue; - if (spawnedOn.equals(material) || material.isAir()) + if (spawnedOn.equals(material) || material.isAir()) { return true; + } } + return false; } } diff --git a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/world/SWorldImpl.java b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/world/SWorldImpl.java index 8a9972f5..e8d37fd4 100644 --- a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/world/SWorldImpl.java +++ b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/world/SWorldImpl.java @@ -7,7 +7,6 @@ import java.util.ArrayList; import java.util.List; public class SWorldImpl implements SWorld { - public SWorldImpl() { } diff --git a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/world/WorldCoreImpl.java b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/world/WorldCoreImpl.java index b5f33e75..966be49c 100644 --- a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/world/WorldCoreImpl.java +++ b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/world/WorldCoreImpl.java @@ -56,28 +56,30 @@ public class WorldCoreImpl implements WorldCore { public void randomTickChunk(org.bukkit.Chunk bukkitChunk, int tickAmount) throws NoSuchFieldException, IllegalAccessException { Chunk chunk = ((CraftChunk) bukkitChunk).getHandle(); - if (tickAmount > 0) { - int j = chunk.locX * 16; - int k = chunk.locZ * 16; + if (tickAmount <= 0) { + return; + } - for (ChunkSection chunksection : chunk.getSections()) { - if (chunksection != net.minecraft.server.v1_11_R1.Chunk.a && chunksection.shouldTick()) { - for (int i = 0; i < tickAmount; ++i) { - int worldL = (int) ReflectionUtils.getFieldValue(chunk.world, "l"); - worldL = worldL * 3 + 1013904223; - ReflectionUtils.setFieldValue(chunk.world, "l", worldL); + int j = chunk.locX * 16; + int k = chunk.locZ * 16; - int l1 = worldL >> 2; - int i2 = l1 & 15; - int j2 = l1 >> 8 & 15; - int k2 = l1 >> 16 & 15; + for (ChunkSection chunksection : chunk.getSections()) { + if (chunksection != net.minecraft.server.v1_11_R1.Chunk.a && chunksection.shouldTick()) { + for (int i = 0; i < tickAmount; ++i) { + int worldL = (int) ReflectionUtils.getFieldValue(chunk.world, "l"); + worldL = worldL * 3 + 1013904223; + ReflectionUtils.setFieldValue(chunk.world, "l", worldL); - IBlockData iblockdata = chunksection.getType(i2, k2, j2); - Block block = iblockdata.getBlock(); + int l1 = worldL >> 2; + int i2 = l1 & 15; + int j2 = l1 >> 8 & 15; + int k2 = l1 >> 16 & 15; - if (block.isTicking()) { - block.a(chunk.world, new BlockPosition(i2 + j, k2 + chunksection.getYPosition(), j2 + k), iblockdata, chunk.world.random); - } + IBlockData iblockdata = chunksection.getType(i2, k2, j2); + Block block = iblockdata.getBlock(); + + if (block.isTicking()) { + block.a(chunk.world, new BlockPosition(i2 + j, k2 + chunksection.getYPosition(), j2 + k), iblockdata, chunk.world.random); } } } diff --git a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/world/spawner/BBaseSpawnerImpl.java b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/world/spawner/BBaseSpawnerImpl.java index bbb52105..6ac524f6 100644 --- a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/world/spawner/BBaseSpawnerImpl.java +++ b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/world/spawner/BBaseSpawnerImpl.java @@ -71,82 +71,84 @@ public class BBaseSpawnerImpl implements BBaseSpawner { ReflectionUtils.setFieldValue(spawner, "e", spawnerD); ReflectionUtils.setFieldValue(spawner, "d", (spawnerD + (double) (1000F / ((float) spawner.spawnDelay + 200F))) % 360D); - } else { - if (spawner.spawnDelay == -1) { - delay(spawner); + return; + } + + if (spawner.spawnDelay == -1) { + delay(spawner); + } + + if (spawner.spawnDelay > 0) { + --spawner.spawnDelay; + return; + } + + boolean flag = false; + int i = 0; + + int spawnCount = (int) ReflectionUtils.getFieldValue(spawner, "spawnCount"); + int spawnRange = (int) ReflectionUtils.getFieldValue(spawner, "spawnRange"); + int maxNearbyEntities = (int) ReflectionUtils.getFieldValue(spawner, "maxNearbyEntities"); + MobSpawnerData spawnData = (MobSpawnerData) ReflectionUtils.getFieldValue(spawner, "spawnData"); + + while (true) { + if (i >= spawnCount) { + if (flag) { + delay(spawner); + } + + break; } - if (spawner.spawnDelay > 0) { - --spawner.spawnDelay; + NBTTagCompound nbttagcompound = spawnData.b(); + NBTTagList nbttaglist = nbttagcompound.getList("Pos", 6); + net.minecraft.server.v1_11_R1.World world = spawner.a(); + int j = nbttaglist.size(); + double d3 = j >= 1 ? nbttaglist.e(0) : (double) blockposition.getX() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawnRange + .5D; + double d4 = j >= 2 ? nbttaglist.e(1) : (double) (blockposition.getY() + world.random.nextInt(3) - 1); + double d5 = j >= 3 ? nbttaglist.e(2) : (double) blockposition.getZ() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawnRange + .5D; + Entity entity = ChunkRegionLoader.a(nbttagcompound, world, d3, d4, d5, false); + if (entity == null) { return; } - boolean flag = false; - int i = 0; - - int spawnCount = (int) ReflectionUtils.getFieldValue(spawner, "spawnCount"); - int spawnRange = (int) ReflectionUtils.getFieldValue(spawner, "spawnRange"); - int maxNearbyEntities = (int) ReflectionUtils.getFieldValue(spawner, "maxNearbyEntities"); - MobSpawnerData spawnData = (MobSpawnerData) ReflectionUtils.getFieldValue(spawner, "spawnData"); - - while (true) { - if (i >= spawnCount) { - if (flag) { - delay(spawner); - } - break; - } - - NBTTagCompound nbttagcompound = spawnData.b(); - NBTTagList nbttaglist = nbttagcompound.getList("Pos", 6); - net.minecraft.server.v1_11_R1.World world = spawner.a(); - int j = nbttaglist.size(); - double d3 = j >= 1 ? nbttaglist.e(0) : (double) blockposition.getX() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawnRange + .5D; - double d4 = j >= 2 ? nbttaglist.e(1) : (double) (blockposition.getY() + world.random.nextInt(3) - 1); - double d5 = j >= 3 ? nbttaglist.e(2) : (double) blockposition.getZ() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawnRange + .5D; - Entity entity = ChunkRegionLoader.a(nbttagcompound, world, d3, d4, d5, false); - if (entity == null) { - return; - } - - int k = world.a(entity.getClass(), (new AxisAlignedBB( - blockposition.getX(), - blockposition.getY(), - blockposition.getZ(), - blockposition.getX() + 1, - blockposition.getY() + 1, - blockposition.getZ() + 1)) - .g(spawnRange)).size(); - if (k >= maxNearbyEntities) { - delay(spawner); - return; - } - - EntityInsentient entityinsentient = entity instanceof EntityInsentient ? (EntityInsentient) entity : null; - entity.setPositionRotation(entity.locX, entity.locY, entity.locZ, world.random.nextFloat() * 360.0F, 0.0F); - if (entityinsentient == null || entityinsentient.cM() && entityinsentient.canSpawn()) { - if (spawnData.b().d() == 1 && spawnData.b().hasKeyOfType("id", 8) && entity instanceof EntityInsentient) { - ((EntityInsentient) entity).prepare(world.D(new BlockPosition(entity)), null); - } - - if (entity.world.spigotConfig.nerfSpawnerMobs) { - entity.fromMobSpawner = true; - } - - if (!CraftEventFactory.callSpawnerSpawnEvent(entity, blockposition).isCancelled()) { - ChunkRegionLoader.a(entity, world, CreatureSpawnEvent.SpawnReason.SPAWNER); - world.triggerEffect(2004, blockposition, 0); - - if (entityinsentient != null) { - entityinsentient.doSpawnEffect(); - } - - flag = true; - } - } - - ++i; + int k = world.a(entity.getClass(), (new AxisAlignedBB( + blockposition.getX(), + blockposition.getY(), + blockposition.getZ(), + blockposition.getX() + 1, + blockposition.getY() + 1, + blockposition.getZ() + 1)) + .g(spawnRange)).size(); + if (k >= maxNearbyEntities) { + delay(spawner); + return; } + + EntityInsentient entityinsentient = entity instanceof EntityInsentient ? (EntityInsentient) entity : null; + entity.setPositionRotation(entity.locX, entity.locY, entity.locZ, world.random.nextFloat() * 360.0F, 0.0F); + if (entityinsentient == null || entityinsentient.cM() && entityinsentient.canSpawn()) { + if (spawnData.b().d() == 1 && spawnData.b().hasKeyOfType("id", 8) && entity instanceof EntityInsentient) { + ((EntityInsentient) entity).prepare(world.D(new BlockPosition(entity)), null); + } + + if (entity.world.spigotConfig.nerfSpawnerMobs) { + entity.fromMobSpawner = true; + } + + if (!CraftEventFactory.callSpawnerSpawnEvent(entity, blockposition).isCancelled()) { + ChunkRegionLoader.a(entity, world, CreatureSpawnEvent.SpawnReason.SPAWNER); + world.triggerEffect(2004, blockposition, 0); + + if (entityinsentient != null) { + entityinsentient.doSpawnEffect(); + } + + flag = true; + } + } + + ++i; } } @@ -157,4 +159,4 @@ public class BBaseSpawnerImpl implements BBaseSpawner { private void delay(MobSpawnerAbstract spawner) throws InvocationTargetException, IllegalAccessException { iMethod.invoke(spawner); } -} \ No newline at end of file +} diff --git a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/anvil/AnvilCore.java b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/anvil/AnvilCore.java index 2ab4b570..df90a03d 100644 --- a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/anvil/AnvilCore.java +++ b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/anvil/AnvilCore.java @@ -6,7 +6,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; public class AnvilCore implements com.songoda.core.nms.anvil.AnvilCore { - @Override public CustomAnvil createAnvil(Player player) { return new AnvilView(((CraftPlayer) player).getHandle(), null); diff --git a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/anvil/AnvilInventoryCustom.java b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/anvil/AnvilInventoryCustom.java index 0577ccbd..65d3e4e3 100644 --- a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/anvil/AnvilInventoryCustom.java +++ b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/anvil/AnvilInventoryCustom.java @@ -7,11 +7,11 @@ import org.bukkit.craftbukkit.v1_12_R1.inventory.CraftInventoryAnvil; import org.bukkit.inventory.InventoryHolder; public class AnvilInventoryCustom extends CraftInventoryAnvil { - final InventoryHolder holder; public AnvilInventoryCustom(InventoryHolder holder, Location location, IInventory inventory, IInventory resultInventory, ContainerAnvil container) { super(location, inventory, resultInventory, container); + this.holder = holder; } diff --git a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/anvil/AnvilView.java b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/anvil/AnvilView.java index 20923a19..fe79bcb4 100644 --- a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/anvil/AnvilView.java +++ b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/anvil/AnvilView.java @@ -20,7 +20,6 @@ import java.util.logging.Level; import java.util.logging.Logger; public class AnvilView extends ContainerAnvil implements CustomAnvil { - private final EntityPlayer entity; private final Inventory inventory; private String title = "Repairing"; @@ -37,8 +36,10 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { try { mc_ContainerAnvil_repairInventory = ContainerAnvil.class.getDeclaredField("h"); mc_ContainerAnvil_repairInventory.setAccessible(true); + mc_ContainerAnvil_resultInventory = ContainerAnvil.class.getDeclaredField("g"); mc_ContainerAnvil_resultInventory.setAccessible(true); + mc_ContainerAnvil_bukkitEntity = ContainerAnvil.class.getDeclaredField("bukkitEntity"); mc_ContainerAnvil_bukkitEntity.setAccessible(true); } catch (Exception ex) { @@ -49,11 +50,13 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { public AnvilView(EntityPlayer entity, InventoryHolder holder) { super(entity.inventory, entity.world, new BlockPosition(0, 0, 0), entity); this.entity = entity; + if (holder != null) { this.inventory = getBukkitView(entity, holder).getTopInventory(); - } else { - this.inventory = getBukkitView().getTopInventory(); + return; } + + this.inventory = getBukkitView().getTopInventory(); } public CraftInventoryView getBukkitView(EntityHuman player, InventoryHolder holder) { @@ -64,10 +67,12 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { (IInventory) mc_ContainerAnvil_resultInventory.get(this), this); CraftInventoryView view = new CraftInventoryView(player.getBukkitEntity(), craftInventory, this); mc_ContainerAnvil_bukkitEntity.set(this, view); + return view; } catch (Exception ex) { Logger.getLogger(AnvilView.class.getName()).log(Level.SEVERE, "Anvil Setup Error", ex); } + return getBukkitView(); } @@ -79,6 +84,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void e() { super.e(); + if (cost >= 0) { this.levelCost = cost; } @@ -166,7 +172,6 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void open() { - // Counter stuff that the game uses to keep track of inventories int id = entity.nextContainerCounter(); diff --git a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/nbt/NBTCompoundImpl.java b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/nbt/NBTCompoundImpl.java index 213d07ca..20a878a0 100644 --- a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/nbt/NBTCompoundImpl.java +++ b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/nbt/NBTCompoundImpl.java @@ -15,7 +15,6 @@ import java.util.Set; import java.util.UUID; public class NBTCompoundImpl implements NBTCompound { - protected NBTTagCompound compound; protected NBTCompoundImpl(NBTTagCompound compound) { @@ -151,11 +150,11 @@ public class NBTCompoundImpl implements NBTCompound { public NBTCompound getCompound(String tag) { if (has(tag)) { return getNBTObject(tag).asCompound(); - } else { - NBTTagCompound newCompound = new NBTTagCompound(); - compound.set(tag, newCompound); - return new NBTCompoundImpl(newCompound); } + + NBTTagCompound newCompound = new NBTTagCompound(); + compound.set(tag, newCompound); + return new NBTCompoundImpl(newCompound); } @Override @@ -175,15 +174,17 @@ public class NBTCompoundImpl implements NBTCompound { addExtras(); NBTTagCompound compound = this.compound.g(); // Changed in 1.12 - for (String exclusion : exclusions) + for (String exclusion : exclusions) { compound.remove(exclusion); + } NBTCompressedStreamTools.a(compound, (OutputStream) dataOutput); return outputStream.toByteArray(); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } + return null; } @@ -192,8 +193,8 @@ public class NBTCompoundImpl implements NBTCompound { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(serialized); ObjectInputStream dataInput = new ObjectInputStream(inputStream)) { compound = NBTCompressedStreamTools.a((InputStream) dataInput); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } } diff --git a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/nbt/NBTCoreImpl.java b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/nbt/NBTCoreImpl.java index ec6ac7fd..2451f26c 100644 --- a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/nbt/NBTCoreImpl.java +++ b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/nbt/NBTCoreImpl.java @@ -10,7 +10,6 @@ import org.bukkit.entity.Entity; import org.bukkit.inventory.ItemStack; public class NBTCoreImpl implements NBTCore { - @Override public NBTItem of(ItemStack item) { return new NBTItemImpl(CraftItemStack.asNMSCopy(item)); @@ -26,6 +25,7 @@ public class NBTCoreImpl implements NBTCore { net.minecraft.server.v1_12_R1.Entity nmsEntity = ((CraftEntity) entity).getHandle(); NBTTagCompound nbt = new NBTTagCompound(); nmsEntity.save(nbt); + return new NBTEntityImpl(nbt, nmsEntity); } diff --git a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/nbt/NBTEntityImpl.java b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/nbt/NBTEntityImpl.java index 5b5592be..45aa80f4 100644 --- a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/nbt/NBTEntityImpl.java +++ b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/nbt/NBTEntityImpl.java @@ -11,11 +11,11 @@ import org.bukkit.craftbukkit.v1_12_R1.CraftWorld; import org.bukkit.event.entity.CreatureSpawnEvent; public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { - private Entity nmsEntity; public NBTEntityImpl(NBTTagCompound entityNBT, Entity nmsEntity) { super(entityNBT); + this.nmsEntity = nmsEntity; } @@ -36,21 +36,26 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { spawned.setLocation(location.getX(), location.getY(), location.getZ(), location.getPitch(), location.getYaw()); nmsEntity = spawned; + return entity; } + return null; } @Override public org.bukkit.entity.Entity reSpawn(Location location) { nmsEntity.dead = true; + return spawn(location); } @Override public void addExtras() { String key = EntityTypes.b(nmsEntity); // Changed in 1.12 - if (key != null) + + if (key != null) { compound.setString("entity_type", key); // Changed in 1.13 + } } } diff --git a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/nbt/NBTItemImpl.java b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/nbt/NBTItemImpl.java index e867af00..e7c993dd 100644 --- a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/nbt/NBTItemImpl.java @@ -6,20 +6,20 @@ import org.bukkit.craftbukkit.v1_12_R1.inventory.CraftItemStack; import org.bukkit.inventory.ItemStack; public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { - private final net.minecraft.server.v1_12_R1.ItemStack nmsItem; public NBTItemImpl(net.minecraft.server.v1_12_R1.ItemStack nmsItem) { super(nmsItem != null && nmsItem.hasTag() ? nmsItem.getTag() : new NBTTagCompound()); + this.nmsItem = nmsItem; } public ItemStack finish() { if (nmsItem == null) { return CraftItemStack.asBukkitCopy(new net.minecraft.server.v1_12_R1.ItemStack(compound)); - } else { - return CraftItemStack.asBukkitCopy(nmsItem); } + + return CraftItemStack.asBukkitCopy(nmsItem); } @Override diff --git a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/nbt/NBTObjectImpl.java b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/nbt/NBTObjectImpl.java index 397f66a0..8d866ac8 100644 --- a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/nbt/NBTObjectImpl.java +++ b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/nbt/NBTObjectImpl.java @@ -7,7 +7,6 @@ import net.minecraft.server.v1_12_R1.NBTTagCompound; import java.util.Set; public class NBTObjectImpl implements NBTObject { - private final NBTTagCompound compound; private final String tag; diff --git a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/world/SItemStackImpl.java b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/world/SItemStackImpl.java index 76f714b0..09487374 100644 --- a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/world/SItemStackImpl.java +++ b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/world/SItemStackImpl.java @@ -11,7 +11,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public class SItemStackImpl implements SItemStack { - private final ItemStack item; public SItemStackImpl(ItemStack item) { @@ -25,7 +24,9 @@ public class SItemStackImpl implements SItemStack { Vec3D vec3d = new Vec3D(((double) random.nextFloat() - 0.5D) * 0.1D, Math.random() * 0.1D + 0.1D, 0.0D); vec3d = vec3d.a(-entityPlayer.pitch * 0.017453292F); vec3d = vec3d.b(-entityPlayer.yaw * 0.017453292F); + double d0 = (double) (-random.nextFloat()) * 0.6D - 0.3D; + Vec3D vec3d1 = new Vec3D(((double) random.nextFloat() - 0.5D) * 0.3D, d0, 0.6D); vec3d1 = vec3d1.a(-entityPlayer.pitch * 0.017453292F); vec3d1 = vec3d1.b(-entityPlayer.yaw * 0.017453292F); diff --git a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/world/SSpawnerImpl.java b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/world/SSpawnerImpl.java index 666b897e..f2daa465 100644 --- a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/world/SSpawnerImpl.java +++ b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/world/SSpawnerImpl.java @@ -23,7 +23,6 @@ import java.util.Random; import java.util.Set; public class SSpawnerImpl implements SSpawner { - private final Location spawnerLocation; public SSpawnerImpl(Location location) { @@ -38,7 +37,6 @@ public class SSpawnerImpl implements SSpawner { @Override public LivingEntity spawnEntity(EntityType type, String particleType, SpawnedEntity spawned, Set canSpawnOn) { - MobSpawnerData data = new MobSpawnerData(); NBTTagCompound compound = data.b(); @@ -60,27 +58,30 @@ public class SSpawnerImpl implements SSpawner { BlockPosition position = entity.getChunkCoordinates(); DifficultyDamageScaler damageScaler = world.D(position); - if (!(entity instanceof EntityInsentient)) + if (!(entity instanceof EntityInsentient)) { continue; + } EntityInsentient entityInsentient = (EntityInsentient) entity; Location spot = new Location(spawnerLocation.getWorld(), x, y, z); - if (!canSpawn(entityInsentient, spot, canSpawnOn)) + if (!canSpawn(entityInsentient, spot, canSpawnOn)) { continue; + } entityInsentient.prepare(damageScaler, null); LivingEntity craftEntity = (LivingEntity) entity.getBukkitEntity(); - if (spawned != null) - if (!spawned.onSpawn(craftEntity)) - return null; + if (spawned != null && !spawned.onSpawn(craftEntity)) { + return null; + } if (particleType != null) { float xx = (float) (0 + (Math.random() * 1)); float yy = (float) (0 + (Math.random() * 2)); float zz = (float) (0 + (Math.random() * 1)); + CompatibleParticleHandler.spawnParticles(CompatibleParticleHandler.ParticleType.getParticle(particleType), spot, 5, xx, yy, zz, 0); } @@ -92,32 +93,37 @@ public class SSpawnerImpl implements SSpawner { return craftEntity; } + return null; } private boolean canSpawn(EntityInsentient entityInsentient, Location location, Set canSpawnOn) { - if (!entityInsentient.canSpawn()) + if (!entityInsentient.canSpawn()) { return false; + } CompatibleMaterial spawnedIn = CompatibleMaterial.getMaterial(location.getBlock()); CompatibleMaterial spawnedOn = CompatibleMaterial.getMaterial(location.getBlock().getRelative(BlockFace.DOWN)); - if (spawnedIn == null || spawnedOn == null) + if (spawnedIn == null || spawnedOn == null) { return false; + } - if (!spawnedIn.isAir() - && spawnedIn != CompatibleMaterial.WATER - && !spawnedIn.name().contains("PRESSURE") - && !spawnedIn.name().contains("SLAB")) { + if (!spawnedIn.isAir() && + spawnedIn != CompatibleMaterial.WATER && + !spawnedIn.name().contains("PRESSURE") && + !spawnedIn.name().contains("SLAB")) { return false; } for (CompatibleMaterial material : canSpawnOn) { if (material == null) continue; - if (spawnedOn.equals(material) || material.isAir()) + if (spawnedOn.equals(material) || material.isAir()) { return true; + } } + return false; } } diff --git a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/world/SWorldImpl.java b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/world/SWorldImpl.java index bd345094..6015dc65 100644 --- a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/world/SWorldImpl.java +++ b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/world/SWorldImpl.java @@ -7,7 +7,6 @@ import java.util.ArrayList; import java.util.List; public class SWorldImpl implements SWorld { - public SWorldImpl() { } diff --git a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/world/WorldCoreImpl.java b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/world/WorldCoreImpl.java index baa8c509..447c2624 100644 --- a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/world/WorldCoreImpl.java +++ b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/world/WorldCoreImpl.java @@ -56,28 +56,30 @@ public class WorldCoreImpl implements WorldCore { public void randomTickChunk(org.bukkit.Chunk bukkitChunk, int tickAmount) throws NoSuchFieldException, IllegalAccessException { Chunk chunk = ((CraftChunk) bukkitChunk).getHandle(); - if (tickAmount > 0) { - int j = chunk.locX * 16; - int k = chunk.locZ * 16; + if (tickAmount <= 0) { + return; + } - for (ChunkSection chunksection : chunk.getSections()) { - if (chunksection != net.minecraft.server.v1_12_R1.Chunk.a && chunksection.shouldTick()) { - for (int k1 = 0; k1 < tickAmount; ++k1) { - int worldL = (int) ReflectionUtils.getFieldValue(chunk.world, "l"); - worldL = worldL * 3 + 1013904223; - ReflectionUtils.setFieldValue(chunk.world, "l", worldL); + int j = chunk.locX * 16; + int k = chunk.locZ * 16; - int l1 = worldL >> 2; - int i2 = l1 & 15; - int j2 = l1 >> 8 & 15; - int k2 = l1 >> 16 & 15; + for (ChunkSection chunksection : chunk.getSections()) { + if (chunksection != net.minecraft.server.v1_12_R1.Chunk.a && chunksection.shouldTick()) { + for (int k1 = 0; k1 < tickAmount; ++k1) { + int worldL = (int) ReflectionUtils.getFieldValue(chunk.world, "l"); + worldL = worldL * 3 + 1013904223; + ReflectionUtils.setFieldValue(chunk.world, "l", worldL); - IBlockData iblockdata = chunksection.getType(i2, k2, j2); - Block block = iblockdata.getBlock(); + int l1 = worldL >> 2; + int i2 = l1 & 15; + int j2 = l1 >> 8 & 15; + int k2 = l1 >> 16 & 15; - if (block.isTicking()) { - block.a(chunk.world, new BlockPosition(i2 + j, k2 + chunksection.getYPosition(), j2 + k), iblockdata, chunk.world.random); - } + IBlockData iblockdata = chunksection.getType(i2, k2, j2); + Block block = iblockdata.getBlock(); + + if (block.isTicking()) { + block.a(chunk.world, new BlockPosition(i2 + j, k2 + chunksection.getYPosition(), j2 + k), iblockdata, chunk.world.random); } } } diff --git a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/world/spawner/BBaseSpawnerImpl.java b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/world/spawner/BBaseSpawnerImpl.java index 47501034..d94b34a9 100644 --- a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/world/spawner/BBaseSpawnerImpl.java +++ b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/world/spawner/BBaseSpawnerImpl.java @@ -72,85 +72,87 @@ public class BBaseSpawnerImpl implements BBaseSpawner { ReflectionUtils.setFieldValue(spawner, "e", spawnerD); ReflectionUtils.setFieldValue(spawner, "d", (spawnerD + (double) (1000F / ((float) spawner.spawnDelay + 200F))) % 360D); - } else { - if (spawner.spawnDelay == -1) { - delay(spawner); + return; + } + + if (spawner.spawnDelay == -1) { + delay(spawner); + } + + if (spawner.spawnDelay > 0) { + --spawner.spawnDelay; + return; + } + + boolean flag = false; + int i = 0; + + MobSpawnerData spawnData = (MobSpawnerData) ReflectionUtils.getFieldValue(spawner, "spawnData"); + + while (true) { + if (i >= spawner.spawnCount) { + if (flag) { + delay(spawner); + } + + break; } - if (spawner.spawnDelay > 0) { - --spawner.spawnDelay; + NBTTagCompound nbttagcompound = spawnData.b(); + NBTTagList nbttaglist = nbttagcompound.getList("Pos", 6); + + net.minecraft.server.v1_12_R1.World world = spawner.a(); + + int j = nbttaglist.size(); + double d3 = j >= 1 ? nbttaglist.f(0) : (double) blockposition.getX() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; + double d4 = j >= 2 ? nbttaglist.f(1) : (double) (blockposition.getY() + world.random.nextInt(3) - 1); + double d5 = j >= 3 ? nbttaglist.f(2) : (double) blockposition.getZ() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; + + Entity entity = ChunkRegionLoader.a(nbttagcompound, world, d3, d4, d5, false); + + if (entity == null) { return; } - boolean flag = false; - int i = 0; + int k = world.a(entity.getClass(), (new AxisAlignedBB( + blockposition.getX(), + blockposition.getY(), + blockposition.getZ(), + blockposition.getX() + 1, + blockposition.getY() + 1, + blockposition.getZ() + 1)) + .g(spawner.spawnRange)).size(); - MobSpawnerData spawnData = (MobSpawnerData) ReflectionUtils.getFieldValue(spawner, "spawnData"); - - while (true) { - if (i >= spawner.spawnCount) { - if (flag) { - delay(spawner); - } - break; - } - - NBTTagCompound nbttagcompound = spawnData.b(); - NBTTagList nbttaglist = nbttagcompound.getList("Pos", 6); - - net.minecraft.server.v1_12_R1.World world = spawner.a(); - - int j = nbttaglist.size(); - double d3 = j >= 1 ? nbttaglist.f(0) : (double) blockposition.getX() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; - double d4 = j >= 2 ? nbttaglist.f(1) : (double) (blockposition.getY() + world.random.nextInt(3) - 1); - double d5 = j >= 3 ? nbttaglist.f(2) : (double) blockposition.getZ() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; - - Entity entity = ChunkRegionLoader.a(nbttagcompound, world, d3, d4, d5, false); - - if (entity == null) { - return; - } - - int k = world.a(entity.getClass(), (new AxisAlignedBB( - blockposition.getX(), - blockposition.getY(), - blockposition.getZ(), - blockposition.getX() + 1, - blockposition.getY() + 1, - blockposition.getZ() + 1)) - .g(spawner.spawnRange)).size(); - - if (k >= spawner.maxNearbyEntities) { - delay(spawner); - return; - } - - EntityInsentient entityinsentient = entity instanceof EntityInsentient ? (EntityInsentient) entity : null; - entity.setPositionRotation(entity.locX, entity.locY, entity.locZ, world.random.nextFloat() * 360.0F, 0.0F); - - if (entityinsentient == null || entityinsentient.P() && entityinsentient.canSpawn()) { - if (spawnData.b().d() == 1 && spawnData.b().hasKeyOfType("id", 8) && entity instanceof EntityInsentient) { - ((EntityInsentient) entity).prepare(world.D(new BlockPosition(entity)), null); - } - - if (entity.world.spigotConfig.nerfSpawnerMobs) { - entity.fromMobSpawner = true; - } - - if (!CraftEventFactory.callSpawnerSpawnEvent(entity, blockposition).isCancelled()) { - ChunkRegionLoader.a(entity, world, CreatureSpawnEvent.SpawnReason.SPAWNER); - world.triggerEffect(2004, blockposition, 0); - - if (entityinsentient != null) { - entityinsentient.doSpawnEffect(); - } - - flag = true; - } - } - - ++i; + if (k >= spawner.maxNearbyEntities) { + delay(spawner); + return; } + + EntityInsentient entityinsentient = entity instanceof EntityInsentient ? (EntityInsentient) entity : null; + entity.setPositionRotation(entity.locX, entity.locY, entity.locZ, world.random.nextFloat() * 360.0F, 0.0F); + + if (entityinsentient == null || entityinsentient.P() && entityinsentient.canSpawn()) { + if (spawnData.b().d() == 1 && spawnData.b().hasKeyOfType("id", 8) && entity instanceof EntityInsentient) { + ((EntityInsentient) entity).prepare(world.D(new BlockPosition(entity)), null); + } + + if (entity.world.spigotConfig.nerfSpawnerMobs) { + entity.fromMobSpawner = true; + } + + if (!CraftEventFactory.callSpawnerSpawnEvent(entity, blockposition).isCancelled()) { + ChunkRegionLoader.a(entity, world, CreatureSpawnEvent.SpawnReason.SPAWNER); + world.triggerEffect(2004, blockposition, 0); + + if (entityinsentient != null) { + entityinsentient.doSpawnEffect(); + } + + flag = true; + } + } + + ++i; } } @@ -161,4 +163,4 @@ public class BBaseSpawnerImpl implements BBaseSpawner { private void delay(MobSpawnerAbstract spawner) throws InvocationTargetException, IllegalAccessException { iMethod.invoke(spawner); } -} \ No newline at end of file +} diff --git a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/anvil/AnvilCore.java b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/anvil/AnvilCore.java index f228650a..8bfec14d 100644 --- a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/anvil/AnvilCore.java +++ b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/anvil/AnvilCore.java @@ -6,7 +6,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; public class AnvilCore implements com.songoda.core.nms.anvil.AnvilCore { - @Override public CustomAnvil createAnvil(Player player) { return new AnvilView(((CraftPlayer) player).getHandle(), null); diff --git a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/anvil/AnvilInventoryCustom.java b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/anvil/AnvilInventoryCustom.java index 2d008ed7..64f08a2e 100644 --- a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/anvil/AnvilInventoryCustom.java +++ b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/anvil/AnvilInventoryCustom.java @@ -7,7 +7,6 @@ import org.bukkit.craftbukkit.v1_13_R1.inventory.CraftInventoryAnvil; import org.bukkit.inventory.InventoryHolder; public class AnvilInventoryCustom extends CraftInventoryAnvil { - final InventoryHolder holder; public AnvilInventoryCustom(InventoryHolder holder, Location location, IInventory inventory, IInventory resultInventory, ContainerAnvil container) { diff --git a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/anvil/AnvilView.java b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/anvil/AnvilView.java index 51391e63..67429038 100644 --- a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/anvil/AnvilView.java +++ b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/anvil/AnvilView.java @@ -20,7 +20,6 @@ import java.util.logging.Level; import java.util.logging.Logger; public class AnvilView extends ContainerAnvil implements CustomAnvil { - private final EntityPlayer entity; private final Inventory inventory; private String title = "Repairing"; @@ -37,8 +36,10 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { try { mc_ContainerAnvil_repairInventory = ContainerAnvil.class.getDeclaredField("repairInventory"); mc_ContainerAnvil_repairInventory.setAccessible(true); + mc_ContainerAnvil_resultInventory = ContainerAnvil.class.getDeclaredField("resultInventory"); mc_ContainerAnvil_resultInventory.setAccessible(true); + mc_ContainerAnvil_bukkitEntity = ContainerAnvil.class.getDeclaredField("bukkitEntity"); mc_ContainerAnvil_bukkitEntity.setAccessible(true); } catch (Exception ex) { @@ -48,13 +49,16 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { public AnvilView(EntityPlayer entity, InventoryHolder holder) { super(entity.inventory, entity.world, new BlockPosition(0, 0, 0), entity); + this.checkReachable = false; this.entity = entity; + if (holder != null) { this.inventory = getBukkitView(entity, holder).getTopInventory(); - } else { - this.inventory = getBukkitView().getTopInventory(); + return; } + + this.inventory = getBukkitView().getTopInventory(); } public CraftInventoryView getBukkitView(EntityHuman player, InventoryHolder holder) { @@ -65,10 +69,12 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { (IInventory) mc_ContainerAnvil_resultInventory.get(this), this); CraftInventoryView view = new CraftInventoryView(player.getBukkitEntity(), craftInventory, this); mc_ContainerAnvil_bukkitEntity.set(this, view); + return view; } catch (Exception ex) { Logger.getLogger(AnvilView.class.getName()).log(Level.SEVERE, "Anvil Setup Error", ex); } + return getBukkitView(); } @@ -80,6 +86,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void d() { super.d(); + if (cost >= 0) { this.levelCost = cost; } @@ -167,7 +174,6 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void open() { - // Counter stuff that the game uses to keep track of inventories int id = entity.nextContainerCounter(); diff --git a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/nbt/NBTCompoundImpl.java b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/nbt/NBTCompoundImpl.java index 9c689459..92bf5f5f 100644 --- a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/nbt/NBTCompoundImpl.java +++ b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/nbt/NBTCompoundImpl.java @@ -15,7 +15,6 @@ import java.util.Set; import java.util.UUID; public class NBTCompoundImpl implements NBTCompound { - protected NBTTagCompound compound; protected NBTCompoundImpl(NBTTagCompound compound) { @@ -151,11 +150,11 @@ public class NBTCompoundImpl implements NBTCompound { public NBTCompound getCompound(String tag) { if (has(tag)) { return getNBTObject(tag).asCompound(); - } else { - NBTTagCompound newCompound = new NBTTagCompound(); - compound.set(tag, newCompound); - return new NBTCompoundImpl(newCompound); } + + NBTTagCompound newCompound = new NBTTagCompound(); + compound.set(tag, newCompound); + return new NBTCompoundImpl(newCompound); } @Override @@ -175,15 +174,17 @@ public class NBTCompoundImpl implements NBTCompound { addExtras(); NBTTagCompound compound = this.compound.clone(); - for (String exclusion : exclusions) + for (String exclusion : exclusions) { compound.remove(exclusion); + } NBTCompressedStreamTools.a(compound, (OutputStream) dataOutput); return outputStream.toByteArray(); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } + return null; } @@ -192,8 +193,8 @@ public class NBTCompoundImpl implements NBTCompound { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(serialized); ObjectInputStream dataInput = new ObjectInputStream(inputStream)) { compound = NBTCompressedStreamTools.a((InputStream) dataInput); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } } diff --git a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/nbt/NBTCoreImpl.java b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/nbt/NBTCoreImpl.java index 0e1729bf..761ebdcb 100644 --- a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/nbt/NBTCoreImpl.java +++ b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/nbt/NBTCoreImpl.java @@ -10,7 +10,6 @@ import org.bukkit.entity.Entity; import org.bukkit.inventory.ItemStack; public class NBTCoreImpl implements NBTCore { - @Override public NBTItem of(ItemStack item) { return new NBTItemImpl(CraftItemStack.asNMSCopy(item)); @@ -26,6 +25,7 @@ public class NBTCoreImpl implements NBTCore { net.minecraft.server.v1_13_R1.Entity nmsEntity = ((CraftEntity) entity).getHandle(); NBTTagCompound nbt = new NBTTagCompound(); nmsEntity.save(nbt); + return new NBTEntityImpl(nbt, nmsEntity); } diff --git a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/nbt/NBTEntityImpl.java b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/nbt/NBTEntityImpl.java index 4055a0ca..ded0cccb 100644 --- a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/nbt/NBTEntityImpl.java +++ b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/nbt/NBTEntityImpl.java @@ -13,11 +13,11 @@ import org.bukkit.event.entity.CreatureSpawnEvent; import java.util.Optional; public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { - private Entity nmsEntity; public NBTEntityImpl(NBTTagCompound entityNBT, Entity nmsEntity) { super(entityNBT); + this.nmsEntity = nmsEntity; } @@ -45,9 +45,11 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { spawned.setLocation(location.getX(), location.getY(), location.getZ(), location.getPitch(), location.getYaw()); nmsEntity = spawned; + return entity; } } + return null; } @@ -60,7 +62,9 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { @Override public void addExtras() { MinecraftKey key = EntityTypes.REGISTRY.b(nmsEntity.P()); // Changed in 1.13 - if (key != null) + + if (key != null) { compound.setString("entity_type", key.toString()); // Changed in 1.13 + } } } diff --git a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/nbt/NBTItemImpl.java b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/nbt/NBTItemImpl.java index 5824da51..d9bcb839 100644 --- a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/nbt/NBTItemImpl.java @@ -6,20 +6,20 @@ import org.bukkit.craftbukkit.v1_13_R1.inventory.CraftItemStack; import org.bukkit.inventory.ItemStack; public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { - private final net.minecraft.server.v1_13_R1.ItemStack nmsItem; public NBTItemImpl(net.minecraft.server.v1_13_R1.ItemStack nmsItem) { super(nmsItem != null && nmsItem.hasTag() ? nmsItem.getTag() : new NBTTagCompound()); + this.nmsItem = nmsItem; } public ItemStack finish() { if (nmsItem == null) { return CraftItemStack.asBukkitCopy(net.minecraft.server.v1_13_R1.ItemStack.a(compound)); - } else { - return CraftItemStack.asBukkitCopy(nmsItem); } + + return CraftItemStack.asBukkitCopy(nmsItem); } @Override diff --git a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/nbt/NBTObjectImpl.java b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/nbt/NBTObjectImpl.java index b5bdaa97..bb2ad599 100644 --- a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/nbt/NBTObjectImpl.java +++ b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/nbt/NBTObjectImpl.java @@ -7,7 +7,6 @@ import net.minecraft.server.v1_13_R1.NBTTagCompound; import java.util.Set; public class NBTObjectImpl implements NBTObject { - private final NBTTagCompound compound; private final String tag; diff --git a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/world/SItemStackImpl.java b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/world/SItemStackImpl.java index 8b596578..8bcd13ae 100644 --- a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/world/SItemStackImpl.java +++ b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/world/SItemStackImpl.java @@ -11,7 +11,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public class SItemStackImpl implements SItemStack { - private final ItemStack item; public SItemStackImpl(ItemStack item) { @@ -21,15 +20,19 @@ public class SItemStackImpl implements SItemStack { @Override public void breakItem(Player player, int amount) { EntityPlayer entityPlayer = ((CraftPlayer) player).getHandle(); + for (int i = 0; i < amount; ++i) { Vec3D vec3d = new Vec3D(((double) this.random.nextFloat() - 0.5D) * 0.1D, Math.random() * 0.1D + 0.1D, 0.0D); vec3d = vec3d.a(-entityPlayer.pitch * 0.017453292F); vec3d = vec3d.b(-entityPlayer.yaw * 0.017453292F); + double d0 = (double) (-this.random.nextFloat()) * 0.6D - 0.3D; + Vec3D vec3d1 = new Vec3D(((double) this.random.nextFloat() - 0.5D) * 0.3D, d0, 0.6D); vec3d1 = vec3d1.a(-entityPlayer.pitch * 0.017453292F); vec3d1 = vec3d1.b(-entityPlayer.yaw * 0.017453292F); vec3d1 = vec3d1.add(entityPlayer.locX, entityPlayer.locY + (double) entityPlayer.getHeadHeight(), entityPlayer.locZ); + entityPlayer.world.addParticle(new ParticleParamItem(Particles.C, CraftItemStack.asNMSCopy(item)), vec3d1.x, vec3d1.y, vec3d1.z, vec3d.x, vec3d.y + 0.05D, vec3d.z); } } diff --git a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/world/SSpawnerImpl.java b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/world/SSpawnerImpl.java index 957ceb98..6ebf5519 100644 --- a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/world/SSpawnerImpl.java +++ b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/world/SSpawnerImpl.java @@ -23,7 +23,6 @@ import java.util.Random; import java.util.Set; public class SSpawnerImpl implements SSpawner { - private final Location spawnerLocation; public SSpawnerImpl(Location location) { @@ -38,7 +37,6 @@ public class SSpawnerImpl implements SSpawner { @Override public LivingEntity spawnEntity(EntityType type, String particleType, SpawnedEntity spawned, Set canSpawnOn) { - MobSpawnerData data = new MobSpawnerData(); NBTTagCompound compound = data.b(); @@ -60,27 +58,30 @@ public class SSpawnerImpl implements SSpawner { BlockPosition position = entity.getChunkCoordinates(); DifficultyDamageScaler damageScaler = world.getDamageScaler(position); - if (!(entity instanceof EntityInsentient)) + if (!(entity instanceof EntityInsentient)) { continue; + } EntityInsentient entityInsentient = (EntityInsentient) entity; Location spot = new Location(spawnerLocation.getWorld(), x, y, z); - if (!canSpawn(world, entityInsentient, spot, canSpawnOn)) + if (!canSpawn(world, entityInsentient, spot, canSpawnOn)) { continue; + } entityInsentient.prepare(damageScaler, null, null); LivingEntity craftEntity = (LivingEntity) entity.getBukkitEntity(); - if (spawned != null) - if (!spawned.onSpawn(craftEntity)) - return null; + if (spawned != null && !spawned.onSpawn(craftEntity)) { + return null; + } if (particleType != null) { float xx = (float) (0 + (Math.random() * 1)); float yy = (float) (0 + (Math.random() * 2)); float zz = (float) (0 + (Math.random() * 1)); + CompatibleParticleHandler.spawnParticles(CompatibleParticleHandler.ParticleType.getParticle(particleType), spot, 5, xx, yy, zz, 0); } @@ -92,34 +93,38 @@ public class SSpawnerImpl implements SSpawner { return craftEntity; } + return null; } private boolean canSpawn(WorldServer world, EntityInsentient entityInsentient, Location location, Set canSpawnOn) { - - if (!world.getCubes(entityInsentient, entityInsentient.getBoundingBox())) + if (!world.getCubes(entityInsentient, entityInsentient.getBoundingBox())) { return false; + } CompatibleMaterial spawnedIn = CompatibleMaterial.getMaterial(location.getBlock()); CompatibleMaterial spawnedOn = CompatibleMaterial.getMaterial(location.getBlock().getRelative(BlockFace.DOWN)); - if (spawnedIn == null || spawnedOn == null) + if (spawnedIn == null || spawnedOn == null) { return false; + } - if (!spawnedIn.isAir() - && spawnedIn != CompatibleMaterial.WATER - && !spawnedIn.name().contains("PRESSURE") - && !spawnedIn.name().contains("SLAB")) { + if (!spawnedIn.isAir() && + spawnedIn != CompatibleMaterial.WATER && + !spawnedIn.name().contains("PRESSURE") && + !spawnedIn.name().contains("SLAB")) { return false; } for (CompatibleMaterial material : canSpawnOn) { if (material == null) continue; - if (spawnedOn.equals(material) || material.isAir()) + if (spawnedOn.equals(material) || material.isAir()) { return true; + } } + return false; } } diff --git a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/world/SWorldImpl.java b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/world/SWorldImpl.java index 1c2fc6e4..78312506 100644 --- a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/world/SWorldImpl.java +++ b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/world/SWorldImpl.java @@ -7,7 +7,6 @@ import java.util.ArrayList; import java.util.List; public class SWorldImpl implements SWorld { - public SWorldImpl() { } diff --git a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/world/WorldCoreImpl.java b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/world/WorldCoreImpl.java index 3ccf1900..3e34e414 100644 --- a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/world/WorldCoreImpl.java +++ b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/world/WorldCoreImpl.java @@ -56,32 +56,34 @@ public class WorldCoreImpl implements WorldCore { public void randomTickChunk(org.bukkit.Chunk bukkitChunk, int tickAmount) throws NoSuchFieldException, IllegalAccessException { Chunk chunk = ((CraftChunk) bukkitChunk).getHandle(); - if (tickAmount > 0) { - int j = chunk.locX * 16; - int k = chunk.locZ * 16; + if (tickAmount <= 0) { + return; + } - for (ChunkSection chunksection : chunk.getSections()) { - if (chunksection != net.minecraft.server.v1_13_R1.Chunk.a && chunksection.b()) { - for (int i = 0; i < tickAmount; ++i) { - int worldM = (int) ReflectionUtils.getFieldValue(chunk.world, "m"); - worldM = worldM * 3 + 1013904223; - ReflectionUtils.setFieldValue(chunk.world, "m", worldM); + int j = chunk.locX * 16; + int k = chunk.locZ * 16; - int l1 = worldM >> 2; - int i2 = l1 & 15; - int j2 = l1 >> 8 & 15; - int k2 = l1 >> 16 & 15; + for (ChunkSection chunksection : chunk.getSections()) { + if (chunksection != net.minecraft.server.v1_13_R1.Chunk.a && chunksection.b()) { + for (int i = 0; i < tickAmount; ++i) { + int worldM = (int) ReflectionUtils.getFieldValue(chunk.world, "m"); + worldM = worldM * 3 + 1013904223; + ReflectionUtils.setFieldValue(chunk.world, "m", worldM); - IBlockData iblockdata = chunksection.getType(i2, k2, j2); - Fluid fluid = chunksection.b(i2, k2, j2); + int l1 = worldM >> 2; + int i2 = l1 & 15; + int j2 = l1 >> 8 & 15; + int k2 = l1 >> 16 & 15; - if (iblockdata.t()) { - iblockdata.b(chunk.world, new BlockPosition(i2 + j, k2 + chunksection.getYPosition(), j2 + k), chunk.world.random); - } + IBlockData iblockdata = chunksection.getType(i2, k2, j2); + Fluid fluid = chunksection.b(i2, k2, j2); - if (fluid.h()) { - fluid.b(chunk.world, new BlockPosition(i2 + j, k2 + chunksection.getYPosition(), j2 + k), chunk.world.random); - } + if (iblockdata.t()) { + iblockdata.b(chunk.world, new BlockPosition(i2 + j, k2 + chunksection.getYPosition(), j2 + k), chunk.world.random); + } + + if (fluid.h()) { + fluid.b(chunk.world, new BlockPosition(i2 + j, k2 + chunksection.getYPosition(), j2 + k), chunk.world.random); } } } diff --git a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/world/spawner/BBaseSpawnerImpl.java b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/world/spawner/BBaseSpawnerImpl.java index f19c4c64..53beaaa8 100644 --- a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/world/spawner/BBaseSpawnerImpl.java +++ b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/world/spawner/BBaseSpawnerImpl.java @@ -74,86 +74,87 @@ public class BBaseSpawnerImpl implements BBaseSpawner { ReflectionUtils.setFieldValue(spawner, "f", spawnerE); ReflectionUtils.setFieldValue(spawner, "e", (spawnerE + (double) (1000F / ((float) spawner.spawnDelay + 200F))) % 360D); - } else { - if (spawner.spawnDelay == -1) { - delay(spawner); + return; + } + + if (spawner.spawnDelay == -1) { + delay(spawner); + } + + if (spawner.spawnDelay > 0) { + --spawner.spawnDelay; + return; + } + + boolean flag = false; + int i = 0; + + MobSpawnerData spawnData = (MobSpawnerData) ReflectionUtils.getFieldValue(spawner, "spawnData"); + + while (true) { + if (i >= spawner.spawnCount) { + if (flag) { + delay(spawner); + } + + break; } - if (spawner.spawnDelay > 0) { - --spawner.spawnDelay; + NBTTagCompound nbttagcompound = spawnData.b(); + NBTTagList nbttaglist = nbttagcompound.getList("Pos", 6); + + net.minecraft.server.v1_13_R1.World world = spawner.a(); + + int j = nbttaglist.size(); + double d3 = j >= 1 ? nbttaglist.k(0) : (double) blockposition.getX() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; + double d4 = j >= 2 ? nbttaglist.k(1) : (double) (blockposition.getY() + world.random.nextInt(3) - 1); + double d5 = j >= 3 ? nbttaglist.k(2) : (double) blockposition.getZ() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; + + Entity entity = ChunkRegionLoader.a(nbttagcompound, world, d3, d4, d5, false); + + if (entity == null) { + delay(spawner); return; } - boolean flag = false; - int i = 0; + int k = world.a(entity.getClass(), (new AxisAlignedBB(blockposition.getX(), + blockposition.getY(), + blockposition.getZ(), + blockposition.getX() + 1, + blockposition.getY() + 1, + blockposition.getZ() + 1)) + .g(spawner.spawnRange)).size(); - MobSpawnerData spawnData = (MobSpawnerData) ReflectionUtils.getFieldValue(spawner, "spawnData"); - - while (true) { - if (i >= spawner.spawnCount) { - if (flag) { - delay(spawner); - } - - break; - } - - NBTTagCompound nbttagcompound = spawnData.b(); - NBTTagList nbttaglist = nbttagcompound.getList("Pos", 6); - - net.minecraft.server.v1_13_R1.World world = spawner.a(); - - int j = nbttaglist.size(); - double d3 = j >= 1 ? nbttaglist.k(0) : (double) blockposition.getX() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; - double d4 = j >= 2 ? nbttaglist.k(1) : (double) (blockposition.getY() + world.random.nextInt(3) - 1); - double d5 = j >= 3 ? nbttaglist.k(2) : (double) blockposition.getZ() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; - - Entity entity = ChunkRegionLoader.a(nbttagcompound, world, d3, d4, d5, false); - - if (entity == null) { - delay(spawner); - return; - } - - int k = world.a(entity.getClass(), (new AxisAlignedBB(blockposition.getX(), - blockposition.getY(), - blockposition.getZ(), - blockposition.getX() + 1, - blockposition.getY() + 1, - blockposition.getZ() + 1)) - .g(spawner.spawnRange)).size(); - - if (k >= spawner.maxNearbyEntities) { - delay(spawner); - return; - } - - EntityInsentient entityinsentient = entity instanceof EntityInsentient ? (EntityInsentient) entity : null; - entity.setPositionRotation(entity.locX, entity.locY, entity.locZ, world.random.nextFloat() * 360F, 0F); - - if (entityinsentient == null || entityinsentient.M() && entityinsentient.canSpawn()) { - if (spawnData.b().d() == 1 && spawnData.b().hasKeyOfType("id", 8) && entity instanceof EntityInsentient) { - ((EntityInsentient) entity).prepare(world.getDamageScaler(new BlockPosition(entity)), null, null); - } - - if (entity.world.spigotConfig.nerfSpawnerMobs) { - entity.fromMobSpawner = true; - } - - if (!CraftEventFactory.callSpawnerSpawnEvent(entity, blockposition).isCancelled()) { - ChunkRegionLoader.a(entity, world, CreatureSpawnEvent.SpawnReason.SPAWNER); - world.triggerEffect(2004, blockposition, 0); - - if (entityinsentient != null) { - entityinsentient.doSpawnEffect(); - } - - flag = true; - } - } - - ++i; + if (k >= spawner.maxNearbyEntities) { + delay(spawner); + return; } + + EntityInsentient entityinsentient = entity instanceof EntityInsentient ? (EntityInsentient) entity : null; + entity.setPositionRotation(entity.locX, entity.locY, entity.locZ, world.random.nextFloat() * 360F, 0F); + + if (entityinsentient == null || entityinsentient.M() && entityinsentient.canSpawn()) { + if (spawnData.b().d() == 1 && spawnData.b().hasKeyOfType("id", 8) && entity instanceof EntityInsentient) { + ((EntityInsentient) entity).prepare(world.getDamageScaler(new BlockPosition(entity)), null, null); + } + + if (entity.world.spigotConfig.nerfSpawnerMobs) { + entity.fromMobSpawner = true; + } + + if (!CraftEventFactory.callSpawnerSpawnEvent(entity, blockposition).isCancelled()) { + ChunkRegionLoader.a(entity, world, CreatureSpawnEvent.SpawnReason.SPAWNER); + world.triggerEffect(2004, blockposition, 0); + + if (entityinsentient != null) { + entityinsentient.doSpawnEffect(); + } + + flag = true; + } + } + + ++i; } } diff --git a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/anvil/AnvilCore.java b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/anvil/AnvilCore.java index 90991c72..7737b382 100644 --- a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/anvil/AnvilCore.java +++ b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/anvil/AnvilCore.java @@ -6,7 +6,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; public class AnvilCore implements com.songoda.core.nms.anvil.AnvilCore { - @Override public CustomAnvil createAnvil(Player player) { return new AnvilView(((CraftPlayer) player).getHandle(), null); diff --git a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/anvil/AnvilInventoryCustom.java b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/anvil/AnvilInventoryCustom.java index a337b49b..dde0402f 100644 --- a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/anvil/AnvilInventoryCustom.java +++ b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/anvil/AnvilInventoryCustom.java @@ -7,7 +7,6 @@ import org.bukkit.craftbukkit.v1_13_R2.inventory.CraftInventoryAnvil; import org.bukkit.inventory.InventoryHolder; public class AnvilInventoryCustom extends CraftInventoryAnvil { - final InventoryHolder holder; public AnvilInventoryCustom(InventoryHolder holder, Location location, IInventory inventory, IInventory resultInventory, ContainerAnvil container) { diff --git a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/anvil/AnvilView.java b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/anvil/AnvilView.java index 7e4fa62f..6f357a06 100644 --- a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/anvil/AnvilView.java +++ b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/anvil/AnvilView.java @@ -20,7 +20,6 @@ import java.util.logging.Level; import java.util.logging.Logger; public class AnvilView extends ContainerAnvil implements CustomAnvil { - private final EntityPlayer entity; private final Inventory inventory; private String title = "Repairing"; @@ -37,8 +36,10 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { try { mc_ContainerAnvil_repairInventory = ContainerAnvil.class.getDeclaredField("repairInventory"); mc_ContainerAnvil_repairInventory.setAccessible(true); + mc_ContainerAnvil_resultInventory = ContainerAnvil.class.getDeclaredField("resultInventory"); mc_ContainerAnvil_resultInventory.setAccessible(true); + mc_ContainerAnvil_bukkitEntity = ContainerAnvil.class.getDeclaredField("bukkitEntity"); mc_ContainerAnvil_bukkitEntity.setAccessible(true); } catch (Exception ex) { @@ -48,8 +49,10 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { public AnvilView(EntityPlayer entity, InventoryHolder holder) { super(entity.inventory, entity.world, new BlockPosition(0, 0, 0), entity); + this.checkReachable = false; this.entity = entity; + if (holder != null) { this.inventory = getBukkitView(entity, holder).getTopInventory(); } else { @@ -65,10 +68,12 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { (IInventory) mc_ContainerAnvil_resultInventory.get(this), this); CraftInventoryView view = new CraftInventoryView(player.getBukkitEntity(), craftInventory, this); mc_ContainerAnvil_bukkitEntity.set(this, view); + return view; } catch (Exception ex) { Logger.getLogger(AnvilView.class.getName()).log(Level.SEVERE, "Anvil Setup Error", ex); } + return getBukkitView(); } @@ -80,6 +85,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void d() { super.d(); + if (cost >= 0) { this.levelCost = cost; } @@ -167,7 +173,6 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void open() { - // Counter stuff that the game uses to keep track of inventories int id = entity.nextContainerCounter(); diff --git a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/nbt/NBTCompoundImpl.java b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/nbt/NBTCompoundImpl.java index cd7adc73..6fd969b9 100644 --- a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/nbt/NBTCompoundImpl.java +++ b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/nbt/NBTCompoundImpl.java @@ -15,7 +15,6 @@ import java.util.Set; import java.util.UUID; public class NBTCompoundImpl implements NBTCompound { - protected NBTTagCompound compound; protected NBTCompoundImpl(NBTTagCompound compound) { @@ -151,11 +150,11 @@ public class NBTCompoundImpl implements NBTCompound { public NBTCompound getCompound(String tag) { if (has(tag)) { return getNBTObject(tag).asCompound(); - } else { - NBTTagCompound newCompound = new NBTTagCompound(); - compound.set(tag, newCompound); - return new NBTCompoundImpl(newCompound); } + + NBTTagCompound newCompound = new NBTTagCompound(); + compound.set(tag, newCompound); + return new NBTCompoundImpl(newCompound); } @Override @@ -181,9 +180,10 @@ public class NBTCompoundImpl implements NBTCompound { NBTCompressedStreamTools.a(compound, (OutputStream) dataOutput); return outputStream.toByteArray(); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } + return null; } @@ -192,8 +192,8 @@ public class NBTCompoundImpl implements NBTCompound { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(serialized); ObjectInputStream dataInput = new ObjectInputStream(inputStream)) { compound = NBTCompressedStreamTools.a((InputStream) dataInput); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } } diff --git a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/nbt/NBTCoreImpl.java b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/nbt/NBTCoreImpl.java index fa07f53d..ed25b138 100644 --- a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/nbt/NBTCoreImpl.java +++ b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/nbt/NBTCoreImpl.java @@ -10,7 +10,6 @@ import org.bukkit.entity.Entity; import org.bukkit.inventory.ItemStack; public class NBTCoreImpl implements NBTCore { - @Override public NBTItem of(ItemStack item) { return new NBTItemImpl(CraftItemStack.asNMSCopy(item)); @@ -26,6 +25,7 @@ public class NBTCoreImpl implements NBTCore { net.minecraft.server.v1_13_R2.Entity nmsEntity = ((CraftEntity) entity).getHandle(); NBTTagCompound nbt = new NBTTagCompound(); nmsEntity.save(nbt); + return new NBTEntityImpl(nbt, nmsEntity); } diff --git a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/nbt/NBTEntityImpl.java b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/nbt/NBTEntityImpl.java index d8f4c2e7..58192c92 100644 --- a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/nbt/NBTEntityImpl.java +++ b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/nbt/NBTEntityImpl.java @@ -14,7 +14,6 @@ import org.bukkit.event.entity.CreatureSpawnEvent; import java.util.Optional; public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { - private Entity nmsEntity; public NBTEntityImpl(NBTTagCompound entityNBT, Entity nmsEntity) { @@ -49,6 +48,7 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { return entity; } } + return null; } @@ -61,7 +61,9 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { @Override public void addExtras() { MinecraftKey key = IRegistry.ENTITY_TYPE.getKey(nmsEntity.P()); - if (key != null) + + if (key != null) { compound.setString("entity_type", key.toString()); // Changed in 1.13 + } } } diff --git a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/nbt/NBTItemImpl.java b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/nbt/NBTItemImpl.java index 2904c6b3..5356f086 100644 --- a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/nbt/NBTItemImpl.java @@ -7,7 +7,6 @@ import org.bukkit.craftbukkit.v1_13_R2.inventory.CraftItemStack; import org.bukkit.inventory.ItemStack; public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { - private final net.minecraft.server.v1_13_R2.ItemStack nmsItem; public NBTItemImpl(net.minecraft.server.v1_13_R2.ItemStack nmsItem) { @@ -18,9 +17,9 @@ public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { public ItemStack finish() { if (nmsItem == null) { return CraftItemStack.asBukkitCopy(net.minecraft.server.v1_13_R2.ItemStack.a(compound)); - } else { - return CraftItemStack.asBukkitCopy(nmsItem); } + + return CraftItemStack.asBukkitCopy(nmsItem); } @Override diff --git a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/nbt/NBTObjectImpl.java b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/nbt/NBTObjectImpl.java index b67bfac7..b3f20c8d 100644 --- a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/nbt/NBTObjectImpl.java +++ b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/nbt/NBTObjectImpl.java @@ -7,7 +7,6 @@ import net.minecraft.server.v1_13_R2.NBTTagCompound; import java.util.Set; public class NBTObjectImpl implements NBTObject { - private final NBTTagCompound compound; private final String tag; diff --git a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/world/SItemStackImpl.java b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/world/SItemStackImpl.java index 17e3abc5..6c35a42d 100644 --- a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/world/SItemStackImpl.java +++ b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/world/SItemStackImpl.java @@ -11,7 +11,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public class SItemStackImpl implements SItemStack { - private final ItemStack item; public SItemStackImpl(ItemStack item) { diff --git a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/world/SSpawnerImpl.java b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/world/SSpawnerImpl.java index 830f1402..81696f56 100644 --- a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/world/SSpawnerImpl.java +++ b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/world/SSpawnerImpl.java @@ -23,7 +23,6 @@ import java.util.Random; import java.util.Set; public class SSpawnerImpl implements SSpawner { - private final Location spawnerLocation; public SSpawnerImpl(Location location) { @@ -38,7 +37,6 @@ public class SSpawnerImpl implements SSpawner { @Override public LivingEntity spawnEntity(EntityType type, String particleType, SpawnedEntity spawned, Set canSpawnOn) { - MobSpawnerData data = new MobSpawnerData(); NBTTagCompound compound = data.b(); @@ -60,27 +58,30 @@ public class SSpawnerImpl implements SSpawner { BlockPosition position = entity.getChunkCoordinates(); DifficultyDamageScaler damageScaler = world.getDamageScaler(position); - if (!(entity instanceof EntityInsentient)) + if (!(entity instanceof EntityInsentient)) { continue; + } EntityInsentient entityInsentient = (EntityInsentient) entity; Location spot = new Location(spawnerLocation.getWorld(), x, y, z); - if (!canSpawn(world, entityInsentient, spot, canSpawnOn)) + if (!canSpawn(world, entityInsentient, spot, canSpawnOn)) { continue; + } entityInsentient.prepare(damageScaler, null, null); LivingEntity craftEntity = (LivingEntity) entity.getBukkitEntity(); - if (spawned != null) - if (!spawned.onSpawn(craftEntity)) - return null; + if (spawned != null && !spawned.onSpawn(craftEntity)) { + return null; + } if (particleType != null) { float xx = (float) (0 + (Math.random() * 1)); float yy = (float) (0 + (Math.random() * 2)); float zz = (float) (0 + (Math.random() * 1)); + CompatibleParticleHandler.spawnParticles(CompatibleParticleHandler.ParticleType.getParticle(particleType), spot, 5, xx, yy, zz, 0); } @@ -92,34 +93,38 @@ public class SSpawnerImpl implements SSpawner { return craftEntity; } + return null; } private boolean canSpawn(WorldServer world, EntityInsentient entityInsentient, Location location, Set canSpawnOn) { - - if (!world.getCubes(entityInsentient, entityInsentient.getBoundingBox())) + if (!world.getCubes(entityInsentient, entityInsentient.getBoundingBox())) { return false; + } CompatibleMaterial spawnedIn = CompatibleMaterial.getMaterial(location.getBlock()); CompatibleMaterial spawnedOn = CompatibleMaterial.getMaterial(location.getBlock().getRelative(BlockFace.DOWN)); - if (spawnedIn == null || spawnedOn == null) + if (spawnedIn == null || spawnedOn == null) { return false; + } - if (!spawnedIn.isAir() - && spawnedIn != CompatibleMaterial.WATER - && !spawnedIn.name().contains("PRESSURE") - && !spawnedIn.name().contains("SLAB")) { + if (!spawnedIn.isAir() && + spawnedIn != CompatibleMaterial.WATER && + !spawnedIn.name().contains("PRESSURE") && + !spawnedIn.name().contains("SLAB")) { return false; } for (CompatibleMaterial material : canSpawnOn) { if (material == null) continue; - if (spawnedOn.equals(material) || material.isAir()) + if (spawnedOn.equals(material) || material.isAir()) { return true; + } } + return false; } } diff --git a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/world/SWorldImpl.java b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/world/SWorldImpl.java index 7ee970f1..845b135a 100644 --- a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/world/SWorldImpl.java +++ b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/world/SWorldImpl.java @@ -7,7 +7,6 @@ import java.util.ArrayList; import java.util.List; public class SWorldImpl implements SWorld { - public SWorldImpl() { } diff --git a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/world/WorldCoreImpl.java b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/world/WorldCoreImpl.java index 3b39c887..28b29315 100644 --- a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/world/WorldCoreImpl.java +++ b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/world/WorldCoreImpl.java @@ -56,42 +56,44 @@ public class WorldCoreImpl implements WorldCore { public void randomTickChunk(org.bukkit.Chunk bukkitChunk, int tickAmount) throws NoSuchFieldException, IllegalAccessException { Chunk chunk = ((CraftChunk) bukkitChunk).getHandle(); - if (tickAmount > 0) { - int j = chunk.locX * 16; - int k = chunk.locZ * 16; + if (tickAmount <= 0) { + return; + } - chunk.world.methodProfiler.enter("tickBlocks"); - for (ChunkSection chunksection : chunk.getSections()) { - if (chunksection != net.minecraft.server.v1_13_R2.Chunk.a && chunksection.b()) { - for (int k1 = 0; k1 < tickAmount; ++k1) { - int worldM = (int) ReflectionUtils.getFieldValue(chunk.world, "m"); - worldM = worldM * 3 + 1013904223; - ReflectionUtils.setFieldValue(chunk.world, "m", worldM); + int j = chunk.locX * 16; + int k = chunk.locZ * 16; - int l1 = worldM >> 2; - int i2 = l1 & 15; - int j2 = l1 >> 8 & 15; - int k2 = l1 >> 16 & 15; + chunk.world.methodProfiler.enter("tickBlocks"); + for (ChunkSection chunksection : chunk.getSections()) { + if (chunksection != net.minecraft.server.v1_13_R2.Chunk.a && chunksection.b()) { + for (int k1 = 0; k1 < tickAmount; ++k1) { + int worldM = (int) ReflectionUtils.getFieldValue(chunk.world, "m"); + worldM = worldM * 3 + 1013904223; + ReflectionUtils.setFieldValue(chunk.world, "m", worldM); - IBlockData iblockdata = chunksection.getType(i2, k2, j2); - Fluid fluid = chunksection.b(i2, k2, j2); + int l1 = worldM >> 2; + int i2 = l1 & 15; + int j2 = l1 >> 8 & 15; + int k2 = l1 >> 16 & 15; - chunk.world.methodProfiler.enter("randomTick"); + IBlockData iblockdata = chunksection.getType(i2, k2, j2); + Fluid fluid = chunksection.b(i2, k2, j2); - if (iblockdata.t()) { - iblockdata.b(chunk.world, new BlockPosition(i2 + j, k2 + chunksection.getYPosition(), j2 + k), chunk.world.random); - } + chunk.world.methodProfiler.enter("randomTick"); - if (fluid.h()) { - fluid.b(chunk.world, new BlockPosition(i2 + j, k2 + chunksection.getYPosition(), j2 + k), chunk.world.random); - } - - chunk.world.methodProfiler.exit(); + if (iblockdata.t()) { + iblockdata.b(chunk.world, new BlockPosition(i2 + j, k2 + chunksection.getYPosition(), j2 + k), chunk.world.random); } + + if (fluid.h()) { + fluid.b(chunk.world, new BlockPosition(i2 + j, k2 + chunksection.getYPosition(), j2 + k), chunk.world.random); + } + + chunk.world.methodProfiler.exit(); } } - - chunk.world.methodProfiler.exit(); } + + chunk.world.methodProfiler.exit(); } } diff --git a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/world/spawner/BBaseSpawnerImpl.java b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/world/spawner/BBaseSpawnerImpl.java index af7a68cd..2c09ea57 100644 --- a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/world/spawner/BBaseSpawnerImpl.java +++ b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/world/spawner/BBaseSpawnerImpl.java @@ -73,92 +73,93 @@ public class BBaseSpawnerImpl implements BBaseSpawner { ReflectionUtils.setFieldValue(spawner, "f", spawnerE); ReflectionUtils.setFieldValue(spawner, "e", (spawnerE + (double) (1000F / ((float) spawner.spawnDelay + 200F))) % 360D); - } else { - if (spawner.spawnDelay == -1) { - delay(spawner); + return; + } + + if (spawner.spawnDelay == -1) { + delay(spawner); + } + + if (spawner.spawnDelay > 0) { + --spawner.spawnDelay; + return; + } + + boolean flag = false; + int i = 0; + + MobSpawnerData spawnData = (MobSpawnerData) ReflectionUtils.getFieldValue(spawner, "spawnData"); + + while (true) { + if (i >= spawner.spawnCount) { + if (flag) { + delay(spawner); + } + + break; } - if (spawner.spawnDelay > 0) { - --spawner.spawnDelay; + NBTTagCompound nbttagcompound = spawnData.b(); + NBTTagList nbttaglist = nbttagcompound.getList("Pos", 6); + net.minecraft.server.v1_13_R2.World world = spawner.a(); + int j = nbttaglist.size(); + double d3 = j >= 1 ? nbttaglist.k(0) : (double) blockposition.getX() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; + double d4 = j >= 2 ? nbttaglist.k(1) : (double) (blockposition.getY() + world.random.nextInt(3) - 1); + double d5 = j >= 3 ? nbttaglist.k(2) : (double) blockposition.getZ() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; + Entity entity = ChunkRegionLoader.a(nbttagcompound, world, d3, d4, d5, false); + if (entity == null) { + delay(spawner); return; } - boolean flag = false; - int i = 0; + int k = world.a(entity.getClass(), (new AxisAlignedBB( + blockposition.getX(), + blockposition.getY(), + blockposition.getZ(), + blockposition.getX() + 1, + blockposition.getY() + 1, + blockposition.getZ() + 1)) + .g(spawner.spawnRange)).size(); - MobSpawnerData spawnData = (MobSpawnerData) ReflectionUtils.getFieldValue(spawner, "spawnData"); - - while (true) { - if (i >= spawner.spawnCount) { - if (flag) { - delay(spawner); - } - - break; - } - - NBTTagCompound nbttagcompound = spawnData.b(); - NBTTagList nbttaglist = nbttagcompound.getList("Pos", 6); - net.minecraft.server.v1_13_R2.World world = spawner.a(); - int j = nbttaglist.size(); - double d3 = j >= 1 ? nbttaglist.k(0) : (double) blockposition.getX() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; - double d4 = j >= 2 ? nbttaglist.k(1) : (double) (blockposition.getY() + world.random.nextInt(3) - 1); - double d5 = j >= 3 ? nbttaglist.k(2) : (double) blockposition.getZ() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; - Entity entity = ChunkRegionLoader.a(nbttagcompound, world, d3, d4, d5, false); - if (entity == null) { - delay(spawner); - return; - } - - int k = world.a(entity.getClass(), (new AxisAlignedBB( - blockposition.getX(), - blockposition.getY(), - blockposition.getZ(), - blockposition.getX() + 1, - blockposition.getY() + 1, - blockposition.getZ() + 1)) - .g(spawner.spawnRange)).size(); - - if (k >= spawner.maxNearbyEntities) { - delay(spawner); - return; - } - - EntityInsentient entityinsentient = entity instanceof EntityInsentient ? (EntityInsentient) entity : null; - entity.setPositionRotation(entity.locX, entity.locY, entity.locZ, world.random.nextFloat() * 360.0F, 0.0F); - if (entityinsentient == null || entityinsentient.a(world, true) && entityinsentient.canSpawn()) { - if (spawnData.b().d() == 1 && spawnData.b().hasKeyOfType("id", 8) && entity instanceof EntityInsentient) { - ((EntityInsentient) entity).prepare(world.getDamageScaler(new BlockPosition(entity)), null, null); - } - - if (entity.world.spigotConfig.nerfSpawnerMobs) { - entity.fromMobSpawner = true; - } - - if (CraftEventFactory.callSpawnerSpawnEvent(entity, blockposition).isCancelled()) { - Entity vehicle = entity.getVehicle(); - if (vehicle != null) { - vehicle.dead = true; - } - - Entity passenger; - for (Iterator var19 = entity.getAllPassengers().iterator(); var19.hasNext(); passenger.dead = true) { - passenger = var19.next(); - } - } else { - ChunkRegionLoader.a(entity, world, CreatureSpawnEvent.SpawnReason.SPAWNER); - world.triggerEffect(2004, blockposition, 0); - - if (entityinsentient != null) { - entityinsentient.doSpawnEffect(); - } - - flag = true; - } - } - - ++i; + if (k >= spawner.maxNearbyEntities) { + delay(spawner); + return; } + + EntityInsentient entityinsentient = entity instanceof EntityInsentient ? (EntityInsentient) entity : null; + entity.setPositionRotation(entity.locX, entity.locY, entity.locZ, world.random.nextFloat() * 360.0F, 0.0F); + if (entityinsentient == null || entityinsentient.a(world, true) && entityinsentient.canSpawn()) { + if (spawnData.b().d() == 1 && spawnData.b().hasKeyOfType("id", 8) && entity instanceof EntityInsentient) { + ((EntityInsentient) entity).prepare(world.getDamageScaler(new BlockPosition(entity)), null, null); + } + + if (entity.world.spigotConfig.nerfSpawnerMobs) { + entity.fromMobSpawner = true; + } + + if (CraftEventFactory.callSpawnerSpawnEvent(entity, blockposition).isCancelled()) { + Entity vehicle = entity.getVehicle(); + if (vehicle != null) { + vehicle.dead = true; + } + + Entity passenger; + for (Iterator var19 = entity.getAllPassengers().iterator(); var19.hasNext(); passenger.dead = true) { + passenger = var19.next(); + } + } else { + ChunkRegionLoader.a(entity, world, CreatureSpawnEvent.SpawnReason.SPAWNER); + world.triggerEffect(2004, blockposition, 0); + + if (entityinsentient != null) { + entityinsentient.doSpawnEffect(); + } + + flag = true; + } + } + + ++i; } } diff --git a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/anvil/AnvilCore.java b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/anvil/AnvilCore.java index af14d1e7..c9c22d24 100644 --- a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/anvil/AnvilCore.java +++ b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/anvil/AnvilCore.java @@ -7,7 +7,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; public class AnvilCore implements com.songoda.core.nms.anvil.AnvilCore { - @Override public CustomAnvil createAnvil(Player player) { EntityPlayer p = ((CraftPlayer) player).getHandle(); diff --git a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/anvil/AnvilInventoryCustom.java b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/anvil/AnvilInventoryCustom.java index 4a36625a..45e41569 100644 --- a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/anvil/AnvilInventoryCustom.java +++ b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/anvil/AnvilInventoryCustom.java @@ -7,11 +7,11 @@ import org.bukkit.craftbukkit.v1_14_R1.inventory.CraftInventoryAnvil; import org.bukkit.inventory.InventoryHolder; public class AnvilInventoryCustom extends CraftInventoryAnvil { - final InventoryHolder holder; public AnvilInventoryCustom(InventoryHolder holder, Location location, IInventory inventory, IInventory resultInventory, ContainerAnvil container) { super(location, inventory, resultInventory, container); + this.holder = holder; } diff --git a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/anvil/AnvilView.java b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/anvil/AnvilView.java index 573ee281..919c668b 100644 --- a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/anvil/AnvilView.java +++ b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/anvil/AnvilView.java @@ -25,7 +25,6 @@ import java.util.logging.Level; import java.util.logging.Logger; public class AnvilView extends ContainerAnvil implements CustomAnvil { - private final EntityPlayer entity; private final Inventory inventory; private String customTitle = "Repairing"; @@ -42,8 +41,10 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { try { mc_ContainerAnvil_repairInventory = ContainerAnvil.class.getDeclaredField("repairInventory"); mc_ContainerAnvil_repairInventory.setAccessible(true); + mc_ContainerAnvil_resultInventory = ContainerAnvil.class.getDeclaredField("resultInventory"); mc_ContainerAnvil_resultInventory.setAccessible(true); + mc_ContainerAnvil_bukkitEntity = ContainerAnvil.class.getDeclaredField("bukkitEntity"); mc_ContainerAnvil_bukkitEntity.setAccessible(true); } catch (Exception ex) { @@ -69,12 +70,14 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { } catch (Exception ex) { Logger.getLogger(AnvilView.class.getName()).log(Level.SEVERE, "Anvil Setup Error", ex); } + for (Method m : ContainerProperty.class.getMethods()) { if (m.getName().equals("set")) { compat_mode = false; break; } } + if (compat_mode) { try { mc_ContainerProperty_set = ContainerProperty.class.getDeclaredMethod("a", int.class); @@ -87,9 +90,11 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { public AnvilView(int id, EntityPlayer entity, InventoryHolder holder) { super(id, entity.inventory, ContainerAccess.at(entity.world, new BlockPosition(0, 0, 0))); + this.setTitle(new ChatMessage(customTitle != null ? customTitle : "")); this.checkReachable = false; this.entity = entity; + if (holder != null) { this.inventory = getBukkitView(entity, holder).getTopInventory(); } else { @@ -105,10 +110,12 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { (IInventory) mc_ContainerAnvil_resultInventory.get(this), this); CraftInventoryView view = new CraftInventoryView(player.getBukkitEntity(), craftInventory, this); mc_ContainerAnvil_bukkitEntity.set(this, view); + return view; } catch (Exception ex) { Logger.getLogger(AnvilView.class.getName()).log(Level.SEVERE, "Anvil Setup Error", ex); } + return getBukkitView(); } @@ -120,6 +127,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void e() { super.e(); + if (cost >= 0) { if (compat_mode) { if (mc_ContainerProperty_set != null) { @@ -134,6 +142,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { this.levelCost.set(cost); } } + textChange.onChange(); } @@ -165,6 +174,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void setCustomTitle(String title) { this.customTitle = title; + try { mc_Container_title.set(this, new ChatMessage(customTitle != null ? customTitle : "")); } catch (Exception ex) { @@ -181,7 +191,9 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { public int getLevelCost() { if (cost >= 0) { return cost; - } else if (compat_mode) { + } + + if (compat_mode) { if (mc_ContainerProperty_get != null) { try { return (int) mc_ContainerProperty_get.invoke(this.levelCost); @@ -193,6 +205,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { } else { return this.levelCost.get(); } + return -1; } @@ -238,7 +251,6 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void open() { - // Counter stuff that the game uses to keep track of inventories int id = entity.nextContainerCounter(); diff --git a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTCompoundImpl.java b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTCompoundImpl.java index 66731c1d..3ef2c3f7 100644 --- a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTCompoundImpl.java +++ b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTCompoundImpl.java @@ -15,7 +15,6 @@ import java.util.Set; import java.util.UUID; public class NBTCompoundImpl implements NBTCompound { - protected NBTTagCompound compound; protected NBTCompoundImpl(NBTTagCompound compound) { @@ -151,11 +150,11 @@ public class NBTCompoundImpl implements NBTCompound { public NBTCompound getCompound(String tag) { if (has(tag)) { return getNBTObject(tag).asCompound(); - } else { - NBTTagCompound newCompound = new NBTTagCompound(); - compound.set(tag, newCompound); - return new NBTCompoundImpl(newCompound); } + + NBTTagCompound newCompound = new NBTTagCompound(); + compound.set(tag, newCompound); + return new NBTCompoundImpl(newCompound); } @Override @@ -175,15 +174,17 @@ public class NBTCompoundImpl implements NBTCompound { addExtras(); NBTTagCompound compound = this.compound.clone(); - for (String exclusion : exclusions) + for (String exclusion : exclusions) { compound.remove(exclusion); + } NBTCompressedStreamTools.a(compound, (OutputStream) dataOutput); return outputStream.toByteArray(); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } + return null; } @@ -192,8 +193,8 @@ public class NBTCompoundImpl implements NBTCompound { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(serialized); ObjectInputStream dataInput = new ObjectInputStream(inputStream)) { compound = NBTCompressedStreamTools.a((InputStream) dataInput); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } } diff --git a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTCoreImpl.java b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTCoreImpl.java index 4d93334b..955daaf8 100644 --- a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTCoreImpl.java +++ b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTCoreImpl.java @@ -10,7 +10,6 @@ import org.bukkit.entity.Entity; import org.bukkit.inventory.ItemStack; public class NBTCoreImpl implements NBTCore { - @Override public NBTItem of(ItemStack item) { return new NBTItemImpl(CraftItemStack.asNMSCopy(item)); @@ -26,6 +25,7 @@ public class NBTCoreImpl implements NBTCore { net.minecraft.server.v1_14_R1.Entity nmsEntity = ((CraftEntity) entity).getHandle(); NBTTagCompound nbt = new NBTTagCompound(); nmsEntity.save(nbt); + return new NBTEntityImpl(nbt, nmsEntity); } diff --git a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTEntityImpl.java b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTEntityImpl.java index 3beb9846..821140c6 100644 --- a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTEntityImpl.java +++ b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTEntityImpl.java @@ -13,11 +13,11 @@ import org.bukkit.craftbukkit.v1_14_R1.CraftWorld; import java.util.Optional; public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { - private Entity nmsEntity; public NBTEntityImpl(NBTTagCompound entityNBT, Entity nmsEntity) { super(entityNBT); + this.nmsEntity = nmsEntity; } @@ -44,9 +44,11 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { spawned.setLocation(location.getX(), location.getY(), location.getZ(), location.getPitch(), location.getYaw()); nmsEntity = spawned; + return entity; } } + return null; } diff --git a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTItemImpl.java b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTItemImpl.java index 8d9827bc..c62059a7 100644 --- a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTItemImpl.java @@ -7,20 +7,20 @@ import org.bukkit.craftbukkit.v1_14_R1.inventory.CraftItemStack; import org.bukkit.inventory.ItemStack; public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { - private final net.minecraft.server.v1_14_R1.ItemStack nmsItem; public NBTItemImpl(net.minecraft.server.v1_14_R1.ItemStack nmsItem) { super(nmsItem != null && nmsItem.hasTag() ? nmsItem.getTag() : new NBTTagCompound()); + this.nmsItem = nmsItem; } public ItemStack finish() { if (nmsItem == null) { return CraftItemStack.asBukkitCopy(net.minecraft.server.v1_14_R1.ItemStack.a(compound)); - } else { - return CraftItemStack.asBukkitCopy(nmsItem); } + + return CraftItemStack.asBukkitCopy(nmsItem); } @Override diff --git a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTObjectImpl.java b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTObjectImpl.java index 211f571a..54693b8c 100644 --- a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTObjectImpl.java +++ b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTObjectImpl.java @@ -7,7 +7,6 @@ import net.minecraft.server.v1_14_R1.NBTTagCompound; import java.util.Set; public class NBTObjectImpl implements NBTObject { - private final NBTTagCompound compound; private final String tag; diff --git a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/world/SItemStackImpl.java b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/world/SItemStackImpl.java index 22986684..e7985856 100644 --- a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/world/SItemStackImpl.java +++ b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/world/SItemStackImpl.java @@ -11,7 +11,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public class SItemStackImpl implements SItemStack { - private final ItemStack item; public SItemStackImpl(ItemStack item) { @@ -21,15 +20,19 @@ public class SItemStackImpl implements SItemStack { @Override public void breakItem(Player player, int amount) { EntityPlayer entityPlayer = ((CraftPlayer) player).getHandle(); + for (int i = 0; i < amount; ++i) { Vec3D vec3d = new Vec3D(((double) this.random.nextFloat() - 0.5D) * 0.1D, Math.random() * 0.1D + 0.1D, 0.0D); vec3d = vec3d.a(-entityPlayer.pitch * 0.017453292F); vec3d = vec3d.b(-entityPlayer.yaw * 0.017453292F); + double d0 = (double) (-this.random.nextFloat()) * 0.6D - 0.3D; + Vec3D vec3d1 = new Vec3D(((double) this.random.nextFloat() - 0.5D) * 0.3D, d0, 0.6D); vec3d1 = vec3d1.a(-entityPlayer.pitch * 0.017453292F); vec3d1 = vec3d1.b(-entityPlayer.yaw * 0.017453292F); vec3d1 = vec3d1.add(entityPlayer.locX, entityPlayer.locY + (double) entityPlayer.getHeadHeight(), entityPlayer.locZ); + entityPlayer.world.addParticle(new ParticleParamItem(Particles.ITEM, CraftItemStack.asNMSCopy(item)), vec3d1.x, vec3d1.y, vec3d1.z, vec3d.x, vec3d.y + 0.05D, vec3d.z); } } diff --git a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/world/SSpawnerImpl.java b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/world/SSpawnerImpl.java index e855dfac..620a715f 100644 --- a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/world/SSpawnerImpl.java +++ b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/world/SSpawnerImpl.java @@ -25,7 +25,6 @@ import java.util.Random; import java.util.Set; public class SSpawnerImpl implements SSpawner { - private final Location spawnerLocation; public SSpawnerImpl(Location location) { @@ -40,7 +39,6 @@ public class SSpawnerImpl implements SSpawner { @Override public LivingEntity spawnEntity(EntityType type, String particleType, SpawnedEntity spawned, Set canSpawnOn) { - MobSpawnerData data = new MobSpawnerData(); NBTTagCompound compound = data.getEntity(); @@ -66,28 +64,30 @@ public class SSpawnerImpl implements SSpawner { BlockPosition position = entity.getChunkCoordinates(); DifficultyDamageScaler damageScaler = world.getDamageScaler(position); - if (!(entity instanceof EntityInsentient)) + if (!(entity instanceof EntityInsentient)) { continue; + } EntityInsentient entityInsentient = (EntityInsentient) entity; Location spot = new Location(spawnerLocation.getWorld(), x, y, z); - if (!canSpawn(world, entityInsentient, spot, canSpawnOn)) + if (!canSpawn(world, entityInsentient, spot, canSpawnOn)) { continue; + } - entityInsentient.prepare(world, damageScaler, EnumMobSpawn.SPAWNER, - null, null); + entityInsentient.prepare(world, damageScaler, EnumMobSpawn.SPAWNER, null, null); LivingEntity craftEntity = (LivingEntity) entity.getBukkitEntity(); - if (spawned != null) - if (!spawned.onSpawn(craftEntity)) - return null; + if (spawned != null && !spawned.onSpawn(craftEntity)) { + return null; + } if (particleType != null) { float xx = (float) (0 + (Math.random() * 1)); float yy = (float) (0 + (Math.random() * 2)); float zz = (float) (0 + (Math.random() * 1)); + CompatibleParticleHandler.spawnParticles(CompatibleParticleHandler.ParticleType.getParticle(particleType), spot, 5, xx, yy, zz, 0); } @@ -99,34 +99,38 @@ public class SSpawnerImpl implements SSpawner { return craftEntity; } + return null; } private boolean canSpawn(WorldServer world, EntityInsentient entityInsentient, Location location, Set canSpawnOn) { - - if (!world.getCubes(entityInsentient, entityInsentient.getBoundingBox())) + if (!world.getCubes(entityInsentient, entityInsentient.getBoundingBox())) { return false; + } CompatibleMaterial spawnedIn = CompatibleMaterial.getMaterial(location.getBlock()); CompatibleMaterial spawnedOn = CompatibleMaterial.getMaterial(location.getBlock().getRelative(BlockFace.DOWN)); - if (spawnedIn == null || spawnedOn == null) + if (spawnedIn == null || spawnedOn == null) { return false; + } - if (!spawnedIn.isAir() - && spawnedIn != CompatibleMaterial.WATER - && !spawnedIn.name().contains("PRESSURE") - && !spawnedIn.name().contains("SLAB")) { + if (!spawnedIn.isAir() && + spawnedIn != CompatibleMaterial.WATER && + !spawnedIn.name().contains("PRESSURE") && + !spawnedIn.name().contains("SLAB")) { return false; } for (CompatibleMaterial material : canSpawnOn) { if (material == null) continue; - if (spawnedOn.equals(material) || material.isAir()) + if (spawnedOn.equals(material) || material.isAir()) { return true; + } } + return false; } } diff --git a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/world/SWorldImpl.java b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/world/SWorldImpl.java index 9bea95d5..ac14e66a 100644 --- a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/world/SWorldImpl.java +++ b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/world/SWorldImpl.java @@ -7,7 +7,6 @@ import java.util.ArrayList; import java.util.List; public class SWorldImpl implements SWorld { - public SWorldImpl() { } diff --git a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/world/WorldCoreImpl.java b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/world/WorldCoreImpl.java index ffae55d7..3dbffc9f 100644 --- a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/world/WorldCoreImpl.java +++ b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/world/WorldCoreImpl.java @@ -57,38 +57,40 @@ public class WorldCoreImpl implements WorldCore { public void randomTickChunk(org.bukkit.Chunk bukkitChunk, int tickAmount) { Chunk chunk = ((CraftChunk) bukkitChunk).getHandle(); - if (tickAmount > 0) { - ChunkCoordIntPair chunkcoordintpair = chunk.getPos(); - int j = chunkcoordintpair.d(); - int k = chunkcoordintpair.e(); + if (tickAmount <= 0) { + return; + } - GameProfilerFiller profiler = chunk.world.getMethodProfiler(); + ChunkCoordIntPair chunkcoordintpair = chunk.getPos(); + int j = chunkcoordintpair.d(); + int k = chunkcoordintpair.e(); - profiler.enter("tickBlocks"); - for (ChunkSection chunksection : chunk.getSections()) { - if (chunksection != net.minecraft.server.v1_14_R1.Chunk.a && chunksection.d()) { - int j1 = chunksection.getYPosition(); + GameProfilerFiller profiler = chunk.world.getMethodProfiler(); - for (int i = 0; i < tickAmount; ++i) { - BlockPosition blockposition2 = chunk.world.a(j, j1, k, 15); - profiler.enter("randomTick"); - IBlockData iblockdata = chunksection.getType(blockposition2.getX() - j, blockposition2.getY() - j1, blockposition2.getZ() - k); + profiler.enter("tickBlocks"); + for (ChunkSection chunksection : chunk.getSections()) { + if (chunksection != net.minecraft.server.v1_14_R1.Chunk.a && chunksection.d()) { + int j1 = chunksection.getYPosition(); - if (iblockdata.q()) { - iblockdata.b(chunk.world, blockposition2, chunk.world.random); - } + for (int i = 0; i < tickAmount; ++i) { + BlockPosition blockposition2 = chunk.world.a(j, j1, k, 15); + profiler.enter("randomTick"); + IBlockData iblockdata = chunksection.getType(blockposition2.getX() - j, blockposition2.getY() - j1, blockposition2.getZ() - k); - Fluid fluid = iblockdata.p(); - if (fluid.h()) { - fluid.b(chunk.world, blockposition2, chunk.world.random); - } - - profiler.exit(); + if (iblockdata.q()) { + iblockdata.b(chunk.world, blockposition2, chunk.world.random); } + + Fluid fluid = iblockdata.p(); + if (fluid.h()) { + fluid.b(chunk.world, blockposition2, chunk.world.random); + } + + profiler.exit(); } } - - profiler.exit(); } + + profiler.exit(); } } diff --git a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/world/spawner/BBaseSpawnerImpl.java b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/world/spawner/BBaseSpawnerImpl.java index a09bf563..4008a5a0 100644 --- a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/world/spawner/BBaseSpawnerImpl.java +++ b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/world/spawner/BBaseSpawnerImpl.java @@ -65,107 +65,108 @@ public class BBaseSpawnerImpl implements BBaseSpawner { double spawnerE = (double) ReflectionUtils.getFieldValue(spawner, "e"); ReflectionUtils.setFieldValue(spawner, "f", spawnerE); ReflectionUtils.setFieldValue(spawner, "e", (spawnerE + (double) (1000F / ((float) spawner.spawnDelay + 200F))) % 360D); - } else { - if (spawner.spawnDelay == -1) { - delay(spawner); + return; + } + + if (spawner.spawnDelay == -1) { + delay(spawner); + } + + if (spawner.spawnDelay > 0) { + --spawner.spawnDelay; + return; + } + + boolean flag = false; + int i = 0; + + while (true) { + if (i >= spawner.spawnCount) { + if (flag) { + delay(spawner); + } + + break; } - if (spawner.spawnDelay > 0) { - --spawner.spawnDelay; + NBTTagCompound nbttagcompound = spawner.spawnData.getEntity(); + Optional> optional = EntityTypes.a(nbttagcompound); + if (!optional.isPresent()) { + delay(spawner); return; } - boolean flag = false; - int i = 0; - - while (true) { - if (i >= spawner.spawnCount) { - if (flag) { + NBTTagList nbttaglist = nbttagcompound.getList("Pos", 6); + int j = nbttaglist.size(); + double d3 = j >= 1 ? nbttaglist.h(0) : (double) blockposition.getX() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; + double d4 = j >= 2 ? nbttaglist.h(1) : (double) (blockposition.getY() + world.random.nextInt(3) - 1); + double d5 = j >= 3 ? nbttaglist.h(2) : (double) blockposition.getZ() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; + if (world.c(optional.get().a(d3, d4, d5)) && EntityPositionTypes.a(optional.get(), world.getMinecraftWorld(), EnumMobSpawn.SPAWNER, new BlockPosition(d3, d4, d5), world.getRandom())) { + label112: + { + Entity entity = EntityTypes.a(nbttagcompound, world, (entity1) -> { + entity1.setPositionRotation(d3, d4, d5, entity1.yaw, entity1.pitch); + return entity1; + }); + if (entity == null) { delay(spawner); + return; } - break; - } + int k = world.a(entity.getClass(), (new AxisAlignedBB( + blockposition.getX(), + blockposition.getY(), + blockposition.getZ(), + blockposition.getX() + 1, + blockposition.getY() + 1, + blockposition.getZ() + 1)) + .g(spawner.spawnRange)).size(); - NBTTagCompound nbttagcompound = spawner.spawnData.getEntity(); - Optional> optional = EntityTypes.a(nbttagcompound); - if (!optional.isPresent()) { - delay(spawner); - return; - } + if (k >= spawner.maxNearbyEntities) { + delay(spawner); + return; + } - NBTTagList nbttaglist = nbttagcompound.getList("Pos", 6); - int j = nbttaglist.size(); - double d3 = j >= 1 ? nbttaglist.h(0) : (double) blockposition.getX() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; - double d4 = j >= 2 ? nbttaglist.h(1) : (double) (blockposition.getY() + world.random.nextInt(3) - 1); - double d5 = j >= 3 ? nbttaglist.h(2) : (double) blockposition.getZ() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; - if (world.c(optional.get().a(d3, d4, d5)) && EntityPositionTypes.a(optional.get(), world.getMinecraftWorld(), EnumMobSpawn.SPAWNER, new BlockPosition(d3, d4, d5), world.getRandom())) { - label112: - { - Entity entity = EntityTypes.a(nbttagcompound, world, (entity1) -> { - entity1.setPositionRotation(d3, d4, d5, entity1.yaw, entity1.pitch); - return entity1; - }); - if (entity == null) { - delay(spawner); - return; + entity.setPositionRotation(entity.locX, entity.locY, entity.locZ, world.random.nextFloat() * 360F, 0F); + if (entity instanceof EntityInsentient) { + EntityInsentient entityinsentient = (EntityInsentient) entity; + if (!entityinsentient.a(world, EnumMobSpawn.SPAWNER) || !entityinsentient.a(world)) { + break label112; } - int k = world.a(entity.getClass(), (new AxisAlignedBB( - blockposition.getX(), - blockposition.getY(), - blockposition.getZ(), - blockposition.getX() + 1, - blockposition.getY() + 1, - blockposition.getZ() + 1)) - .g(spawner.spawnRange)).size(); + if (spawner.spawnData.getEntity().d() == 1 && spawner.spawnData.getEntity().hasKeyOfType("id", 8)) { + ((EntityInsentient) entity).prepare(world, world.getDamageScaler(new BlockPosition(entity)), EnumMobSpawn.SPAWNER, null, null); + } + } - if (k >= spawner.maxNearbyEntities) { - delay(spawner); - return; + if (entity.world.spigotConfig.nerfSpawnerMobs) { + entity.fromMobSpawner = true; + } + + if (CraftEventFactory.callSpawnerSpawnEvent(entity, blockposition).isCancelled()) { + Entity vehicle = entity.getVehicle(); + if (vehicle != null) { + vehicle.dead = true; } - entity.setPositionRotation(entity.locX, entity.locY, entity.locZ, world.random.nextFloat() * 360F, 0F); + Entity passenger; + for (Iterator var19 = entity.getAllPassengers().iterator(); var19.hasNext(); passenger.dead = true) { + passenger = var19.next(); + } + } else { + addWithPassengers(spawner, entity); + world.triggerEffect(2004, blockposition, 0); + if (entity instanceof EntityInsentient) { - EntityInsentient entityinsentient = (EntityInsentient) entity; - if (!entityinsentient.a(world, EnumMobSpawn.SPAWNER) || !entityinsentient.a(world)) { - break label112; - } - - if (spawner.spawnData.getEntity().d() == 1 && spawner.spawnData.getEntity().hasKeyOfType("id", 8)) { - ((EntityInsentient) entity).prepare(world, world.getDamageScaler(new BlockPosition(entity)), EnumMobSpawn.SPAWNER, null, null); - } + ((EntityInsentient) entity).doSpawnEffect(); } - if (entity.world.spigotConfig.nerfSpawnerMobs) { - entity.fromMobSpawner = true; - } - - if (CraftEventFactory.callSpawnerSpawnEvent(entity, blockposition).isCancelled()) { - Entity vehicle = entity.getVehicle(); - if (vehicle != null) { - vehicle.dead = true; - } - - Entity passenger; - for (Iterator var19 = entity.getAllPassengers().iterator(); var19.hasNext(); passenger.dead = true) { - passenger = var19.next(); - } - } else { - addWithPassengers(spawner, entity); - world.triggerEffect(2004, blockposition, 0); - - if (entity instanceof EntityInsentient) { - ((EntityInsentient) entity).doSpawnEffect(); - } - - flag = true; - } + flag = true; } } - - ++i; } + + ++i; } } @@ -199,4 +200,4 @@ public class BBaseSpawnerImpl implements BBaseSpawner { } } } -} \ No newline at end of file +} diff --git a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/anvil/AnvilCore.java b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/anvil/AnvilCore.java index 8ec5ce1f..75e1da40 100644 --- a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/anvil/AnvilCore.java +++ b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/anvil/AnvilCore.java @@ -7,16 +7,17 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; public class AnvilCore implements com.songoda.core.nms.anvil.AnvilCore { - @Override public CustomAnvil createAnvil(Player player) { EntityPlayer p = ((CraftPlayer) player).getHandle(); + return new AnvilView(p.nextContainerCounter(), p, null); } @Override public CustomAnvil createAnvil(Player player, InventoryHolder holder) { EntityPlayer p = ((CraftPlayer) player).getHandle(); + return new AnvilView(p.nextContainerCounter(), p, holder); } } diff --git a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/anvil/AnvilInventoryCustom.java b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/anvil/AnvilInventoryCustom.java index 199fa4c2..91d686f0 100644 --- a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/anvil/AnvilInventoryCustom.java +++ b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/anvil/AnvilInventoryCustom.java @@ -7,11 +7,11 @@ import org.bukkit.craftbukkit.v1_15_R1.inventory.CraftInventoryAnvil; import org.bukkit.inventory.InventoryHolder; public class AnvilInventoryCustom extends CraftInventoryAnvil { - final InventoryHolder holder; public AnvilInventoryCustom(InventoryHolder holder, Location location, IInventory inventory, IInventory resultInventory, ContainerAnvil container) { super(location, inventory, resultInventory, container); + this.holder = holder; } diff --git a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/anvil/AnvilView.java b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/anvil/AnvilView.java index 0977eefd..afbf23c4 100644 --- a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/anvil/AnvilView.java +++ b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/anvil/AnvilView.java @@ -25,7 +25,6 @@ import java.util.logging.Level; import java.util.logging.Logger; public class AnvilView extends ContainerAnvil implements CustomAnvil { - private final EntityPlayer entity; private final Inventory inventory; private String customTitle = "Repairing"; @@ -42,8 +41,10 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { try { mc_ContainerAnvil_repairInventory = ContainerAnvil.class.getDeclaredField("repairInventory"); mc_ContainerAnvil_repairInventory.setAccessible(true); + mc_ContainerAnvil_resultInventory = ContainerAnvil.class.getDeclaredField("resultInventory"); mc_ContainerAnvil_resultInventory.setAccessible(true); + mc_ContainerAnvil_bukkitEntity = ContainerAnvil.class.getDeclaredField("bukkitEntity"); mc_ContainerAnvil_bukkitEntity.setAccessible(true); } catch (Exception ex) { @@ -76,9 +77,11 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { public AnvilView(int id, EntityPlayer entity, InventoryHolder holder) { super(id, entity.inventory, ContainerAccess.at(entity.world, new BlockPosition(0, 0, 0))); + this.setTitle(new ChatMessage(customTitle != null ? customTitle : "")); this.checkReachable = false; this.entity = entity; + if (holder != null) { this.inventory = getBukkitView(entity, holder).getTopInventory(); } else { @@ -94,10 +97,12 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { (IInventory) mc_ContainerAnvil_resultInventory.get(this), this); CraftInventoryView view = new CraftInventoryView(player.getBukkitEntity(), craftInventory, this); mc_ContainerAnvil_bukkitEntity.set(this, view); + return view; } catch (Exception ex) { Logger.getLogger(AnvilView.class.getName()).log(Level.SEVERE, "Anvil Setup Error", ex); } + return getBukkitView(); } @@ -109,9 +114,11 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void e() { super.e(); + if (cost >= 0) { this.levelCost.set(cost); } + textChange.onChange(); } @@ -143,6 +150,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void setCustomTitle(String title) { this.customTitle = title; + try { mc_Container_title.set(this, new ChatMessage(customTitle != null ? customTitle : "")); } catch (Exception ex) { @@ -159,9 +167,9 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { public int getLevelCost() { if (cost >= 0) { return cost; - } else { - return this.levelCost.get(); } + + return this.levelCost.get(); } @Override @@ -206,7 +214,6 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void open() { - // Counter stuff that the game uses to keep track of inventories int id = entity.nextContainerCounter(); diff --git a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTCompoundImpl.java b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTCompoundImpl.java index a727dfed..46f76740 100644 --- a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTCompoundImpl.java +++ b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTCompoundImpl.java @@ -15,7 +15,6 @@ import java.util.Set; import java.util.UUID; public class NBTCompoundImpl implements NBTCompound { - protected NBTTagCompound compound; protected NBTCompoundImpl(NBTTagCompound compound) { @@ -151,11 +150,11 @@ public class NBTCompoundImpl implements NBTCompound { public NBTCompound getCompound(String tag) { if (has(tag)) { return getNBTObject(tag).asCompound(); - } else { - NBTTagCompound newCompound = new NBTTagCompound(); - compound.set(tag, newCompound); - return new NBTCompoundImpl(newCompound); } + + NBTTagCompound newCompound = new NBTTagCompound(); + compound.set(tag, newCompound); + return new NBTCompoundImpl(newCompound); } @Override @@ -175,15 +174,17 @@ public class NBTCompoundImpl implements NBTCompound { addExtras(); NBTTagCompound compound = this.compound.clone(); - for (String exclusion : exclusions) + for (String exclusion : exclusions) { compound.remove(exclusion); + } NBTCompressedStreamTools.a(compound, (OutputStream) dataOutput); return outputStream.toByteArray(); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } + return null; } @@ -192,8 +193,8 @@ public class NBTCompoundImpl implements NBTCompound { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(serialized); ObjectInputStream dataInput = new ObjectInputStream(inputStream)) { compound = NBTCompressedStreamTools.a((InputStream) dataInput); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } } diff --git a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTCoreImpl.java b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTCoreImpl.java index 7a338dce..d0f1bd7c 100644 --- a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTCoreImpl.java +++ b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTCoreImpl.java @@ -10,7 +10,6 @@ import org.bukkit.entity.Entity; import org.bukkit.inventory.ItemStack; public class NBTCoreImpl implements NBTCore { - @Override public NBTItem of(ItemStack item) { return new NBTItemImpl(CraftItemStack.asNMSCopy(item)); @@ -26,6 +25,7 @@ public class NBTCoreImpl implements NBTCore { net.minecraft.server.v1_15_R1.Entity nmsEntity = ((CraftEntity) entity).getHandle(); NBTTagCompound nbt = new NBTTagCompound(); nmsEntity.save(nbt); + return new NBTEntityImpl(nbt, nmsEntity); } diff --git a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTEntityImpl.java b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTEntityImpl.java index 9343e647..ce6c1151 100644 --- a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTEntityImpl.java +++ b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTEntityImpl.java @@ -14,11 +14,11 @@ import org.bukkit.craftbukkit.v1_15_R1.CraftWorld; import java.util.Optional; public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { - private Entity nmsEntity; public NBTEntityImpl(NBTTagCompound entityNBT, Entity nmsEntity) { super(entityNBT); + this.nmsEntity = nmsEntity; } @@ -45,21 +45,25 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { spawned.setLocation(location.getX(), location.getY(), location.getZ(), location.getPitch(), location.getYaw()); nmsEntity = spawned; + return entity; } } + return null; } @Override public org.bukkit.entity.Entity reSpawn(Location location) { nmsEntity.dead = true; + return spawn(location); } @Override public NBTCompound set(String tag, byte[] b) { compound.setByteArray(tag, b); + return this; } diff --git a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTItemImpl.java b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTItemImpl.java index dbd5f2f0..086c8bfc 100644 --- a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTItemImpl.java @@ -6,20 +6,20 @@ import org.bukkit.craftbukkit.v1_15_R1.inventory.CraftItemStack; import org.bukkit.inventory.ItemStack; public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { - private final net.minecraft.server.v1_15_R1.ItemStack nmsItem; public NBTItemImpl(net.minecraft.server.v1_15_R1.ItemStack nmsItem) { super(nmsItem != null && nmsItem.hasTag() ? nmsItem.getTag() : new NBTTagCompound()); + this.nmsItem = nmsItem; } public ItemStack finish() { if (nmsItem == null) { return CraftItemStack.asBukkitCopy(net.minecraft.server.v1_15_R1.ItemStack.a(compound)); - } else { - return CraftItemStack.asBukkitCopy(nmsItem); } + + return CraftItemStack.asBukkitCopy(nmsItem); } @Override diff --git a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTObjectImpl.java b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTObjectImpl.java index 8f85aea4..3b9a5a28 100644 --- a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTObjectImpl.java +++ b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTObjectImpl.java @@ -7,7 +7,6 @@ import net.minecraft.server.v1_15_R1.NBTTagCompound; import java.util.Set; public class NBTObjectImpl implements NBTObject { - private final NBTTagCompound compound; private final String tag; diff --git a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/world/SItemStackImpl.java b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/world/SItemStackImpl.java index 0bf8d1a3..b16d557d 100644 --- a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/world/SItemStackImpl.java +++ b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/world/SItemStackImpl.java @@ -11,7 +11,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public class SItemStackImpl implements SItemStack { - private final ItemStack item; public SItemStackImpl(ItemStack item) { @@ -21,15 +20,19 @@ public class SItemStackImpl implements SItemStack { @Override public void breakItem(Player player, int amount) { EntityPlayer entityPlayer = ((CraftPlayer) player).getHandle(); + for (int i = 0; i < amount; ++i) { Vec3D vec3d = new Vec3D(((double) this.random.nextFloat() - 0.5D) * 0.1D, Math.random() * 0.1D + 0.1D, 0.0D); vec3d = vec3d.a(-entityPlayer.pitch * 0.017453292F); vec3d = vec3d.b(-entityPlayer.yaw * 0.017453292F); + double d0 = (double) (-this.random.nextFloat()) * 0.6D - 0.3D; + Vec3D vec3d1 = new Vec3D(((double) this.random.nextFloat() - 0.5D) * 0.3D, d0, 0.6D); vec3d1 = vec3d1.a(-entityPlayer.pitch * 0.017453292F); vec3d1 = vec3d1.b(-entityPlayer.yaw * 0.017453292F); vec3d1 = vec3d1.add(entityPlayer.locX(), entityPlayer.getHeadY(), entityPlayer.locZ()); + entityPlayer.world.addParticle(new ParticleParamItem(Particles.ITEM, CraftItemStack.asNMSCopy(item)), vec3d1.x, vec3d1.y, vec3d1.z, vec3d.x, vec3d.y + 0.05D, vec3d.z); } } diff --git a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/world/SSpawnerImpl.java b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/world/SSpawnerImpl.java index 4e75c59d..a347fba9 100644 --- a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/world/SSpawnerImpl.java +++ b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/world/SSpawnerImpl.java @@ -25,7 +25,6 @@ import java.util.Random; import java.util.Set; public class SSpawnerImpl implements SSpawner { - private final Location spawnerLocation; public SSpawnerImpl(Location location) { @@ -40,7 +39,6 @@ public class SSpawnerImpl implements SSpawner { @Override public LivingEntity spawnEntity(EntityType type, String particleType, SpawnedEntity spawned, Set canSpawnOn) { - MobSpawnerData data = new MobSpawnerData(); NBTTagCompound compound = data.getEntity(); @@ -58,7 +56,9 @@ public class SSpawnerImpl implements SSpawner { double z = spawnerLocation.getZ() + (random.nextDouble() - random.nextDouble()) * (double) spawnRange + 0.5D; Optional optionalEntity = EntityTypes.a(compound, world); - if (!optionalEntity.isPresent()) continue; + if (!optionalEntity.isPresent()) { + continue; + } Entity entity = optionalEntity.get(); entity.setPosition(x, y, z); @@ -66,28 +66,30 @@ public class SSpawnerImpl implements SSpawner { BlockPosition position = entity.getChunkCoordinates(); DifficultyDamageScaler damageScaler = world.getDamageScaler(position); - if (!(entity instanceof EntityInsentient)) + if (!(entity instanceof EntityInsentient)) { continue; + } EntityInsentient entityInsentient = (EntityInsentient) entity; Location spot = new Location(spawnerLocation.getWorld(), x, y, z); - if (!canSpawn(world, entityInsentient, spot, canSpawnOn)) + if (!canSpawn(world, entityInsentient, spot, canSpawnOn)) { continue; + } - entityInsentient.prepare(world, damageScaler, EnumMobSpawn.SPAWNER, - null, null); + entityInsentient.prepare(world, damageScaler, EnumMobSpawn.SPAWNER, null, null); LivingEntity craftEntity = (LivingEntity) entity.getBukkitEntity(); - if (spawned != null) - if (!spawned.onSpawn(craftEntity)) - return null; + if (spawned != null && !spawned.onSpawn(craftEntity)) { + return null; + } if (particleType != null) { float xx = (float) (0 + (Math.random() * 1)); float yy = (float) (0 + (Math.random() * 2)); float zz = (float) (0 + (Math.random() * 1)); + CompatibleParticleHandler.spawnParticles(CompatibleParticleHandler.ParticleType.getParticle(particleType), spot, 5, xx, yy, zz, 0); } @@ -99,34 +101,38 @@ public class SSpawnerImpl implements SSpawner { return craftEntity; } + return null; } private boolean canSpawn(WorldServer world, EntityInsentient entityInsentient, Location location, Set canSpawnOn) { - - if (!world.getCubes(entityInsentient, entityInsentient.getBoundingBox())) + if (!world.getCubes(entityInsentient, entityInsentient.getBoundingBox())) { return false; + } CompatibleMaterial spawnedIn = CompatibleMaterial.getMaterial(location.getBlock()); CompatibleMaterial spawnedOn = CompatibleMaterial.getMaterial(location.getBlock().getRelative(BlockFace.DOWN)); - if (spawnedIn == null || spawnedOn == null) + if (spawnedIn == null || spawnedOn == null) { return false; + } - if (!spawnedIn.isAir() - && spawnedIn != CompatibleMaterial.WATER - && !spawnedIn.name().contains("PRESSURE") - && !spawnedIn.name().contains("SLAB")) { + if (!spawnedIn.isAir() && + spawnedIn != CompatibleMaterial.WATER && + !spawnedIn.name().contains("PRESSURE") && + !spawnedIn.name().contains("SLAB")) { return false; } for (CompatibleMaterial material : canSpawnOn) { if (material == null) continue; - if (spawnedOn.equals(material) || material.isAir()) + if (spawnedOn.equals(material) || material.isAir()) { return true; + } } + return false; } } diff --git a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/world/SWorldImpl.java b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/world/SWorldImpl.java index bed8355a..5b569025 100644 --- a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/world/SWorldImpl.java +++ b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/world/SWorldImpl.java @@ -7,7 +7,6 @@ import java.util.ArrayList; import java.util.List; public class SWorldImpl implements SWorld { - public SWorldImpl() { } diff --git a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/world/WorldCoreImpl.java b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/world/WorldCoreImpl.java index ee51a767..b32e1e7a 100644 --- a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/world/WorldCoreImpl.java +++ b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/world/WorldCoreImpl.java @@ -57,41 +57,43 @@ public class WorldCoreImpl implements WorldCore { public void randomTickChunk(org.bukkit.Chunk bukkitChunk, int tickAmount) { Chunk chunk = ((CraftChunk) bukkitChunk).getHandle(); - if (tickAmount > 0) { - ChunkCoordIntPair chunkcoordintpair = chunk.getPos(); - int j = chunkcoordintpair.d(); - int k = chunkcoordintpair.e(); - GameProfilerFiller profiler = chunk.world.getMethodProfiler(); + if (tickAmount <= 0) { + return; + } - profiler.enter("tickBlocks"); + ChunkCoordIntPair chunkcoordintpair = chunk.getPos(); + int j = chunkcoordintpair.d(); + int k = chunkcoordintpair.e(); + GameProfilerFiller profiler = chunk.world.getMethodProfiler(); - for (ChunkSection chunksection : chunk.getSections()) { - if (chunksection != Chunk.a && chunksection.d()) { - int j1 = chunksection.getYPosition(); + profiler.enter("tickBlocks"); - for (int k1 = 0; k1 < tickAmount; ++k1) { - BlockPosition blockposition2 = chunk.world.a(j, j1, k, 15); - profiler.enter("randomTick"); - IBlockData iblockdata = chunksection.getType( - blockposition2.getX() - j, - blockposition2.getY() - j1, - blockposition2.getZ() - k); + for (ChunkSection chunksection : chunk.getSections()) { + if (chunksection != Chunk.a && chunksection.d()) { + int j1 = chunksection.getYPosition(); - if (iblockdata.q()) { - iblockdata.b((WorldServer) chunk.world, blockposition2, chunk.world.random); - } + for (int k1 = 0; k1 < tickAmount; ++k1) { + BlockPosition blockposition2 = chunk.world.a(j, j1, k, 15); + profiler.enter("randomTick"); + IBlockData iblockdata = chunksection.getType( + blockposition2.getX() - j, + blockposition2.getY() - j1, + blockposition2.getZ() - k); - Fluid fluid = iblockdata.getFluid(); - if (fluid.h()) { - fluid.b(chunk.world, blockposition2, chunk.world.random); - } - - profiler.exit(); + if (iblockdata.q()) { + iblockdata.b((WorldServer) chunk.world, blockposition2, chunk.world.random); } + + Fluid fluid = iblockdata.getFluid(); + if (fluid.h()) { + fluid.b(chunk.world, blockposition2, chunk.world.random); + } + + profiler.exit(); } } - - profiler.exit(); } + + profiler.exit(); } } diff --git a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/world/spawner/BBaseSpawnerImpl.java b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/world/spawner/BBaseSpawnerImpl.java index a353d577..744272b3 100644 --- a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/world/spawner/BBaseSpawnerImpl.java +++ b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/world/spawner/BBaseSpawnerImpl.java @@ -63,110 +63,111 @@ public class BBaseSpawnerImpl implements BBaseSpawner { double spawnerE = (double) ReflectionUtils.getFieldValue(spawner, "e"); ReflectionUtils.setFieldValue(spawner, "f", spawnerE); ReflectionUtils.setFieldValue(spawner, "e", (spawnerE + (double) (1000F / ((float) spawner.spawnDelay + 200F))) % 360D); - } else { - if (spawner.spawnDelay == -1) { - delay(spawner); + return; + } + + if (spawner.spawnDelay == -1) { + delay(spawner); + } + + if (spawner.spawnDelay > 0) { + --spawner.spawnDelay; + return; + } + + boolean flag = false; + int i = 0; + + while (true) { + if (i >= spawner.spawnCount) { + if (flag) { + delay(spawner); + } + + break; } - if (spawner.spawnDelay > 0) { - --spawner.spawnDelay; + NBTTagCompound nbttagcompound = spawner.spawnData.getEntity(); + Optional> optional = EntityTypes.a(nbttagcompound); + if (!optional.isPresent()) { + delay(spawner); return; } - boolean flag = false; - int i = 0; - - while (true) { - if (i >= spawner.spawnCount) { - if (flag) { + NBTTagList nbttaglist = nbttagcompound.getList("Pos", 6); + int j = nbttaglist.size(); + double d3 = j >= 1 ? nbttaglist.h(0) : (double) blockposition.getX() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; + double d4 = j >= 2 ? nbttaglist.h(1) : (double) (blockposition.getY() + world.random.nextInt(3) - 1); + double d5 = j >= 3 ? nbttaglist.h(2) : (double) blockposition.getZ() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; + if (world.a(optional.get().a(d3, d4, d5)) && EntityPositionTypes.a(optional.get(), world.getMinecraftWorld(), EnumMobSpawn.SPAWNER, new BlockPosition(d3, d4, d5), world.getRandom())) { + label112: + { + Entity entity = EntityTypes.a(nbttagcompound, world, (entity1) -> { + entity1.setPositionRotation(d3, d4, d5, entity1.yaw, entity1.pitch); + return entity1; + }); + if (entity == null) { delay(spawner); + return; } - break; - } + int k = world.a(entity.getClass(), (new AxisAlignedBB( + blockposition.getX(), + blockposition.getY(), + blockposition.getZ(), + blockposition.getX() + 1, + blockposition.getY() + 1, + blockposition.getZ() + 1)) + .g(spawner.spawnRange)).size(); - NBTTagCompound nbttagcompound = spawner.spawnData.getEntity(); - Optional> optional = EntityTypes.a(nbttagcompound); - if (!optional.isPresent()) { - delay(spawner); - return; - } + if (k >= spawner.maxNearbyEntities) { + delay(spawner); + return; + } - NBTTagList nbttaglist = nbttagcompound.getList("Pos", 6); - int j = nbttaglist.size(); - double d3 = j >= 1 ? nbttaglist.h(0) : (double) blockposition.getX() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; - double d4 = j >= 2 ? nbttaglist.h(1) : (double) (blockposition.getY() + world.random.nextInt(3) - 1); - double d5 = j >= 3 ? nbttaglist.h(2) : (double) blockposition.getZ() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; - if (world.a(optional.get().a(d3, d4, d5)) && EntityPositionTypes.a(optional.get(), world.getMinecraftWorld(), EnumMobSpawn.SPAWNER, new BlockPosition(d3, d4, d5), world.getRandom())) { - label112: - { - Entity entity = EntityTypes.a(nbttagcompound, world, (entity1) -> { - entity1.setPositionRotation(d3, d4, d5, entity1.yaw, entity1.pitch); - return entity1; - }); - if (entity == null) { - delay(spawner); - return; + entity.setPositionRotation(entity.locX(), entity.locY(), entity.locZ(), world.random.nextFloat() * 360F, 0F); + if (entity instanceof EntityInsentient) { + EntityInsentient entityinsentient = (EntityInsentient) entity; + if (!entityinsentient.a(world, EnumMobSpawn.SPAWNER) || !entityinsentient.a(world)) { + break label112; } - int k = world.a(entity.getClass(), (new AxisAlignedBB( - blockposition.getX(), - blockposition.getY(), - blockposition.getZ(), - blockposition.getX() + 1, - blockposition.getY() + 1, - blockposition.getZ() + 1)) - .g(spawner.spawnRange)).size(); - - if (k >= spawner.maxNearbyEntities) { - delay(spawner); - return; + if (spawner.spawnData.getEntity().e() == 1 && spawner.spawnData.getEntity().hasKeyOfType("id", 8)) { + ((EntityInsentient) entity).prepare(world, world.getDamageScaler(new BlockPosition(entity)), EnumMobSpawn.SPAWNER, null, null); } - entity.setPositionRotation(entity.locX(), entity.locY(), entity.locZ(), world.random.nextFloat() * 360F, 0F); + if (entityinsentient.world.spigotConfig.nerfSpawnerMobs) { + try { + entityinsentient.getClass().getField("aware").setBoolean(entityinsentient, false); + } catch (NoSuchFieldException ignore) { // Spigot 1.15.0 uses another flag for it + entityinsentient.fromMobSpawner = true; + } + } + } + + if (CraftEventFactory.callSpawnerSpawnEvent(entity, blockposition).isCancelled()) { + Entity vehicle = entity.getVehicle(); + if (vehicle != null) { + vehicle.dead = true; + } + + Entity passenger; + for (Iterator var19 = entity.getAllPassengers().iterator(); var19.hasNext(); passenger.dead = true) { + passenger = var19.next(); + } + } else { + addWithPassengers(spawner, entity); + world.triggerEffect(2004, blockposition, 0); if (entity instanceof EntityInsentient) { - EntityInsentient entityinsentient = (EntityInsentient) entity; - if (!entityinsentient.a(world, EnumMobSpawn.SPAWNER) || !entityinsentient.a(world)) { - break label112; - } - - if (spawner.spawnData.getEntity().e() == 1 && spawner.spawnData.getEntity().hasKeyOfType("id", 8)) { - ((EntityInsentient) entity).prepare(world, world.getDamageScaler(new BlockPosition(entity)), EnumMobSpawn.SPAWNER, null, null); - } - - if (entityinsentient.world.spigotConfig.nerfSpawnerMobs) { - try { - entityinsentient.getClass().getField("aware").setBoolean(entityinsentient, false); - } catch (NoSuchFieldException ignore) { // Spigot 1.15.0 uses another flag for it - entityinsentient.fromMobSpawner = true; - } - } + ((EntityInsentient) entity).doSpawnEffect(); } - if (CraftEventFactory.callSpawnerSpawnEvent(entity, blockposition).isCancelled()) { - Entity vehicle = entity.getVehicle(); - if (vehicle != null) { - vehicle.dead = true; - } - - Entity passenger; - for (Iterator var19 = entity.getAllPassengers().iterator(); var19.hasNext(); passenger.dead = true) { - passenger = var19.next(); - } - } else { - addWithPassengers(spawner, entity); - world.triggerEffect(2004, blockposition, 0); - if (entity instanceof EntityInsentient) { - ((EntityInsentient) entity).doSpawnEffect(); - } - - flag = true; - } + flag = true; } } - - ++i; } + + ++i; } } @@ -200,4 +201,4 @@ public class BBaseSpawnerImpl implements BBaseSpawner { } } } -} \ No newline at end of file +} diff --git a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/anvil/AnvilCore.java b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/anvil/AnvilCore.java index 1e35a315..e8e775a7 100644 --- a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/anvil/AnvilCore.java +++ b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/anvil/AnvilCore.java @@ -7,16 +7,17 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; public class AnvilCore implements com.songoda.core.nms.anvil.AnvilCore { - @Override public CustomAnvil createAnvil(Player player) { EntityPlayer p = ((CraftPlayer) player).getHandle(); + return new AnvilView(p.nextContainerCounter(), p, null); } @Override public CustomAnvil createAnvil(Player player, InventoryHolder holder) { EntityPlayer p = ((CraftPlayer) player).getHandle(); + return new AnvilView(p.nextContainerCounter(), p, holder); } } diff --git a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/anvil/AnvilInventoryCustom.java b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/anvil/AnvilInventoryCustom.java index 9a1d078a..a6c55837 100644 --- a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/anvil/AnvilInventoryCustom.java +++ b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/anvil/AnvilInventoryCustom.java @@ -7,11 +7,11 @@ import org.bukkit.craftbukkit.v1_16_R1.inventory.CraftInventoryAnvil; import org.bukkit.inventory.InventoryHolder; public class AnvilInventoryCustom extends CraftInventoryAnvil { - final InventoryHolder holder; public AnvilInventoryCustom(InventoryHolder holder, Location location, IInventory inventory, IInventory resultInventory, ContainerAnvil container) { super(location, inventory, resultInventory, container); + this.holder = holder; } diff --git a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/anvil/AnvilView.java b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/anvil/AnvilView.java index 15e76699..89ce4bb2 100644 --- a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/anvil/AnvilView.java +++ b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/anvil/AnvilView.java @@ -26,7 +26,6 @@ import java.util.logging.Level; import java.util.logging.Logger; public class AnvilView extends ContainerAnvil implements CustomAnvil { - private final EntityPlayer entity; private final Inventory inventory; private String customTitle = "Repairing"; @@ -43,8 +42,10 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { try { mc_ContainerAnvil_repairInventory = ContainerAnvilAbstract.class.getDeclaredField("repairInventory"); mc_ContainerAnvil_repairInventory.setAccessible(true); + mc_ContainerAnvil_resultInventory = ContainerAnvilAbstract.class.getDeclaredField("resultInventory"); mc_ContainerAnvil_resultInventory.setAccessible(true); + mc_ContainerAnvil_bukkitEntity = ContainerAnvil.class.getDeclaredField("bukkitEntity"); mc_ContainerAnvil_bukkitEntity.setAccessible(true); } catch (Exception ex) { @@ -77,9 +78,11 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { public AnvilView(int id, EntityPlayer entity, InventoryHolder holder) { super(id, entity.inventory, ContainerAccess.at(entity.world, new BlockPosition(0, 0, 0))); + this.setTitle(new ChatMessage(customTitle != null ? customTitle : "")); this.checkReachable = false; this.entity = entity; + if (holder != null) { this.inventory = getBukkitView(entity, holder).getTopInventory(); } else { @@ -95,10 +98,12 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { (IInventory) mc_ContainerAnvil_resultInventory.get(this), this); CraftInventoryView view = new CraftInventoryView(player.getBukkitEntity(), craftInventory, this); mc_ContainerAnvil_bukkitEntity.set(this, view); + return view; } catch (Exception ex) { Logger.getLogger(AnvilView.class.getName()).log(Level.SEVERE, "Anvil Setup Error", ex); } + return getBukkitView(); } @@ -110,9 +115,11 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void e() { super.e(); + if (cost >= 0) { this.levelCost.set(cost); } + textChange.onChange(); } @@ -144,6 +151,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void setCustomTitle(String title) { this.customTitle = title; + try { mc_Container_title.set(this, new ChatMessage(customTitle != null ? customTitle : "")); } catch (Exception ex) { @@ -160,9 +168,9 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { public int getLevelCost() { if (cost >= 0) { return cost; - } else { - return this.levelCost.get(); } + + return this.levelCost.get(); } @Override @@ -207,7 +215,6 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void open() { - // Counter stuff that the game uses to keep track of inventories int id = entity.nextContainerCounter(); diff --git a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTCompoundImpl.java b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTCompoundImpl.java index 3ed48bf0..56945be4 100644 --- a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTCompoundImpl.java +++ b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTCompoundImpl.java @@ -15,7 +15,6 @@ import java.util.Set; import java.util.UUID; public class NBTCompoundImpl implements NBTCompound { - protected NBTTagCompound compound; protected NBTCompoundImpl(NBTTagCompound compound) { @@ -151,11 +150,11 @@ public class NBTCompoundImpl implements NBTCompound { public NBTCompound getCompound(String tag) { if (has(tag)) { return getNBTObject(tag).asCompound(); - } else { - NBTTagCompound newCompound = new NBTTagCompound(); - compound.set(tag, newCompound); - return new NBTCompoundImpl(newCompound); } + + NBTTagCompound newCompound = new NBTTagCompound(); + compound.set(tag, newCompound); + return new NBTCompoundImpl(newCompound); } @Override @@ -175,15 +174,17 @@ public class NBTCompoundImpl implements NBTCompound { addExtras(); NBTTagCompound compound = this.compound.clone(); - for (String exclusion : exclusions) + for (String exclusion : exclusions) { compound.remove(exclusion); + } NBTCompressedStreamTools.a(compound, (OutputStream) dataOutput); return outputStream.toByteArray(); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } + return null; } @@ -192,8 +193,8 @@ public class NBTCompoundImpl implements NBTCompound { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(serialized); ObjectInputStream dataInput = new ObjectInputStream(inputStream)) { compound = NBTCompressedStreamTools.a((InputStream) dataInput); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } } diff --git a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTCoreImpl.java b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTCoreImpl.java index 0c647586..90b43fa1 100644 --- a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTCoreImpl.java +++ b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTCoreImpl.java @@ -10,7 +10,6 @@ import org.bukkit.entity.Entity; import org.bukkit.inventory.ItemStack; public class NBTCoreImpl implements NBTCore { - @Override public NBTItem of(ItemStack item) { return new NBTItemImpl(CraftItemStack.asNMSCopy(item)); diff --git a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTEntityImpl.java b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTEntityImpl.java index c1b4af43..54340361 100644 --- a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTEntityImpl.java +++ b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTEntityImpl.java @@ -13,11 +13,11 @@ import org.bukkit.craftbukkit.v1_16_R1.CraftWorld; import java.util.Optional; public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { - private Entity nmsEntity; public NBTEntityImpl(NBTTagCompound entityNBT, Entity nmsEntity) { super(entityNBT); + this.nmsEntity = nmsEntity; } @@ -43,9 +43,11 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { org.bukkit.entity.Entity entity = spawned.getBukkitEntity(); entity.teleport(location); nmsEntity = spawned; + return entity; } } + return null; } diff --git a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTItemImpl.java b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTItemImpl.java index 8ee25e9a..c576efa4 100644 --- a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTItemImpl.java @@ -7,20 +7,20 @@ import org.bukkit.craftbukkit.v1_16_R1.inventory.CraftItemStack; import org.bukkit.inventory.ItemStack; public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { - private final net.minecraft.server.v1_16_R1.ItemStack nmsItem; public NBTItemImpl(net.minecraft.server.v1_16_R1.ItemStack nmsItem) { super(nmsItem != null && nmsItem.hasTag() ? nmsItem.getTag() : new NBTTagCompound()); + this.nmsItem = nmsItem; } public ItemStack finish() { if (nmsItem == null) { return CraftItemStack.asBukkitCopy(net.minecraft.server.v1_16_R1.ItemStack.a(compound)); - } else { - return CraftItemStack.asBukkitCopy(nmsItem); } + + return CraftItemStack.asBukkitCopy(nmsItem); } @Override diff --git a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTObjectImpl.java b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTObjectImpl.java index 3d2968c8..c530c25f 100644 --- a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTObjectImpl.java +++ b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTObjectImpl.java @@ -7,7 +7,6 @@ import net.minecraft.server.v1_16_R1.NBTTagCompound; import java.util.Set; public class NBTObjectImpl implements NBTObject { - private final NBTTagCompound compound; private final String tag; diff --git a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/world/SItemStackImpl.java b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/world/SItemStackImpl.java index 1945e47d..d190e25f 100644 --- a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/world/SItemStackImpl.java +++ b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/world/SItemStackImpl.java @@ -11,7 +11,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public class SItemStackImpl implements SItemStack { - private final ItemStack item; public SItemStackImpl(ItemStack item) { @@ -21,15 +20,19 @@ public class SItemStackImpl implements SItemStack { @Override public void breakItem(Player player, int amount) { EntityPlayer entityPlayer = ((CraftPlayer) player).getHandle(); + for (int i = 0; i < amount; ++i) { Vec3D vec3d = new Vec3D(((double) this.random.nextFloat() - 0.5D) * 0.1D, Math.random() * 0.1D + 0.1D, 0.0D); vec3d = vec3d.a(-entityPlayer.pitch * 0.017453292F); vec3d = vec3d.b(-entityPlayer.yaw * 0.017453292F); + double d0 = (double) (-this.random.nextFloat()) * 0.6D - 0.3D; + Vec3D vec3d1 = new Vec3D(((double) this.random.nextFloat() - 0.5D) * 0.3D, d0, 0.6D); vec3d1 = vec3d1.a(-entityPlayer.pitch * 0.017453292F); vec3d1 = vec3d1.b(-entityPlayer.yaw * 0.017453292F); vec3d1 = vec3d1.add(entityPlayer.locX(), entityPlayer.getHeadY(), entityPlayer.locZ()); + entityPlayer.world.addParticle(new ParticleParamItem(Particles.ITEM, CraftItemStack.asNMSCopy(item)), vec3d1.x, vec3d1.y, vec3d1.z, vec3d.x, vec3d.y + 0.05D, vec3d.z); } } diff --git a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/world/SSpawnerImpl.java b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/world/SSpawnerImpl.java index e582b3f3..ad305fa8 100644 --- a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/world/SSpawnerImpl.java +++ b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/world/SSpawnerImpl.java @@ -25,7 +25,6 @@ import java.util.Random; import java.util.Set; public class SSpawnerImpl implements SSpawner { - private final Location spawnerLocation; public SSpawnerImpl(Location location) { @@ -40,7 +39,6 @@ public class SSpawnerImpl implements SSpawner { @Override public LivingEntity spawnEntity(EntityType type, String particleType, SpawnedEntity spawned, Set canSpawnOn) { - MobSpawnerData data = new MobSpawnerData(); NBTTagCompound compound = data.getEntity(); @@ -58,7 +56,9 @@ public class SSpawnerImpl implements SSpawner { double z = spawnerLocation.getZ() + (random.nextDouble() - random.nextDouble()) * (double) spawnRange + 0.5D; Optional optionalEntity = EntityTypes.a(compound, world); - if (!optionalEntity.isPresent()) continue; + if (!optionalEntity.isPresent()) { + continue; + } Entity entity = optionalEntity.get(); entity.setPosition(x, y, z); @@ -66,28 +66,30 @@ public class SSpawnerImpl implements SSpawner { BlockPosition position = entity.getChunkCoordinates(); DifficultyDamageScaler damageScaler = world.getDamageScaler(position); - if (!(entity instanceof EntityInsentient)) + if (!(entity instanceof EntityInsentient)) { continue; + } EntityInsentient entityInsentient = (EntityInsentient) entity; Location spot = new Location(spawnerLocation.getWorld(), x, y, z); - if (!canSpawn(world, entityInsentient, spot, canSpawnOn)) + if (!canSpawn(world, entityInsentient, spot, canSpawnOn)) { continue; + } - entityInsentient.prepare(world, damageScaler, EnumMobSpawn.SPAWNER, - null, null); + entityInsentient.prepare(world, damageScaler, EnumMobSpawn.SPAWNER, null, null); LivingEntity craftEntity = (LivingEntity) entity.getBukkitEntity(); - if (spawned != null) - if (!spawned.onSpawn(craftEntity)) - return null; + if (spawned != null && !spawned.onSpawn(craftEntity)) { + return null; + } if (particleType != null) { float xx = (float) (0 + (Math.random() * 1)); float yy = (float) (0 + (Math.random() * 2)); float zz = (float) (0 + (Math.random() * 1)); + CompatibleParticleHandler.spawnParticles(CompatibleParticleHandler.ParticleType.getParticle(particleType), spot, 5, xx, yy, zz, 0); } @@ -99,34 +101,38 @@ public class SSpawnerImpl implements SSpawner { return craftEntity; } + return null; } private boolean canSpawn(WorldServer world, EntityInsentient entityInsentient, Location location, Set canSpawnOn) { - - if (!world.getCubes(entityInsentient, entityInsentient.getBoundingBox())) + if (!world.getCubes(entityInsentient, entityInsentient.getBoundingBox())) { return false; + } CompatibleMaterial spawnedIn = CompatibleMaterial.getMaterial(location.getBlock()); CompatibleMaterial spawnedOn = CompatibleMaterial.getMaterial(location.getBlock().getRelative(BlockFace.DOWN)); - if (spawnedIn == null || spawnedOn == null) + if (spawnedIn == null || spawnedOn == null) { return false; + } - if (!spawnedIn.isAir() - && spawnedIn != CompatibleMaterial.WATER - && !spawnedIn.name().contains("PRESSURE") - && !spawnedIn.name().contains("SLAB")) { + if (!spawnedIn.isAir() && + spawnedIn != CompatibleMaterial.WATER && + !spawnedIn.name().contains("PRESSURE") && + !spawnedIn.name().contains("SLAB")) { return false; } for (CompatibleMaterial material : canSpawnOn) { if (material == null) continue; - if (spawnedOn.equals(material) || material.isAir()) + if (spawnedOn.equals(material) || material.isAir()) { return true; + } } + return false; } } diff --git a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/world/SWorldImpl.java b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/world/SWorldImpl.java index de5f8e38..1ad6bf55 100644 --- a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/world/SWorldImpl.java +++ b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/world/SWorldImpl.java @@ -7,7 +7,6 @@ import java.util.ArrayList; import java.util.List; public class SWorldImpl implements SWorld { - public SWorldImpl() { } diff --git a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/world/WorldCoreImpl.java b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/world/WorldCoreImpl.java index 04218147..b86c9568 100644 --- a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/world/WorldCoreImpl.java +++ b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/world/WorldCoreImpl.java @@ -57,42 +57,44 @@ public class WorldCoreImpl implements WorldCore { public void randomTickChunk(org.bukkit.Chunk bukkitChunk, int tickAmount) { Chunk chunk = ((CraftChunk) bukkitChunk).getHandle(); - if (tickAmount > 0) { - ChunkCoordIntPair chunkcoordintpair = chunk.getPos(); - int j = chunkcoordintpair.d(); - int k = chunkcoordintpair.e(); + if (tickAmount <= 0) { + return; + } - GameProfilerFiller profiler = chunk.world.getMethodProfiler(); + ChunkCoordIntPair chunkcoordintpair = chunk.getPos(); + int j = chunkcoordintpair.d(); + int k = chunkcoordintpair.e(); - profiler.enter("tickBlocks"); - for (ChunkSection chunksection : chunk.getSections()) { - if (chunksection != Chunk.a && chunksection.d()) { - int j1 = chunksection.getYPosition(); + GameProfilerFiller profiler = chunk.world.getMethodProfiler(); - for (int k1 = 0; k1 < tickAmount; ++k1) { - BlockPosition blockposition2 = chunk.world.a(j, j1, k, 15); - profiler.enter("randomTick"); + profiler.enter("tickBlocks"); + for (ChunkSection chunksection : chunk.getSections()) { + if (chunksection != Chunk.a && chunksection.d()) { + int j1 = chunksection.getYPosition(); - IBlockData iblockdata = chunksection.getType( - blockposition2.getX() - j, - blockposition2.getY() - j1, - blockposition2.getZ() - k); + for (int k1 = 0; k1 < tickAmount; ++k1) { + BlockPosition blockposition2 = chunk.world.a(j, j1, k, 15); + profiler.enter("randomTick"); - if (iblockdata.isTicking()) { - iblockdata.b(chunk.world, blockposition2, chunk.world.random); - } + IBlockData iblockdata = chunksection.getType( + blockposition2.getX() - j, + blockposition2.getY() - j1, + blockposition2.getZ() - k); - Fluid fluid = iblockdata.getFluid(); - if (fluid.f()) { - fluid.b(chunk.world, blockposition2, chunk.world.random); - } - - profiler.exit(); + if (iblockdata.isTicking()) { + iblockdata.b(chunk.world, blockposition2, chunk.world.random); } + + Fluid fluid = iblockdata.getFluid(); + if (fluid.f()) { + fluid.b(chunk.world, blockposition2, chunk.world.random); + } + + profiler.exit(); } } - - profiler.exit(); } + + profiler.exit(); } } diff --git a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/world/spawner/BBaseSpawnerImpl.java b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/world/spawner/BBaseSpawnerImpl.java index 1ba12b09..02273bef 100644 --- a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/world/spawner/BBaseSpawnerImpl.java +++ b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/world/spawner/BBaseSpawnerImpl.java @@ -62,104 +62,106 @@ public class BBaseSpawnerImpl implements BBaseSpawner { double spawnerE = (double) ReflectionUtils.getFieldValue(spawner, "e"); ReflectionUtils.setFieldValue(spawner, "f", spawnerE); ReflectionUtils.setFieldValue(spawner, "e", (spawnerE + (double) (1000F / ((float) spawner.spawnDelay + 200F))) % 360D); - } else { - if (spawner.spawnDelay == -1) { - delay(spawner); + return; + } + + if (spawner.spawnDelay == -1) { + delay(spawner); + } + + if (spawner.spawnDelay > 0) { + --spawner.spawnDelay; + return; + } + + boolean flag = false; + int i = 0; + + while (true) { + if (i >= spawner.spawnCount) { + if (flag) { + delay(spawner); + } + + break; } - if (spawner.spawnDelay > 0) { - --spawner.spawnDelay; + NBTTagCompound nbttagcompound = spawner.spawnData.getEntity(); + Optional> optional = EntityTypes.a(nbttagcompound); + if (!optional.isPresent()) { + delay(spawner); return; } - boolean flag = false; - int i = 0; - - while (true) { - if (i >= spawner.spawnCount) { - if (flag) { + NBTTagList nbttaglist = nbttagcompound.getList("Pos", 6); + int j = nbttaglist.size(); + double d3 = j >= 1 ? nbttaglist.h(0) : (double) blockposition.getX() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; + double d4 = j >= 2 ? nbttaglist.h(1) : (double) (blockposition.getY() + world.random.nextInt(3) - 1); + double d5 = j >= 3 ? nbttaglist.h(2) : (double) blockposition.getZ() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; + if (world.b(optional.get().a(d3, d4, d5)) && EntityPositionTypes.a(optional.get(), world.getMinecraftWorld(), EnumMobSpawn.SPAWNER, new BlockPosition(d3, d4, d5), world.getRandom())) { + label112: + { + Entity entity = EntityTypes.a(nbttagcompound, world, (entity1) -> { + entity1.setPositionRotation(d3, d4, d5, entity1.yaw, entity1.pitch); + return entity1; + }); + if (entity == null) { delay(spawner); + return; } - break; - } - NBTTagCompound nbttagcompound = spawner.spawnData.getEntity(); - Optional> optional = EntityTypes.a(nbttagcompound); - if (!optional.isPresent()) { - delay(spawner); - return; - } + int k = world.a(entity.getClass(), (new AxisAlignedBB( + blockposition.getX(), + blockposition.getY(), + blockposition.getZ(), + blockposition.getX() + 1, + blockposition.getY() + 1, + blockposition.getZ() + 1)) + .g(spawner.spawnRange)).size(); + if (k >= spawner.maxNearbyEntities) { + delay(spawner); + return; + } - NBTTagList nbttaglist = nbttagcompound.getList("Pos", 6); - int j = nbttaglist.size(); - double d3 = j >= 1 ? nbttaglist.h(0) : (double) blockposition.getX() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; - double d4 = j >= 2 ? nbttaglist.h(1) : (double) (blockposition.getY() + world.random.nextInt(3) - 1); - double d5 = j >= 3 ? nbttaglist.h(2) : (double) blockposition.getZ() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; - if (world.b(optional.get().a(d3, d4, d5)) && EntityPositionTypes.a(optional.get(), world.getMinecraftWorld(), EnumMobSpawn.SPAWNER, new BlockPosition(d3, d4, d5), world.getRandom())) { - label112: - { - Entity entity = EntityTypes.a(nbttagcompound, world, (entity1) -> { - entity1.setPositionRotation(d3, d4, d5, entity1.yaw, entity1.pitch); - return entity1; - }); - if (entity == null) { - delay(spawner); - return; + entity.setPositionRotation(entity.locX(), entity.locY(), entity.locZ(), world.random.nextFloat() * 360.0F, 0.0F); + if (entity instanceof EntityInsentient) { + EntityInsentient entityinsentient = (EntityInsentient) entity; + if (!entityinsentient.a(world, EnumMobSpawn.SPAWNER) || !entityinsentient.a(world)) { + break label112; } - int k = world.a(entity.getClass(), (new AxisAlignedBB( - blockposition.getX(), - blockposition.getY(), - blockposition.getZ(), - blockposition.getX() + 1, - blockposition.getY() + 1, - blockposition.getZ() + 1)) - .g(spawner.spawnRange)).size(); - if (k >= spawner.maxNearbyEntities) { - delay(spawner); - return; + if (spawner.spawnData.getEntity().e() == 1 && spawner.spawnData.getEntity().hasKeyOfType("id", 8)) { + ((EntityInsentient) entity).prepare(world, world.getDamageScaler(entity.getChunkCoordinates()), EnumMobSpawn.SPAWNER, null, null); } - entity.setPositionRotation(entity.locX(), entity.locY(), entity.locZ(), world.random.nextFloat() * 360.0F, 0.0F); + if (entityinsentient.world.spigotConfig.nerfSpawnerMobs) { + entityinsentient.aware = false; + } + } + + if (CraftEventFactory.callSpawnerSpawnEvent(entity, blockposition).isCancelled()) { + Entity vehicle = entity.getVehicle(); + if (vehicle != null) { + vehicle.dead = true; + } + + Entity passenger; + for (Iterator var19 = entity.getAllPassengers().iterator(); var19.hasNext(); passenger.dead = true) { + passenger = var19.next(); + } + } else { + addWithPassengers(spawner, entity); + world.triggerEffect(2004, blockposition, 0); if (entity instanceof EntityInsentient) { - EntityInsentient entityinsentient = (EntityInsentient) entity; - if (!entityinsentient.a(world, EnumMobSpawn.SPAWNER) || !entityinsentient.a(world)) { - break label112; - } - - if (spawner.spawnData.getEntity().e() == 1 && spawner.spawnData.getEntity().hasKeyOfType("id", 8)) { - ((EntityInsentient) entity).prepare(world, world.getDamageScaler(entity.getChunkCoordinates()), EnumMobSpawn.SPAWNER, null, null); - } - - if (entityinsentient.world.spigotConfig.nerfSpawnerMobs) { - entityinsentient.aware = false; - } + ((EntityInsentient) entity).doSpawnEffect(); } - if (CraftEventFactory.callSpawnerSpawnEvent(entity, blockposition).isCancelled()) { - Entity vehicle = entity.getVehicle(); - if (vehicle != null) { - vehicle.dead = true; - } - - Entity passenger; - for (Iterator var19 = entity.getAllPassengers().iterator(); var19.hasNext(); passenger.dead = true) { - passenger = var19.next(); - } - } else { - addWithPassengers(spawner, entity); - world.triggerEffect(2004, blockposition, 0); - if (entity instanceof EntityInsentient) { - ((EntityInsentient) entity).doSpawnEffect(); - } - - flag = true; - } + flag = true; } } - - ++i; } + + ++i; } } @@ -188,7 +190,6 @@ public class BBaseSpawnerImpl implements BBaseSpawner { @SuppressWarnings("JavadocReference") private void addWithPassengers(MobSpawnerAbstract spawner, Entity entity) { if (spawner.a().addEntity(entity, CreatureSpawnEvent.SpawnReason.SPAWNER)) { - for (Entity entity1 : entity.getPassengers()) { addWithPassengers(spawner, entity1); } diff --git a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/anvil/AnvilCore.java b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/anvil/AnvilCore.java index 70410849..42633228 100644 --- a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/anvil/AnvilCore.java +++ b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/anvil/AnvilCore.java @@ -7,7 +7,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; public class AnvilCore implements com.songoda.core.nms.anvil.AnvilCore { - @Override public CustomAnvil createAnvil(Player player) { EntityPlayer p = ((CraftPlayer) player).getHandle(); diff --git a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/anvil/AnvilInventoryCustom.java b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/anvil/AnvilInventoryCustom.java index 2e53d66e..e0e9169e 100644 --- a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/anvil/AnvilInventoryCustom.java +++ b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/anvil/AnvilInventoryCustom.java @@ -7,11 +7,11 @@ import org.bukkit.craftbukkit.v1_16_R2.inventory.CraftInventoryAnvil; import org.bukkit.inventory.InventoryHolder; public class AnvilInventoryCustom extends CraftInventoryAnvil { - final InventoryHolder holder; public AnvilInventoryCustom(InventoryHolder holder, Location location, IInventory inventory, IInventory resultInventory, ContainerAnvil container) { super(location, inventory, resultInventory, container); + this.holder = holder; } diff --git a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/anvil/AnvilView.java b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/anvil/AnvilView.java index ada5f32d..87cd83a5 100644 --- a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/anvil/AnvilView.java +++ b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/anvil/AnvilView.java @@ -26,7 +26,6 @@ import java.util.logging.Level; import java.util.logging.Logger; public class AnvilView extends ContainerAnvil implements CustomAnvil { - private final EntityPlayer entity; private final Inventory inventory; private String customTitle = "Repairing"; @@ -43,8 +42,10 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { try { mc_ContainerAnvil_repairInventory = ContainerAnvilAbstract.class.getDeclaredField("repairInventory"); mc_ContainerAnvil_repairInventory.setAccessible(true); + mc_ContainerAnvil_resultInventory = ContainerAnvilAbstract.class.getDeclaredField("resultInventory"); mc_ContainerAnvil_resultInventory.setAccessible(true); + mc_ContainerAnvil_bukkitEntity = ContainerAnvil.class.getDeclaredField("bukkitEntity"); mc_ContainerAnvil_bukkitEntity.setAccessible(true); } catch (Exception ex) { @@ -77,9 +78,11 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { public AnvilView(int id, EntityPlayer entity, InventoryHolder holder) { super(id, entity.inventory, ContainerAccess.at(entity.world, new BlockPosition(0, 0, 0))); + this.setTitle(new ChatMessage(customTitle != null ? customTitle : "")); this.checkReachable = false; this.entity = entity; + if (holder != null) { this.inventory = getBukkitView(entity, holder).getTopInventory(); } else { @@ -95,10 +98,12 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { (IInventory) mc_ContainerAnvil_resultInventory.get(this), this); CraftInventoryView view = new CraftInventoryView(player.getBukkitEntity(), craftInventory, this); mc_ContainerAnvil_bukkitEntity.set(this, view); + return view; } catch (Exception ex) { Logger.getLogger(AnvilView.class.getName()).log(Level.SEVERE, "Anvil Setup Error", ex); } + return getBukkitView(); } @@ -110,9 +115,11 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void e() { super.e(); + if (cost >= 0) { this.levelCost.set(cost); } + textChange.onChange(); } @@ -144,6 +151,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void setCustomTitle(String title) { this.customTitle = title; + try { mc_Container_title.set(this, new ChatMessage(customTitle != null ? customTitle : "")); } catch (Exception ex) { @@ -160,9 +168,9 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { public int getLevelCost() { if (cost >= 0) { return cost; - } else { - return this.levelCost.get(); } + + return this.levelCost.get(); } @Override @@ -207,7 +215,6 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void open() { - // Counter stuff that the game uses to keep track of inventories int id = entity.nextContainerCounter(); diff --git a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/nbt/NBTCompoundImpl.java b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/nbt/NBTCompoundImpl.java index 3a627f99..f2c989e1 100644 --- a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/nbt/NBTCompoundImpl.java +++ b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/nbt/NBTCompoundImpl.java @@ -15,7 +15,6 @@ import java.util.Set; import java.util.UUID; public class NBTCompoundImpl implements NBTCompound { - protected NBTTagCompound compound; protected NBTCompoundImpl(NBTTagCompound compound) { @@ -151,11 +150,11 @@ public class NBTCompoundImpl implements NBTCompound { public NBTCompound getCompound(String tag) { if (has(tag)) { return getNBTObject(tag).asCompound(); - } else { - NBTTagCompound newCompound = new NBTTagCompound(); - compound.set(tag, newCompound); - return new NBTCompoundImpl(newCompound); } + + NBTTagCompound newCompound = new NBTTagCompound(); + compound.set(tag, newCompound); + return new NBTCompoundImpl(newCompound); } @Override @@ -175,15 +174,17 @@ public class NBTCompoundImpl implements NBTCompound { addExtras(); NBTTagCompound compound = this.compound.clone(); - for (String exclusion : exclusions) + for (String exclusion : exclusions) { compound.remove(exclusion); + } NBTCompressedStreamTools.a(compound, (OutputStream) dataOutput); return outputStream.toByteArray(); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } + return null; } @@ -192,8 +193,8 @@ public class NBTCompoundImpl implements NBTCompound { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(serialized); ObjectInputStream dataInput = new ObjectInputStream(inputStream)) { compound = NBTCompressedStreamTools.a((InputStream) dataInput); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } } diff --git a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/nbt/NBTCoreImpl.java b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/nbt/NBTCoreImpl.java index e291da4f..72cba80f 100644 --- a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/nbt/NBTCoreImpl.java +++ b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/nbt/NBTCoreImpl.java @@ -10,7 +10,6 @@ import org.bukkit.entity.Entity; import org.bukkit.inventory.ItemStack; public class NBTCoreImpl implements NBTCore { - @Override public NBTItem of(ItemStack item) { return new NBTItemImpl(CraftItemStack.asNMSCopy(item)); @@ -26,6 +25,7 @@ public class NBTCoreImpl implements NBTCore { net.minecraft.server.v1_16_R2.Entity nmsEntity = ((CraftEntity) entity).getHandle(); NBTTagCompound nbt = new NBTTagCompound(); nmsEntity.save(nbt); + return new NBTEntityImpl(nbt, nmsEntity); } diff --git a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/nbt/NBTEntityImpl.java b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/nbt/NBTEntityImpl.java index 688d9996..0761dea5 100644 --- a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/nbt/NBTEntityImpl.java +++ b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/nbt/NBTEntityImpl.java @@ -13,11 +13,11 @@ import org.bukkit.craftbukkit.v1_16_R2.CraftWorld; import java.util.Optional; public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { - private Entity nmsEntity; public NBTEntityImpl(NBTTagCompound entityNBT, Entity nmsEntity) { super(entityNBT); + this.nmsEntity = nmsEntity; } @@ -43,9 +43,11 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { org.bukkit.entity.Entity entity = spawned.getBukkitEntity(); entity.teleport(location); nmsEntity = spawned; + return entity; } } + return null; } diff --git a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/nbt/NBTItemImpl.java b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/nbt/NBTItemImpl.java index 488a07d4..d350ea94 100644 --- a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/nbt/NBTItemImpl.java @@ -6,20 +6,20 @@ import org.bukkit.craftbukkit.v1_16_R2.inventory.CraftItemStack; import org.bukkit.inventory.ItemStack; public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { - private final net.minecraft.server.v1_16_R2.ItemStack nmsItem; public NBTItemImpl(net.minecraft.server.v1_16_R2.ItemStack nmsItem) { super(nmsItem != null && nmsItem.hasTag() ? nmsItem.getTag() : new NBTTagCompound()); + this.nmsItem = nmsItem; } public ItemStack finish() { if (nmsItem == null) { return CraftItemStack.asBukkitCopy(net.minecraft.server.v1_16_R2.ItemStack.a(compound)); - } else { - return CraftItemStack.asBukkitCopy(nmsItem); } + + return CraftItemStack.asBukkitCopy(nmsItem); } @Override diff --git a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/nbt/NBTObjectImpl.java b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/nbt/NBTObjectImpl.java index b0a06f1d..aadf122b 100644 --- a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/nbt/NBTObjectImpl.java +++ b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/nbt/NBTObjectImpl.java @@ -7,7 +7,6 @@ import net.minecraft.server.v1_16_R2.NBTTagCompound; import java.util.Set; public class NBTObjectImpl implements NBTObject { - private final NBTTagCompound compound; private final String tag; diff --git a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/world/SItemStackImpl.java b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/world/SItemStackImpl.java index 8203000d..07303faf 100644 --- a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/world/SItemStackImpl.java +++ b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/world/SItemStackImpl.java @@ -11,7 +11,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public class SItemStackImpl implements SItemStack { - private final ItemStack item; public SItemStackImpl(ItemStack item) { @@ -21,15 +20,19 @@ public class SItemStackImpl implements SItemStack { @Override public void breakItem(Player player, int amount) { EntityPlayer entityPlayer = ((CraftPlayer) player).getHandle(); + for (int i = 0; i < amount; ++i) { Vec3D vec3d = new Vec3D(((double) this.random.nextFloat() - 0.5D) * 0.1D, Math.random() * 0.1D + 0.1D, 0.0D); vec3d = vec3d.a(-entityPlayer.pitch * 0.017453292F); vec3d = vec3d.b(-entityPlayer.yaw * 0.017453292F); + double d0 = (double) (-this.random.nextFloat()) * 0.6D - 0.3D; + Vec3D vec3d1 = new Vec3D(((double) this.random.nextFloat() - 0.5D) * 0.3D, d0, 0.6D); vec3d1 = vec3d1.a(-entityPlayer.pitch * 0.017453292F); vec3d1 = vec3d1.b(-entityPlayer.yaw * 0.017453292F); vec3d1 = vec3d1.add(entityPlayer.locX(), entityPlayer.getHeadY(), entityPlayer.locZ()); + entityPlayer.world.addParticle(new ParticleParamItem(Particles.ITEM, CraftItemStack.asNMSCopy(item)), vec3d1.x, vec3d1.y, vec3d1.z, vec3d.x, vec3d.y + 0.05D, vec3d.z); } } diff --git a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/world/SSpawnerImpl.java b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/world/SSpawnerImpl.java index c2444570..7c769ec2 100644 --- a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/world/SSpawnerImpl.java +++ b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/world/SSpawnerImpl.java @@ -25,7 +25,6 @@ import java.util.Random; import java.util.Set; public class SSpawnerImpl implements SSpawner { - private final Location spawnerLocation; public SSpawnerImpl(Location location) { @@ -40,7 +39,6 @@ public class SSpawnerImpl implements SSpawner { @Override public LivingEntity spawnEntity(EntityType type, String particleType, SpawnedEntity spawned, Set canSpawnOn) { - MobSpawnerData data = new MobSpawnerData(); NBTTagCompound compound = data.getEntity(); @@ -58,7 +56,9 @@ public class SSpawnerImpl implements SSpawner { double z = spawnerLocation.getZ() + (random.nextDouble() - random.nextDouble()) * (double) spawnRange + 0.5D; Optional optionalEntity = EntityTypes.a(compound, world); - if (!optionalEntity.isPresent()) continue; + if (!optionalEntity.isPresent()) { + continue; + } Entity entity = optionalEntity.get(); entity.setPosition(x, y, z); @@ -66,28 +66,30 @@ public class SSpawnerImpl implements SSpawner { BlockPosition position = entity.getChunkCoordinates(); DifficultyDamageScaler damageScaler = world.getDamageScaler(position); - if (!(entity instanceof EntityInsentient)) + if (!(entity instanceof EntityInsentient)) { continue; + } EntityInsentient entityInsentient = (EntityInsentient) entity; Location spot = new Location(spawnerLocation.getWorld(), x, y, z); - if (!canSpawn(world, entityInsentient, spot, canSpawnOn)) + if (!canSpawn(world, entityInsentient, spot, canSpawnOn)) { continue; + } - entityInsentient.prepare(world, damageScaler, EnumMobSpawn.SPAWNER, - null, null); + entityInsentient.prepare(world, damageScaler, EnumMobSpawn.SPAWNER, null, null); LivingEntity craftEntity = (LivingEntity) entity.getBukkitEntity(); - if (spawned != null) - if (!spawned.onSpawn(craftEntity)) - return null; + if (spawned != null && !spawned.onSpawn(craftEntity)) { + return null; + } if (particleType != null) { float xx = (float) (0 + (Math.random() * 1)); float yy = (float) (0 + (Math.random() * 2)); float zz = (float) (0 + (Math.random() * 1)); + CompatibleParticleHandler.spawnParticles(CompatibleParticleHandler.ParticleType.getParticle(particleType), spot, 5, xx, yy, zz, 0); } @@ -99,34 +101,38 @@ public class SSpawnerImpl implements SSpawner { return craftEntity; } + return null; } private boolean canSpawn(WorldServer world, EntityInsentient entityInsentient, Location location, Set canSpawnOn) { - - if (!world.getCubes(entityInsentient, entityInsentient.getBoundingBox())) + if (!world.getCubes(entityInsentient, entityInsentient.getBoundingBox())) { return false; + } CompatibleMaterial spawnedIn = CompatibleMaterial.getMaterial(location.getBlock()); CompatibleMaterial spawnedOn = CompatibleMaterial.getMaterial(location.getBlock().getRelative(BlockFace.DOWN)); - if (spawnedIn == null || spawnedOn == null) + if (spawnedIn == null || spawnedOn == null) { return false; + } - if (!spawnedIn.isAir() - && spawnedIn != CompatibleMaterial.WATER - && !spawnedIn.name().contains("PRESSURE") - && !spawnedIn.name().contains("SLAB")) { + if (!spawnedIn.isAir() && + spawnedIn != CompatibleMaterial.WATER && + !spawnedIn.name().contains("PRESSURE") && + !spawnedIn.name().contains("SLAB")) { return false; } for (CompatibleMaterial material : canSpawnOn) { if (material == null) continue; - if (spawnedOn.equals(material) || material.isAir()) + if (spawnedOn.equals(material) || material.isAir()) { return true; + } } + return false; } } diff --git a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/world/SWorldImpl.java b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/world/SWorldImpl.java index defd7dc0..b827e04f 100644 --- a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/world/SWorldImpl.java +++ b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/world/SWorldImpl.java @@ -7,7 +7,6 @@ import java.util.ArrayList; import java.util.List; public class SWorldImpl implements SWorld { - public SWorldImpl() { } diff --git a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/world/WorldCoreImpl.java b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/world/WorldCoreImpl.java index 1c9c474e..bdf815df 100644 --- a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/world/WorldCoreImpl.java +++ b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/world/WorldCoreImpl.java @@ -57,42 +57,44 @@ public class WorldCoreImpl implements WorldCore { public void randomTickChunk(org.bukkit.Chunk bukkitChunk, int tickAmount) { Chunk chunk = ((CraftChunk) bukkitChunk).getHandle(); - if (tickAmount > 0) { - ChunkCoordIntPair chunkcoordintpair = chunk.getPos(); - int j = chunkcoordintpair.d(); - int k = chunkcoordintpair.e(); + if (tickAmount <= 0) { + return; + } - GameProfilerFiller profiler = chunk.world.getMethodProfiler(); + ChunkCoordIntPair chunkcoordintpair = chunk.getPos(); + int j = chunkcoordintpair.d(); + int k = chunkcoordintpair.e(); - profiler.enter("tickBlocks"); - for (ChunkSection chunksection : chunk.getSections()) { - if (chunksection != Chunk.a && chunksection.d()) { - int j1 = chunksection.getYPosition(); + GameProfilerFiller profiler = chunk.world.getMethodProfiler(); - for (int i = 0; i < tickAmount; ++i) { - BlockPosition blockposition2 = chunk.world.a(j, j1, k, 15); - profiler.enter("randomTick"); + profiler.enter("tickBlocks"); + for (ChunkSection chunksection : chunk.getSections()) { + if (chunksection != Chunk.a && chunksection.d()) { + int j1 = chunksection.getYPosition(); - IBlockData iblockdata = chunksection.getType( - blockposition2.getX() - j, - blockposition2.getY() - j1, - blockposition2.getZ() - k); + for (int i = 0; i < tickAmount; ++i) { + BlockPosition blockposition2 = chunk.world.a(j, j1, k, 15); + profiler.enter("randomTick"); - if (iblockdata.isTicking()) { - iblockdata.b(chunk.world, blockposition2, chunk.world.random); - } + IBlockData iblockdata = chunksection.getType( + blockposition2.getX() - j, + blockposition2.getY() - j1, + blockposition2.getZ() - k); - Fluid fluid = iblockdata.getFluid(); - if (fluid.f()) { - fluid.b(chunk.world, blockposition2, chunk.world.random); - } - - profiler.exit(); + if (iblockdata.isTicking()) { + iblockdata.b(chunk.world, blockposition2, chunk.world.random); } + + Fluid fluid = iblockdata.getFluid(); + if (fluid.f()) { + fluid.b(chunk.world, blockposition2, chunk.world.random); + } + + profiler.exit(); } } - - profiler.exit(); } + + profiler.exit(); } } diff --git a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/world/spawner/BBaseSpawnerImpl.java b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/world/spawner/BBaseSpawnerImpl.java index 75e1b9ea..55038a55 100644 --- a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/world/spawner/BBaseSpawnerImpl.java +++ b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/world/spawner/BBaseSpawnerImpl.java @@ -64,113 +64,114 @@ public class BBaseSpawnerImpl implements BBaseSpawner { double spawnerE = (double) ReflectionUtils.getFieldValue(spawner, "e"); ReflectionUtils.setFieldValue(spawner, "f", spawnerE); ReflectionUtils.setFieldValue(spawner, "e", (spawnerE + (double) (1000F / ((float) spawner.spawnDelay + 200F))) % 360D); - } else { - if (spawner.spawnDelay == -1) { - delay(spawner); + return; + } + + if (spawner.spawnDelay == -1) { + delay(spawner); + } + + if (spawner.spawnDelay > 0) { + --spawner.spawnDelay; + return; + } + + boolean flag = false; + int i = 0; + + while (true) { + if (i >= spawner.spawnCount) { + if (flag) { + delay(spawner); + } + + break; } - if (spawner.spawnDelay > 0) { - --spawner.spawnDelay; + NBTTagCompound nbttagcompound = spawner.spawnData.getEntity(); + Optional> optional = EntityTypes.a(nbttagcompound); + if (!optional.isPresent()) { + delay(spawner); return; } - boolean flag = false; - int i = 0; + NBTTagList nbttaglist = nbttagcompound.getList("Pos", 6); + int j = nbttaglist.size(); + double d3 = j >= 1 ? nbttaglist.h(0) : (double) blockposition.getX() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; + double d4 = j >= 2 ? nbttaglist.h(1) : (double) (blockposition.getY() + world.random.nextInt(3) - 1); + double d5 = j >= 3 ? nbttaglist.h(2) : (double) blockposition.getZ() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; + if (world.b(optional.get().a(d3, d4, d5))) { + WorldServer worldserver = (WorldServer) world; + if (EntityPositionTypes.a(optional.get(), worldserver, EnumMobSpawn.SPAWNER, new BlockPosition(d3, d4, d5), world.getRandom())) { + label116: + { + Entity entity = EntityTypes.a(nbttagcompound, world, (entity1) -> { + entity1.setPositionRotation(d3, d4, d5, entity1.yaw, entity1.pitch); + return entity1; + }); + if (entity == null) { + delay(spawner); + return; + } - while (true) { - if (i >= spawner.spawnCount) { - if (flag) { - delay(spawner); - } + int k = world.a(entity.getClass(), (new AxisAlignedBB( + blockposition.getX(), + blockposition.getY(), + blockposition.getZ(), + blockposition.getX() + 1, + blockposition.getY() + 1, + blockposition.getZ() + 1)) + .g(spawner.spawnRange)).size(); - break; - } + if (k >= spawner.maxNearbyEntities) { + delay(spawner); + return; + } - NBTTagCompound nbttagcompound = spawner.spawnData.getEntity(); - Optional> optional = EntityTypes.a(nbttagcompound); - if (!optional.isPresent()) { - delay(spawner); - return; - } + entity.setPositionRotation(entity.locX(), entity.locY(), entity.locZ(), world.random.nextFloat() * 360.0F, 0.0F); + if (entity instanceof EntityInsentient) { + EntityInsentient entityinsentient = (EntityInsentient) entity; + if (!entityinsentient.a(world, EnumMobSpawn.SPAWNER) || !entityinsentient.a(world)) { + break label116; + } - NBTTagList nbttaglist = nbttagcompound.getList("Pos", 6); - int j = nbttaglist.size(); - double d3 = j >= 1 ? nbttaglist.h(0) : (double) blockposition.getX() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; - double d4 = j >= 2 ? nbttaglist.h(1) : (double) (blockposition.getY() + world.random.nextInt(3) - 1); - double d5 = j >= 3 ? nbttaglist.h(2) : (double) blockposition.getZ() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; - if (world.b(optional.get().a(d3, d4, d5))) { - WorldServer worldserver = (WorldServer) world; - if (EntityPositionTypes.a(optional.get(), worldserver, EnumMobSpawn.SPAWNER, new BlockPosition(d3, d4, d5), world.getRandom())) { - label116: - { - Entity entity = EntityTypes.a(nbttagcompound, world, (entity1) -> { - entity1.setPositionRotation(d3, d4, d5, entity1.yaw, entity1.pitch); - return entity1; - }); - if (entity == null) { + if (spawner.spawnData.getEntity().e() == 1 && spawner.spawnData.getEntity().hasKeyOfType("id", 8)) { + ((EntityInsentient) entity).prepare(worldserver, world.getDamageScaler(entity.getChunkCoordinates()), EnumMobSpawn.SPAWNER, null, null); + } + + if (entityinsentient.world.spigotConfig.nerfSpawnerMobs) { + entityinsentient.aware = false; + } + } + + if (CraftEventFactory.callSpawnerSpawnEvent(entity, blockposition).isCancelled()) { + Entity vehicle = entity.getVehicle(); + if (vehicle != null) { + vehicle.dead = true; + } + + Entity passenger; + for (Iterator var20 = entity.getAllPassengers().iterator(); var20.hasNext(); passenger.dead = true) { + passenger = var20.next(); + } + } else { + if (!worldserver.addAllEntitiesSafely(entity, CreatureSpawnEvent.SpawnReason.SPAWNER)) { delay(spawner); return; } - int k = world.a(entity.getClass(), (new AxisAlignedBB( - blockposition.getX(), - blockposition.getY(), - blockposition.getZ(), - blockposition.getX() + 1, - blockposition.getY() + 1, - blockposition.getZ() + 1)) - .g(spawner.spawnRange)).size(); - - if (k >= spawner.maxNearbyEntities) { - delay(spawner); - return; - } - - entity.setPositionRotation(entity.locX(), entity.locY(), entity.locZ(), world.random.nextFloat() * 360.0F, 0.0F); + world.triggerEffect(2004, blockposition, 0); if (entity instanceof EntityInsentient) { - EntityInsentient entityinsentient = (EntityInsentient) entity; - if (!entityinsentient.a(world, EnumMobSpawn.SPAWNER) || !entityinsentient.a(world)) { - break label116; - } - - if (spawner.spawnData.getEntity().e() == 1 && spawner.spawnData.getEntity().hasKeyOfType("id", 8)) { - ((EntityInsentient) entity).prepare(worldserver, world.getDamageScaler(entity.getChunkCoordinates()), EnumMobSpawn.SPAWNER, null, null); - } - - if (entityinsentient.world.spigotConfig.nerfSpawnerMobs) { - entityinsentient.aware = false; - } + ((EntityInsentient) entity).doSpawnEffect(); } - if (CraftEventFactory.callSpawnerSpawnEvent(entity, blockposition).isCancelled()) { - Entity vehicle = entity.getVehicle(); - if (vehicle != null) { - vehicle.dead = true; - } - - Entity passenger; - for (Iterator var20 = entity.getAllPassengers().iterator(); var20.hasNext(); passenger.dead = true) { - passenger = var20.next(); - } - } else { - if (!worldserver.addAllEntitiesSafely(entity, CreatureSpawnEvent.SpawnReason.SPAWNER)) { - delay(spawner); - return; - } - - world.triggerEffect(2004, blockposition, 0); - if (entity instanceof EntityInsentient) { - ((EntityInsentient) entity).doSpawnEffect(); - } - - flag = true; - } + flag = true; } } } - - ++i; } + + ++i; } } diff --git a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/anvil/AnvilCore.java b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/anvil/AnvilCore.java index 0bf4afa2..8ada9f6a 100644 --- a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/anvil/AnvilCore.java +++ b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/anvil/AnvilCore.java @@ -7,7 +7,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; public class AnvilCore implements com.songoda.core.nms.anvil.AnvilCore { - @Override public CustomAnvil createAnvil(Player player) { EntityPlayer p = ((CraftPlayer) player).getHandle(); diff --git a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/anvil/AnvilInventoryCustom.java b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/anvil/AnvilInventoryCustom.java index ba067f2a..e52d9227 100644 --- a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/anvil/AnvilInventoryCustom.java +++ b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/anvil/AnvilInventoryCustom.java @@ -7,11 +7,11 @@ import org.bukkit.craftbukkit.v1_16_R3.inventory.CraftInventoryAnvil; import org.bukkit.inventory.InventoryHolder; public class AnvilInventoryCustom extends CraftInventoryAnvil { - final InventoryHolder holder; public AnvilInventoryCustom(InventoryHolder holder, Location location, IInventory inventory, IInventory resultInventory, ContainerAnvil container) { super(location, inventory, resultInventory, container); + this.holder = holder; } diff --git a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/anvil/AnvilView.java b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/anvil/AnvilView.java index 2334edb7..1d1cf233 100644 --- a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/anvil/AnvilView.java +++ b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/anvil/AnvilView.java @@ -26,7 +26,6 @@ import java.util.logging.Level; import java.util.logging.Logger; public class AnvilView extends ContainerAnvil implements CustomAnvil { - private final EntityPlayer entity; private final Inventory inventory; private String customTitle = "Repairing"; @@ -43,8 +42,10 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { try { mc_ContainerAnvil_repairInventory = ContainerAnvilAbstract.class.getDeclaredField("repairInventory"); mc_ContainerAnvil_repairInventory.setAccessible(true); + mc_ContainerAnvil_resultInventory = ContainerAnvilAbstract.class.getDeclaredField("resultInventory"); mc_ContainerAnvil_resultInventory.setAccessible(true); + mc_ContainerAnvil_bukkitEntity = ContainerAnvil.class.getDeclaredField("bukkitEntity"); mc_ContainerAnvil_bukkitEntity.setAccessible(true); } catch (Exception ex) { @@ -77,14 +78,17 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { public AnvilView(int id, EntityPlayer entity, InventoryHolder holder) { super(id, entity.inventory, ContainerAccess.at(entity.world, new BlockPosition(0, 0, 0))); + this.setTitle(new ChatMessage(customTitle != null ? customTitle : "")); this.checkReachable = false; this.entity = entity; + if (holder != null) { this.inventory = getBukkitView(entity, holder).getTopInventory(); - } else { - this.inventory = getBukkitView().getTopInventory(); + return; } + + this.inventory = getBukkitView().getTopInventory(); } public CraftInventoryView getBukkitView(EntityHuman player, InventoryHolder holder) { @@ -95,10 +99,12 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { (IInventory) mc_ContainerAnvil_resultInventory.get(this), this); CraftInventoryView view = new CraftInventoryView(player.getBukkitEntity(), craftInventory, this); mc_ContainerAnvil_bukkitEntity.set(this, view); + return view; } catch (Exception ex) { Logger.getLogger(AnvilView.class.getName()).log(Level.SEVERE, "Anvil Setup Error", ex); } + return getBukkitView(); } @@ -110,9 +116,11 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void e() { super.e(); + if (cost >= 0) { this.levelCost.set(cost); } + textChange.onChange(); } @@ -144,6 +152,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void setCustomTitle(String title) { this.customTitle = title; + try { mc_Container_title.set(this, new ChatMessage(customTitle != null ? customTitle : "")); } catch (Exception ex) { @@ -160,9 +169,9 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { public int getLevelCost() { if (cost >= 0) { return cost; - } else { - return this.levelCost.get(); } + + return this.levelCost.get(); } @Override @@ -207,7 +216,6 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void open() { - // Counter stuff that the game uses to keep track of inventories int id = entity.nextContainerCounter(); diff --git a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/nbt/NBTCompoundImpl.java b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/nbt/NBTCompoundImpl.java index 75ce518b..d4439d92 100644 --- a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/nbt/NBTCompoundImpl.java +++ b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/nbt/NBTCompoundImpl.java @@ -15,7 +15,6 @@ import java.util.Set; import java.util.UUID; public class NBTCompoundImpl implements NBTCompound { - protected NBTTagCompound compound; protected NBTCompoundImpl(NBTTagCompound compound) { @@ -151,11 +150,11 @@ public class NBTCompoundImpl implements NBTCompound { public NBTCompound getCompound(String tag) { if (has(tag)) { return getNBTObject(tag).asCompound(); - } else { - NBTTagCompound newCompound = new NBTTagCompound(); - compound.set(tag, newCompound); - return new NBTCompoundImpl(newCompound); } + + NBTTagCompound newCompound = new NBTTagCompound(); + compound.set(tag, newCompound); + return new NBTCompoundImpl(newCompound); } @Override @@ -175,15 +174,17 @@ public class NBTCompoundImpl implements NBTCompound { addExtras(); NBTTagCompound compound = this.compound.clone(); - for (String exclusion : exclusions) + for (String exclusion : exclusions) { compound.remove(exclusion); + } NBTCompressedStreamTools.a(compound, (OutputStream) dataOutput); return outputStream.toByteArray(); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } + return null; } @@ -192,8 +193,8 @@ public class NBTCompoundImpl implements NBTCompound { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(serialized); ObjectInputStream dataInput = new ObjectInputStream(inputStream)) { compound = NBTCompressedStreamTools.a((InputStream) dataInput); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } } diff --git a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/nbt/NBTCoreImpl.java b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/nbt/NBTCoreImpl.java index cc9c924b..8961999d 100644 --- a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/nbt/NBTCoreImpl.java +++ b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/nbt/NBTCoreImpl.java @@ -10,7 +10,6 @@ import org.bukkit.entity.Entity; import org.bukkit.inventory.ItemStack; public class NBTCoreImpl implements NBTCore { - @Override public NBTItem of(ItemStack item) { return new NBTItemImpl(CraftItemStack.asNMSCopy(item)); @@ -26,6 +25,7 @@ public class NBTCoreImpl implements NBTCore { net.minecraft.server.v1_16_R3.Entity nmsEntity = ((CraftEntity) entity).getHandle(); NBTTagCompound nbt = new NBTTagCompound(); nmsEntity.save(nbt); + return new NBTEntityImpl(nbt, nmsEntity); } diff --git a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/nbt/NBTEntityImpl.java b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/nbt/NBTEntityImpl.java index c39af315..8d605471 100644 --- a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/nbt/NBTEntityImpl.java +++ b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/nbt/NBTEntityImpl.java @@ -13,11 +13,11 @@ import org.bukkit.craftbukkit.v1_16_R3.CraftWorld; import java.util.Optional; public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { - private Entity nmsEntity; public NBTEntityImpl(NBTTagCompound entityNBT, Entity nmsEntity) { super(entityNBT); + this.nmsEntity = nmsEntity; } @@ -43,15 +43,18 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { org.bukkit.entity.Entity entity = spawned.getBukkitEntity(); entity.teleport(location); nmsEntity = spawned; + return entity; } } + return null; } @Override public org.bukkit.entity.Entity reSpawn(Location location) { nmsEntity.dead = true; + return spawn(location); } diff --git a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/nbt/NBTItemImpl.java b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/nbt/NBTItemImpl.java index 2915d6fa..7f3474e5 100644 --- a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/nbt/NBTItemImpl.java @@ -6,20 +6,20 @@ import org.bukkit.craftbukkit.v1_16_R3.inventory.CraftItemStack; import org.bukkit.inventory.ItemStack; public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { - private final net.minecraft.server.v1_16_R3.ItemStack nmsItem; public NBTItemImpl(net.minecraft.server.v1_16_R3.ItemStack nmsItem) { super(nmsItem != null && nmsItem.hasTag() ? nmsItem.getTag() : new NBTTagCompound()); + this.nmsItem = nmsItem; } public ItemStack finish() { if (nmsItem == null) { return CraftItemStack.asBukkitCopy(net.minecraft.server.v1_16_R3.ItemStack.a(compound)); - } else { - return CraftItemStack.asBukkitCopy(nmsItem); } + + return CraftItemStack.asBukkitCopy(nmsItem); } @Override diff --git a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/nbt/NBTObjectImpl.java b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/nbt/NBTObjectImpl.java index 56af357c..5dcd8982 100644 --- a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/nbt/NBTObjectImpl.java +++ b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/nbt/NBTObjectImpl.java @@ -7,7 +7,6 @@ import net.minecraft.server.v1_16_R3.NBTTagCompound; import java.util.Set; public class NBTObjectImpl implements NBTObject { - private final NBTTagCompound compound; private final String tag; diff --git a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/world/SItemStackImpl.java b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/world/SItemStackImpl.java index 0ce0dfb6..6b217a3f 100644 --- a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/world/SItemStackImpl.java +++ b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/world/SItemStackImpl.java @@ -11,7 +11,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public class SItemStackImpl implements SItemStack { - private final ItemStack item; public SItemStackImpl(ItemStack item) { @@ -21,15 +20,19 @@ public class SItemStackImpl implements SItemStack { @Override public void breakItem(Player player, int amount) { EntityPlayer entityPlayer = ((CraftPlayer) player).getHandle(); + for (int i = 0; i < amount; ++i) { Vec3D vec3d = new Vec3D(((double) this.random.nextFloat() - 0.5D) * 0.1D, Math.random() * 0.1D + 0.1D, 0.0D); vec3d = vec3d.a(-entityPlayer.pitch * 0.017453292F); vec3d = vec3d.b(-entityPlayer.yaw * 0.017453292F); + double d0 = (double) (-this.random.nextFloat()) * 0.6D - 0.3D; + Vec3D vec3d1 = new Vec3D(((double) this.random.nextFloat() - 0.5D) * 0.3D, d0, 0.6D); vec3d1 = vec3d1.a(-entityPlayer.pitch * 0.017453292F); vec3d1 = vec3d1.b(-entityPlayer.yaw * 0.017453292F); vec3d1 = vec3d1.add(entityPlayer.locX(), entityPlayer.getHeadY(), entityPlayer.locZ()); + entityPlayer.world.addParticle(new ParticleParamItem(Particles.ITEM, CraftItemStack.asNMSCopy(item)), vec3d1.x, vec3d1.y, vec3d1.z, vec3d.x, vec3d.y + 0.05D, vec3d.z); } } diff --git a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/world/SSpawnerImpl.java b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/world/SSpawnerImpl.java index 658bb3f7..e7fb6262 100644 --- a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/world/SSpawnerImpl.java +++ b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/world/SSpawnerImpl.java @@ -25,7 +25,6 @@ import java.util.Random; import java.util.Set; public class SSpawnerImpl implements SSpawner { - private final Location spawnerLocation; public SSpawnerImpl(Location location) { @@ -40,7 +39,6 @@ public class SSpawnerImpl implements SSpawner { @Override public LivingEntity spawnEntity(EntityType type, String particleType, SpawnedEntity spawned, Set canSpawnOn) { - MobSpawnerData data = new MobSpawnerData(); NBTTagCompound compound = data.getEntity(); @@ -58,7 +56,9 @@ public class SSpawnerImpl implements SSpawner { double z = spawnerLocation.getZ() + (random.nextDouble() - random.nextDouble()) * (double) spawnRange + 0.5D; Optional optionalEntity = EntityTypes.a(compound, world); - if (!optionalEntity.isPresent()) continue; + if (!optionalEntity.isPresent()) { + continue; + } Entity entity = optionalEntity.get(); entity.setPosition(x, y, z); @@ -66,23 +66,24 @@ public class SSpawnerImpl implements SSpawner { BlockPosition position = entity.getChunkCoordinates(); DifficultyDamageScaler damageScaler = world.getDamageScaler(position); - if (!(entity instanceof EntityInsentient)) + if (!(entity instanceof EntityInsentient)) { continue; + } EntityInsentient entityInsentient = (EntityInsentient) entity; Location spot = new Location(spawnerLocation.getWorld(), x, y, z); - if (!canSpawn(world, entityInsentient, spot, canSpawnOn)) + if (!canSpawn(world, entityInsentient, spot, canSpawnOn)) { continue; + } - entityInsentient.prepare(world, damageScaler, EnumMobSpawn.SPAWNER, - null, null); + entityInsentient.prepare(world, damageScaler, EnumMobSpawn.SPAWNER, null, null); LivingEntity craftEntity = (LivingEntity) entity.getBukkitEntity(); - if (spawned != null) - if (!spawned.onSpawn(craftEntity)) - return null; + if (spawned != null && !spawned.onSpawn(craftEntity)) { + return null; + } if (particleType != null) { float xx = (float) (0 + (Math.random() * 1)); @@ -99,34 +100,38 @@ public class SSpawnerImpl implements SSpawner { return craftEntity; } + return null; } private boolean canSpawn(WorldServer world, EntityInsentient entityInsentient, Location location, Set canSpawnOn) { - - if (!world.getCubes(entityInsentient, entityInsentient.getBoundingBox())) + if (!world.getCubes(entityInsentient, entityInsentient.getBoundingBox())) { return false; + } CompatibleMaterial spawnedIn = CompatibleMaterial.getMaterial(location.getBlock()); CompatibleMaterial spawnedOn = CompatibleMaterial.getMaterial(location.getBlock().getRelative(BlockFace.DOWN)); - if (spawnedIn == null || spawnedOn == null) + if (spawnedIn == null || spawnedOn == null) { return false; + } - if (!spawnedIn.isAir() - && spawnedIn != CompatibleMaterial.WATER - && !spawnedIn.name().contains("PRESSURE") - && !spawnedIn.name().contains("SLAB")) { + if (!spawnedIn.isAir() && + spawnedIn != CompatibleMaterial.WATER && + !spawnedIn.name().contains("PRESSURE") && + !spawnedIn.name().contains("SLAB")) { return false; } for (CompatibleMaterial material : canSpawnOn) { if (material == null) continue; - if (spawnedOn.equals(material) || material.isAir()) + if (spawnedOn.equals(material) || material.isAir()) { return true; + } } + return false; } } diff --git a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/world/SWorldImpl.java b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/world/SWorldImpl.java index 59e6bfb1..0b12fabd 100644 --- a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/world/SWorldImpl.java +++ b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/world/SWorldImpl.java @@ -7,7 +7,6 @@ import java.util.ArrayList; import java.util.List; public class SWorldImpl implements SWorld { - public SWorldImpl() { } diff --git a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/world/WorldCoreImpl.java b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/world/WorldCoreImpl.java index 2fd2fa98..c4b0f5c3 100644 --- a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/world/WorldCoreImpl.java +++ b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/world/WorldCoreImpl.java @@ -57,43 +57,45 @@ public class WorldCoreImpl implements WorldCore { public void randomTickChunk(org.bukkit.Chunk bukkitChunk, int tickAmount) { Chunk chunk = ((CraftChunk) bukkitChunk).getHandle(); - if (tickAmount > 0) { - GameProfilerFiller profiler = chunk.world.getMethodProfiler(); + if (tickAmount <= 0) { + return; + } - ChunkCoordIntPair chunkPos = chunk.getPos(); - int minBlockX = chunkPos.d(); - int minBlockZ = chunkPos.e(); + GameProfilerFiller profiler = chunk.world.getMethodProfiler(); - profiler.enter("tickBlocks"); - for (ChunkSection cSection : chunk.getSections()) { - if (cSection != Chunk.a && // cSection != Chunk.EMPTY_SECTION - cSection.d()) { // #isRandomlyTicking() - int bottomBlockY = cSection.getYPosition(); + ChunkCoordIntPair chunkPos = chunk.getPos(); + int minBlockX = chunkPos.d(); + int minBlockZ = chunkPos.e(); - for (int i = 0; i < tickAmount; ++i) { - BlockPosition randomBlockPos = chunk.world.a(minBlockX, bottomBlockY, minBlockZ, 15); // getBlockRandomPos - profiler.enter("randomTick"); + profiler.enter("tickBlocks"); + for (ChunkSection cSection : chunk.getSections()) { + if (cSection != Chunk.a && // cSection != Chunk.EMPTY_SECTION + cSection.d()) { // #isRandomlyTicking() + int bottomBlockY = cSection.getYPosition(); - IBlockData blockState = cSection.getType( - randomBlockPos.getX() - minBlockX, - randomBlockPos.getY() - bottomBlockY, - randomBlockPos.getZ() - minBlockZ); // #getBlockState + for (int i = 0; i < tickAmount; ++i) { + BlockPosition randomBlockPos = chunk.world.a(minBlockX, bottomBlockY, minBlockZ, 15); // getBlockRandomPos + profiler.enter("randomTick"); - if (blockState.isTicking()) { // #isRandomlyTicking() - blockState.b(chunk.world, randomBlockPos, chunk.world.random); // #randomTick - } + IBlockData blockState = cSection.getType( + randomBlockPos.getX() - minBlockX, + randomBlockPos.getY() - bottomBlockY, + randomBlockPos.getZ() - minBlockZ); // #getBlockState - Fluid fluidState = blockState.getFluid(); // #getFluidState() - if (fluidState.f()) { // #isRandomlyTicking() - fluidState.b(chunk.world, randomBlockPos, chunk.world.random); // #randomTick - } - - profiler.exit(); + if (blockState.isTicking()) { // #isRandomlyTicking() + blockState.b(chunk.world, randomBlockPos, chunk.world.random); // #randomTick } + + Fluid fluidState = blockState.getFluid(); // #getFluidState() + if (fluidState.f()) { // #isRandomlyTicking() + fluidState.b(chunk.world, randomBlockPos, chunk.world.random); // #randomTick + } + + profiler.exit(); } } - - profiler.exit(); } + + profiler.exit(); } } diff --git a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/world/spawner/BBaseSpawnerImpl.java b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/world/spawner/BBaseSpawnerImpl.java index e493bee6..fb27693d 100644 --- a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/world/spawner/BBaseSpawnerImpl.java +++ b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/world/spawner/BBaseSpawnerImpl.java @@ -66,114 +66,115 @@ public class BBaseSpawnerImpl implements BBaseSpawner { double spawnerE = (double) ReflectionUtils.getFieldValue(spawner, "e"); ReflectionUtils.setFieldValue(spawner, "f", spawnerE); ReflectionUtils.setFieldValue(spawner, "e", (spawnerE + (double) (1000F / ((float) spawner.spawnDelay + 200F))) % 360D); - } else { - if (spawner.spawnDelay == -1) { - delay(spawner); + return; + } + + if (spawner.spawnDelay == -1) { + delay(spawner); + } + + if (spawner.spawnDelay > 0) { + --spawner.spawnDelay; + return; + } + + boolean flag = false; + int i = 0; + + while (true) { + if (i >= spawner.spawnCount) { + if (flag) { + delay(spawner); + } + + break; } - if (spawner.spawnDelay > 0) { - --spawner.spawnDelay; + NBTTagCompound nbttagcompound = spawner.spawnData.getEntity(); + Optional> optional = EntityTypes.a(nbttagcompound); + if (!optional.isPresent()) { + delay(spawner); return; } - boolean flag = false; - int i = 0; + NBTTagList nbttaglist = nbttagcompound.getList("Pos", 6); + int j = nbttaglist.size(); + double d3 = j >= 1 ? nbttaglist.h(0) : (double) blockposition.getX() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; + double d4 = j >= 2 ? nbttaglist.h(1) : (double) (blockposition.getY() + world.random.nextInt(3) - 1); + double d5 = j >= 3 ? nbttaglist.h(2) : (double) blockposition.getZ() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; - while (true) { - if (i >= spawner.spawnCount) { - if (flag) { - delay(spawner); - } + if (world.b(optional.get().a(d3, d4, d5))) { + WorldServer worldserver = (WorldServer) world; + if (EntityPositionTypes.a(optional.get(), worldserver, EnumMobSpawn.SPAWNER, new BlockPosition(d3, d4, d5), world.getRandom())) { + label116: + { + Entity entity = EntityTypes.a(nbttagcompound, world, (entity1) -> { + entity1.setPositionRotation(d3, d4, d5, entity1.yaw, entity1.pitch); + return entity1; + }); + if (entity == null) { + delay(spawner); + return; + } - break; - } + int k = world.a(entity.getClass(), (new AxisAlignedBB( + blockposition.getX(), + blockposition.getY(), + blockposition.getZ(), + blockposition.getX() + 1, + blockposition.getY() + 1, + blockposition.getZ() + 1)) + .g(spawner.spawnRange)).size(); - NBTTagCompound nbttagcompound = spawner.spawnData.getEntity(); - Optional> optional = EntityTypes.a(nbttagcompound); - if (!optional.isPresent()) { - delay(spawner); - return; - } + if (k >= spawner.maxNearbyEntities) { + delay(spawner); + return; + } - NBTTagList nbttaglist = nbttagcompound.getList("Pos", 6); - int j = nbttaglist.size(); - double d3 = j >= 1 ? nbttaglist.h(0) : (double) blockposition.getX() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; - double d4 = j >= 2 ? nbttaglist.h(1) : (double) (blockposition.getY() + world.random.nextInt(3) - 1); - double d5 = j >= 3 ? nbttaglist.h(2) : (double) blockposition.getZ() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawner.spawnRange + .5D; + entity.setPositionRotation(entity.locX(), entity.locY(), entity.locZ(), world.random.nextFloat() * 360F, 0F); + if (entity instanceof EntityInsentient) { + EntityInsentient entityinsentient = (EntityInsentient) entity; + if (!entityinsentient.a(world, EnumMobSpawn.SPAWNER) || !entityinsentient.a(world)) { + break label116; + } - if (world.b(optional.get().a(d3, d4, d5))) { - WorldServer worldserver = (WorldServer) world; - if (EntityPositionTypes.a(optional.get(), worldserver, EnumMobSpawn.SPAWNER, new BlockPosition(d3, d4, d5), world.getRandom())) { - label116: - { - Entity entity = EntityTypes.a(nbttagcompound, world, (entity1) -> { - entity1.setPositionRotation(d3, d4, d5, entity1.yaw, entity1.pitch); - return entity1; - }); - if (entity == null) { + if (spawner.spawnData.getEntity().e() == 1 && spawner.spawnData.getEntity().hasKeyOfType("id", 8)) { + ((EntityInsentient) entity).prepare(worldserver, world.getDamageScaler(entity.getChunkCoordinates()), EnumMobSpawn.SPAWNER, null, null); + } + + if (entityinsentient.world.spigotConfig.nerfSpawnerMobs) { + entityinsentient.aware = false; + } + } + + if (CraftEventFactory.callSpawnerSpawnEvent(entity, blockposition).isCancelled()) { + Entity vehicle = entity.getVehicle(); + if (vehicle != null) { + vehicle.dead = true; + } + + Entity passenger; + for (Iterator var20 = entity.getAllPassengers().iterator(); var20.hasNext(); passenger.dead = true) { + passenger = var20.next(); + } + } else { + if (!worldserver.addAllEntitiesSafely(entity, CreatureSpawnEvent.SpawnReason.SPAWNER)) { delay(spawner); return; } - int k = world.a(entity.getClass(), (new AxisAlignedBB( - blockposition.getX(), - blockposition.getY(), - blockposition.getZ(), - blockposition.getX() + 1, - blockposition.getY() + 1, - blockposition.getZ() + 1)) - .g(spawner.spawnRange)).size(); - - if (k >= spawner.maxNearbyEntities) { - delay(spawner); - return; - } - - entity.setPositionRotation(entity.locX(), entity.locY(), entity.locZ(), world.random.nextFloat() * 360F, 0F); + world.triggerEffect(2004, blockposition, 0); if (entity instanceof EntityInsentient) { - EntityInsentient entityinsentient = (EntityInsentient) entity; - if (!entityinsentient.a(world, EnumMobSpawn.SPAWNER) || !entityinsentient.a(world)) { - break label116; - } - - if (spawner.spawnData.getEntity().e() == 1 && spawner.spawnData.getEntity().hasKeyOfType("id", 8)) { - ((EntityInsentient) entity).prepare(worldserver, world.getDamageScaler(entity.getChunkCoordinates()), EnumMobSpawn.SPAWNER, null, null); - } - - if (entityinsentient.world.spigotConfig.nerfSpawnerMobs) { - entityinsentient.aware = false; - } + ((EntityInsentient) entity).doSpawnEffect(); } - if (CraftEventFactory.callSpawnerSpawnEvent(entity, blockposition).isCancelled()) { - Entity vehicle = entity.getVehicle(); - if (vehicle != null) { - vehicle.dead = true; - } - - Entity passenger; - for (Iterator var20 = entity.getAllPassengers().iterator(); var20.hasNext(); passenger.dead = true) { - passenger = var20.next(); - } - } else { - if (!worldserver.addAllEntitiesSafely(entity, CreatureSpawnEvent.SpawnReason.SPAWNER)) { - delay(spawner); - return; - } - - world.triggerEffect(2004, blockposition, 0); - if (entity instanceof EntityInsentient) { - ((EntityInsentient) entity).doSpawnEffect(); - } - - flag = true; - } + flag = true; } } } - - ++i; } + + ++i; } } diff --git a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/anvil/AnvilCore.java b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/anvil/AnvilCore.java index 50c030f7..17323400 100644 --- a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/anvil/AnvilCore.java +++ b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/anvil/AnvilCore.java @@ -7,7 +7,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; public class AnvilCore implements com.songoda.core.nms.anvil.AnvilCore { - @Override public CustomAnvil createAnvil(Player player) { EntityPlayer p = ((CraftPlayer) player).getHandle(); diff --git a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/anvil/AnvilInventoryCustom.java b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/anvil/AnvilInventoryCustom.java index 1ffabde7..f854ae28 100644 --- a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/anvil/AnvilInventoryCustom.java +++ b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/anvil/AnvilInventoryCustom.java @@ -7,11 +7,11 @@ import org.bukkit.craftbukkit.v1_17_R1.inventory.CraftInventoryAnvil; import org.bukkit.inventory.InventoryHolder; public class AnvilInventoryCustom extends CraftInventoryAnvil { - final InventoryHolder holder; public AnvilInventoryCustom(InventoryHolder holder, Location location, IInventory inventory, IInventory resultInventory, ContainerAnvil container) { super(location, inventory, resultInventory, container); + this.holder = holder; } diff --git a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/anvil/AnvilView.java b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/anvil/AnvilView.java index c19e88e9..dc84cd93 100644 --- a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/anvil/AnvilView.java +++ b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/anvil/AnvilView.java @@ -24,7 +24,6 @@ import java.util.logging.Level; import java.util.logging.Logger; public class AnvilView extends ContainerAnvil implements CustomAnvil { - private final EntityPlayer entity; private final Inventory inventory; private String customTitle = "Repairing"; @@ -41,8 +40,10 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { try { mc_ContainerAnvil_repairInventory = ContainerAnvilAbstract.class.getDeclaredField("p"); mc_ContainerAnvil_repairInventory.setAccessible(true); + mc_ContainerAnvil_resultInventory = ContainerAnvilAbstract.class.getDeclaredField("o"); mc_ContainerAnvil_resultInventory.setAccessible(true); + mc_ContainerAnvil_bukkitEntity = ContainerAnvil.class.getDeclaredField("bukkitEntity"); mc_ContainerAnvil_bukkitEntity.setAccessible(true); } catch (Exception ex) { @@ -64,9 +65,11 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { public AnvilView(int id, EntityPlayer entity, InventoryHolder holder) { super(entity.nextContainerCounter(), entity.getInventory(), ContainerAccess.at(entity.getWorld(), new BlockPosition(0, 0, 0))); + this.setTitle(new ChatMessage(customTitle != null ? customTitle : "")); this.checkReachable = false; this.entity = entity; + if (holder != null) { this.inventory = getBukkitView(entity, holder).getTopInventory(); } else { @@ -82,10 +85,12 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { (IInventory) mc_ContainerAnvil_resultInventory.get(this), this); CraftInventoryView view = new CraftInventoryView(player.getBukkitEntity(), craftInventory, this); mc_ContainerAnvil_bukkitEntity.set(this, view); + return view; } catch (Exception ex) { Logger.getLogger(AnvilView.class.getName()).log(Level.SEVERE, "Anvil Setup Error", ex); } + return getBukkitView(); } @@ -97,9 +102,11 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void e() { super.e(); + if (cost >= 0) { this.setLevelCost(cost); } + textChange.onChange(); } @@ -131,6 +138,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void setCustomTitle(String title) { this.customTitle = title; + try { mc_Container_title.set(this, new ChatMessage(customTitle != null ? customTitle : "")); } catch (Exception ex) { @@ -147,9 +155,9 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { public int getLevelCost() { if (cost >= 0) { return cost; - } else { - return this.getLevelCost(); } + + return this.getLevelCost(); } @Override diff --git a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/nbt/NBTCompoundImpl.java b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/nbt/NBTCompoundImpl.java index 4a45a267..8fa5647c 100644 --- a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/nbt/NBTCompoundImpl.java +++ b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/nbt/NBTCompoundImpl.java @@ -15,7 +15,6 @@ import java.util.Set; import java.util.UUID; public class NBTCompoundImpl implements NBTCompound { - protected NBTTagCompound compound; protected NBTCompoundImpl(NBTTagCompound compound) { @@ -151,11 +150,11 @@ public class NBTCompoundImpl implements NBTCompound { public NBTCompound getCompound(String tag) { if (has(tag)) { return getNBTObject(tag).asCompound(); - } else { - NBTTagCompound newCompound = new NBTTagCompound(); - compound.set(tag, newCompound); - return new NBTCompoundImpl(newCompound); } + + NBTTagCompound newCompound = new NBTTagCompound(); + compound.set(tag, newCompound); + return new NBTCompoundImpl(newCompound); } @Override @@ -175,15 +174,17 @@ public class NBTCompoundImpl implements NBTCompound { addExtras(); NBTTagCompound compound = this.compound.clone(); - for (String exclusion : exclusions) + for (String exclusion : exclusions) { compound.remove(exclusion); + } NBTCompressedStreamTools.a(compound, (OutputStream) dataOutput); return outputStream.toByteArray(); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } + return null; } @@ -192,8 +193,8 @@ public class NBTCompoundImpl implements NBTCompound { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(serialized); ObjectInputStream dataInput = new ObjectInputStream(inputStream)) { compound = NBTCompressedStreamTools.a((InputStream) dataInput); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } } diff --git a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/nbt/NBTCoreImpl.java b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/nbt/NBTCoreImpl.java index 4ea5c8b0..d10727d2 100644 --- a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/nbt/NBTCoreImpl.java +++ b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/nbt/NBTCoreImpl.java @@ -10,7 +10,6 @@ import org.bukkit.entity.Entity; import org.bukkit.inventory.ItemStack; public class NBTCoreImpl implements NBTCore { - @Override public NBTItem of(ItemStack item) { return new NBTItemImpl(CraftItemStack.asNMSCopy(item)); @@ -26,6 +25,7 @@ public class NBTCoreImpl implements NBTCore { net.minecraft.world.entity.Entity nmsEntity = ((CraftEntity) entity).getHandle(); NBTTagCompound nbt = new NBTTagCompound(); nmsEntity.save(nbt); + return new NBTEntityImpl(nbt, nmsEntity); } diff --git a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/nbt/NBTEntityImpl.java b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/nbt/NBTEntityImpl.java index 35e7f572..05a22b79 100644 --- a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/nbt/NBTEntityImpl.java +++ b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/nbt/NBTEntityImpl.java @@ -13,11 +13,11 @@ import org.bukkit.craftbukkit.v1_17_R1.CraftWorld; import java.util.Optional; public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { - private Entity nmsEntity; public NBTEntityImpl(NBTTagCompound entityNBT, Entity nmsEntity) { super(entityNBT); + this.nmsEntity = nmsEntity; } @@ -43,9 +43,11 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { org.bukkit.entity.Entity entity = spawned.getBukkitEntity(); entity.teleport(location); nmsEntity = spawned; + return entity; } } + return null; } diff --git a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/nbt/NBTItemImpl.java b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/nbt/NBTItemImpl.java index d0a5dd29..31cd554a 100644 --- a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/nbt/NBTItemImpl.java @@ -6,20 +6,20 @@ import org.bukkit.craftbukkit.v1_17_R1.inventory.CraftItemStack; import org.bukkit.inventory.ItemStack; public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { - private final net.minecraft.world.item.ItemStack nmsItem; public NBTItemImpl(net.minecraft.world.item.ItemStack nmsItem) { super(nmsItem != null && nmsItem.hasTag() ? nmsItem.getTag() : new NBTTagCompound()); + this.nmsItem = nmsItem; } public ItemStack finish() { if (nmsItem == null) { return CraftItemStack.asBukkitCopy(net.minecraft.world.item.ItemStack.a(compound)); - } else { - return CraftItemStack.asBukkitCopy(nmsItem); } + + return CraftItemStack.asBukkitCopy(nmsItem); } @Override diff --git a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/nbt/NBTObjectImpl.java b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/nbt/NBTObjectImpl.java index 7acacce0..3484b693 100644 --- a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/nbt/NBTObjectImpl.java +++ b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/nbt/NBTObjectImpl.java @@ -7,7 +7,6 @@ import net.minecraft.nbt.NBTTagCompound; import java.util.Set; public class NBTObjectImpl implements NBTObject { - private final NBTTagCompound compound; private final String tag; diff --git a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/SItemStackImpl.java b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/SItemStackImpl.java index 000fdd43..5c3b989c 100644 --- a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/SItemStackImpl.java +++ b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/SItemStackImpl.java @@ -11,7 +11,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public class SItemStackImpl implements SItemStack { - private final ItemStack item; public SItemStackImpl(ItemStack item) { @@ -21,15 +20,19 @@ public class SItemStackImpl implements SItemStack { @Override public void breakItem(Player player, int amount) { EntityPlayer entityPlayer = ((CraftPlayer) player).getHandle(); + for (int i = 0; i < amount; ++i) { Vec3D vec3d = new Vec3D(((double) random.nextFloat() - 0.5D) * 0.1D, Math.random() * 0.1D + 0.1D, 0.0D); vec3d = vec3d.a(-entityPlayer.getXRot() * 0.017453292F); vec3d = vec3d.b(-entityPlayer.getYRot() * 0.017453292F); + double d0 = (double) (-random.nextFloat()) * 0.6D - 0.3D; + Vec3D vec3d1 = new Vec3D(((double) random.nextFloat() - 0.5D) * 0.3D, d0, 0.6D); vec3d1 = vec3d1.a(-entityPlayer.getXRot() * 0.017453292F); vec3d1 = vec3d1.b(-entityPlayer.getYRot() * 0.017453292F); vec3d1 = vec3d1.add(entityPlayer.locX(), entityPlayer.getHeadY(), entityPlayer.locZ()); + entityPlayer.t.addParticle(new ParticleParamItem(Particles.K, CraftItemStack.asNMSCopy(item)), vec3d1.b, vec3d1.c, vec3d1.d, vec3d.b, vec3d.c + 0.05D, vec3d.d); } } diff --git a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/SSpawnerImpl.java b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/SSpawnerImpl.java index 27b499c7..3d1b5795 100644 --- a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/SSpawnerImpl.java +++ b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/SSpawnerImpl.java @@ -25,7 +25,6 @@ import java.util.Random; import java.util.Set; public class SSpawnerImpl implements SSpawner { - private final Location spawnerLocation; public SSpawnerImpl(Location location) { @@ -40,7 +39,6 @@ public class SSpawnerImpl implements SSpawner { @Override public LivingEntity spawnEntity(EntityType type, String particleType, SpawnedEntity spawned, Set canSpawnOn) { - MobSpawnerData data = new MobSpawnerData(); NBTTagCompound compound = data.getEntity(); @@ -66,28 +64,30 @@ public class SSpawnerImpl implements SSpawner { BlockPosition position = entity.getChunkCoordinates(); DifficultyDamageScaler damageScaler = world.getDamageScaler(position); - if (!(entity instanceof EntityInsentient)) + if (!(entity instanceof EntityInsentient)) { continue; + } EntityInsentient entityInsentient = (EntityInsentient) entity; - Location spot = new Location(spawnerLocation.getWorld(), x, y, z); - if (!canSpawn(world, entityInsentient, spot, canSpawnOn)) - continue; - entityInsentient.prepare(world, damageScaler, EnumMobSpawn.c, - null, null); + if (!canSpawn(world, entityInsentient, spot, canSpawnOn)) { + continue; + } + + entityInsentient.prepare(world, damageScaler, EnumMobSpawn.c, null, null); LivingEntity craftEntity = (LivingEntity) entity.getBukkitEntity(); - if (spawned != null) - if (!spawned.onSpawn(craftEntity)) - return null; + if (spawned != null && !spawned.onSpawn(craftEntity)) { + return null; + } if (particleType != null) { float xx = (float) (0 + (Math.random() * 1)); float yy = (float) (0 + (Math.random() * 2)); float zz = (float) (0 + (Math.random() * 1)); + CompatibleParticleHandler.spawnParticles(CompatibleParticleHandler.ParticleType.getParticle(particleType), spot, 5, xx, yy, zz, 0); } @@ -99,34 +99,38 @@ public class SSpawnerImpl implements SSpawner { return craftEntity; } + return null; } private boolean canSpawn(WorldServer world, EntityInsentient entityInsentient, Location location, Set canSpawnOn) { - - if (!world.getCubes(entityInsentient, entityInsentient.getBoundingBox())) + if (!world.getCubes(entityInsentient, entityInsentient.getBoundingBox())) { return false; + } CompatibleMaterial spawnedIn = CompatibleMaterial.getMaterial(location.getBlock()); CompatibleMaterial spawnedOn = CompatibleMaterial.getMaterial(location.getBlock().getRelative(BlockFace.DOWN)); - if (spawnedIn == null || spawnedOn == null) + if (spawnedIn == null || spawnedOn == null) { return false; + } - if (!spawnedIn.isAir() - && spawnedIn != CompatibleMaterial.WATER - && !spawnedIn.name().contains("PRESSURE") - && !spawnedIn.name().contains("SLAB")) { + if (!spawnedIn.isAir() && + spawnedIn != CompatibleMaterial.WATER && + !spawnedIn.name().contains("PRESSURE") && + !spawnedIn.name().contains("SLAB")) { return false; } for (CompatibleMaterial material : canSpawnOn) { if (material == null) continue; - if (spawnedOn.equals(material) || material.isAir()) + if (spawnedOn.equals(material) || material.isAir()) { return true; + } } + return false; } } diff --git a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/SWorldImpl.java b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/SWorldImpl.java index 39e75ebe..673be2ed 100644 --- a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/SWorldImpl.java +++ b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/SWorldImpl.java @@ -14,7 +14,6 @@ import java.util.ArrayList; import java.util.List; public class SWorldImpl implements SWorld { - private final World world; private static Field fieldG; @@ -22,9 +21,10 @@ public class SWorldImpl implements SWorld { static { try { fieldG = WorldServer.class.getDeclaredField("G"); - } catch (NoSuchFieldException e) { - e.printStackTrace(); + } catch (NoSuchFieldException ex) { + ex.printStackTrace(); } + fieldG.setAccessible(true); } @@ -47,9 +47,10 @@ public class SWorldImpl implements SWorld { list.add((LivingEntity) bukkitEntity); } }); - } catch (IllegalAccessException e) { - e.printStackTrace(); + } catch (IllegalAccessException ex) { + ex.printStackTrace(); } + return list; } } diff --git a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/WorldCoreImpl.java b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/WorldCoreImpl.java index 3b4ba2f3..7f800f18 100644 --- a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/WorldCoreImpl.java +++ b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/WorldCoreImpl.java @@ -23,7 +23,6 @@ import org.bukkit.craftbukkit.v1_17_R1.CraftChunk; import org.bukkit.inventory.ItemStack; public class WorldCoreImpl implements WorldCore { - @Override public SSpawner getSpawner(CreatureSpawner spawner) { return new SSpawnerImpl(spawner.getLocation()); @@ -59,40 +58,42 @@ public class WorldCoreImpl implements WorldCore { Chunk chunk = ((CraftChunk) bukkitChunk).getHandle(); WorldServer world = (WorldServer) chunk.getWorld(); - if (tickAmount > 0) { - GameProfilerFiller profiler = world.getMethodProfiler(); + if (tickAmount <= 0) { + return; + } - ChunkCoordIntPair chunkPos = chunk.getPos(); - int minBlockX = chunkPos.d(); - int minBlockZ = chunkPos.e(); + GameProfilerFiller profiler = world.getMethodProfiler(); - profiler.enter("tickBlocks"); - for (ChunkSection cSection : chunk.getSections()) { - if (cSection != Chunk.a && // cSection != Chunk.EMPTY_SECTION - cSection.d()) { // #isRandomlyTicking - int bottomBlockY = cSection.getYPosition(); + ChunkCoordIntPair chunkPos = chunk.getPos(); + int minBlockX = chunkPos.d(); + int minBlockZ = chunkPos.e(); - for (int k1 = 0; k1 < tickAmount; ++k1) { - BlockPosition bPos = world.a(minBlockX, bottomBlockY, minBlockZ, 15); - profiler.enter("randomTick"); + profiler.enter("tickBlocks"); + for (ChunkSection cSection : chunk.getSections()) { + if (cSection != Chunk.a && // cSection != Chunk.EMPTY_SECTION + cSection.d()) { // #isRandomlyTicking + int bottomBlockY = cSection.getYPosition(); - IBlockData blockState = cSection.getType(bPos.getX() - minBlockX, bPos.getY() - bottomBlockY, bPos.getZ() - minBlockZ); + for (int k1 = 0; k1 < tickAmount; ++k1) { + BlockPosition bPos = world.a(minBlockX, bottomBlockY, minBlockZ, 15); + profiler.enter("randomTick"); - if (blockState.isTicking()) { - blockState.b(world, bPos, chunk.getWorld().w); // #randomTick - } + IBlockData blockState = cSection.getType(bPos.getX() - minBlockX, bPos.getY() - bottomBlockY, bPos.getZ() - minBlockZ); - Fluid fluid = blockState.getFluid(); - if (fluid.f()) { // #isRandomlyTicking - fluid.b(world, bPos, chunk.getWorld().w); // #randomTick - } - - profiler.exit(); + if (blockState.isTicking()) { + blockState.b(world, bPos, chunk.getWorld().w); // #randomTick } + + Fluid fluid = blockState.getFluid(); + if (fluid.f()) { // #isRandomlyTicking + fluid.b(world, bPos, chunk.getWorld().w); // #randomTick + } + + profiler.exit(); } } - - profiler.exit(); } + + profiler.exit(); } } diff --git a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/spawner/BBaseSpawnerImpl.java b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/spawner/BBaseSpawnerImpl.java index 4a06dc0a..809972b2 100644 --- a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/spawner/BBaseSpawnerImpl.java +++ b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/spawner/BBaseSpawnerImpl.java @@ -58,90 +58,93 @@ public class BBaseSpawnerImpl implements BBaseSpawner { if (this.spawner.d > 0) { --this.spawner.d; - } else { - boolean flag = false; - int i = 0; + return; + } - while (true) { - if (i >= this.spawner.k) { - if (flag) { - this.delay(world, bPos); - } - break; - } + boolean flag = false; + int i = 0; - NBTTagCompound nbttagcompound = this.spawner.f.getEntity(); - Optional> optional = EntityTypes.a(nbttagcompound); - if (optional.isEmpty()) { + while (true) { + if (i >= this.spawner.k) { + if (flag) { this.delay(world, bPos); - return; } - NBTTagList nbttaglist = nbttagcompound.getList("Pos", 6); - int j = nbttaglist.size(); - double d0 = j >= 1 ? nbttaglist.h(0) : (double) bPos.getX() + (world.w.nextDouble() - world.w.nextDouble()) * (double) this.spawner.o + 0.5D; - double d1 = j >= 2 ? nbttaglist.h(1) : (double) (bPos.getY() + world.w.nextInt(3) - 1); - double d2 = j >= 3 ? nbttaglist.h(2) : (double) bPos.getZ() + (world.w.nextDouble() - world.w.nextDouble()) * (double) this.spawner.o + 0.5D; - if (world.b(optional.get().a(d0, d1, d2)) && EntityPositionTypes.a((EntityTypes) optional.get(), world, EnumMobSpawn.c, new BlockPosition(d0, d1, d2), world.getRandom())) { - label107: - { - Entity entity = EntityTypes.a(nbttagcompound, world, (entity1) -> { - entity1.setPositionRotation(d0, d1, d2, entity1.getYRot(), entity1.getXRot()); - return entity1; - }); - if (entity == null) { - this.delay(world, bPos); - return; + break; + } + + NBTTagCompound nbttagcompound = this.spawner.f.getEntity(); + Optional> optional = EntityTypes.a(nbttagcompound); + if (optional.isEmpty()) { + this.delay(world, bPos); + return; + } + + NBTTagList nbttaglist = nbttagcompound.getList("Pos", 6); + int j = nbttaglist.size(); + double d0 = j >= 1 ? nbttaglist.h(0) : (double) bPos.getX() + (world.w.nextDouble() - world.w.nextDouble()) * (double) this.spawner.o + 0.5D; + double d1 = j >= 2 ? nbttaglist.h(1) : (double) (bPos.getY() + world.w.nextInt(3) - 1); + double d2 = j >= 3 ? nbttaglist.h(2) : (double) bPos.getZ() + (world.w.nextDouble() - world.w.nextDouble()) * (double) this.spawner.o + 0.5D; + if (world.b(optional.get().a(d0, d1, d2)) && + EntityPositionTypes.a((EntityTypes) optional.get(), world, EnumMobSpawn.c, new BlockPosition(d0, d1, d2), world.getRandom())) { + label107: + { + Entity entity = EntityTypes.a(nbttagcompound, world, (entity1) -> { + entity1.setPositionRotation(d0, d1, d2, entity1.getYRot(), entity1.getXRot()); + return entity1; + }); + if (entity == null) { + this.delay(world, bPos); + return; + } + + int k = world.a(entity.getClass(), (new AxisAlignedBB(bPos.getX(), bPos.getY(), bPos.getZ(), bPos.getX() + 1, bPos.getY() + 1, bPos.getZ() + 1)).g(this.spawner.o)).size(); + if (k >= this.spawner.m) { + this.delay(world, bPos); + return; + } + + entity.setPositionRotation(entity.locX(), entity.locY(), entity.locZ(), world.w.nextFloat() * 360.0F, 0.0F); + if (entity instanceof EntityInsentient entityinsentient) { + if (!entityinsentient.a(world, EnumMobSpawn.c) || !entityinsentient.a(world)) { + break label107; } - int k = world.a(entity.getClass(), (new AxisAlignedBB(bPos.getX(), bPos.getY(), bPos.getZ(), bPos.getX() + 1, bPos.getY() + 1, bPos.getZ() + 1)).g(this.spawner.o)).size(); - if (k >= this.spawner.m) { - this.delay(world, bPos); - return; + if (this.spawner.f.getEntity().e() == 1 && this.spawner.f.getEntity().hasKeyOfType("id", 8)) { + ((EntityInsentient) entity).prepare(world, world.getDamageScaler(entity.getChunkCoordinates()), EnumMobSpawn.c, null, null); } - entity.setPositionRotation(entity.locX(), entity.locY(), entity.locZ(), world.w.nextFloat() * 360.0F, 0.0F); - if (entity instanceof EntityInsentient entityinsentient) { - if (!entityinsentient.a(world, EnumMobSpawn.c) || !entityinsentient.a(world)) { - break label107; - } - - if (this.spawner.f.getEntity().e() == 1 && this.spawner.f.getEntity().hasKeyOfType("id", 8)) { - ((EntityInsentient) entity).prepare(world, world.getDamageScaler(entity.getChunkCoordinates()), EnumMobSpawn.c, null, null); - } - - if (entityinsentient.t.spigotConfig.nerfSpawnerMobs) { - entityinsentient.aware = false; - } - } - - if (CraftEventFactory.callSpawnerSpawnEvent(entity, bPos).isCancelled()) { - Entity vehicle = entity.getVehicle(); - if (vehicle != null) { - vehicle.die(); - } - - for (Entity passenger : entity.getAllPassengers()) { - passenger.die(); - } - } else { - if (!world.addAllEntitiesSafely(entity, CreatureSpawnEvent.SpawnReason.SPAWNER)) { - this.delay(world, bPos); - return; - } - - world.triggerEffect(2004, bPos, 0); - if (entity instanceof EntityInsentient) { - ((EntityInsentient) entity).doSpawnEffect(); - } - - flag = true; + if (entityinsentient.t.spigotConfig.nerfSpawnerMobs) { + entityinsentient.aware = false; } } - } - ++i; + if (CraftEventFactory.callSpawnerSpawnEvent(entity, bPos).isCancelled()) { + Entity vehicle = entity.getVehicle(); + if (vehicle != null) { + vehicle.die(); + } + + for (Entity passenger : entity.getAllPassengers()) { + passenger.die(); + } + } else { + if (!world.addAllEntitiesSafely(entity, CreatureSpawnEvent.SpawnReason.SPAWNER)) { + this.delay(world, bPos); + return; + } + + world.triggerEffect(2004, bPos, 0); + if (entity instanceof EntityInsentient) { + ((EntityInsentient) entity).doSpawnEffect(); + } + + flag = true; + } + } } + + ++i; } } diff --git a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/anvil/AnvilCore.java b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/anvil/AnvilCore.java index 22dae5e5..17122494 100644 --- a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/anvil/AnvilCore.java +++ b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/anvil/AnvilCore.java @@ -6,7 +6,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; public class AnvilCore implements com.songoda.core.nms.anvil.AnvilCore { - @Override public CustomAnvil createAnvil(Player player) { return new AnvilView(((CraftPlayer) player).getHandle(), null); diff --git a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/anvil/AnvilInventoryCustom.java b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/anvil/AnvilInventoryCustom.java index 7a15c047..e8a8ce80 100644 --- a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/anvil/AnvilInventoryCustom.java +++ b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/anvil/AnvilInventoryCustom.java @@ -5,11 +5,11 @@ import org.bukkit.craftbukkit.v1_8_R1.inventory.CraftInventoryAnvil; import org.bukkit.inventory.InventoryHolder; public class AnvilInventoryCustom extends CraftInventoryAnvil { - final InventoryHolder holder; public AnvilInventoryCustom(InventoryHolder holder, IInventory inventory, IInventory resultInventory) { super(inventory, resultInventory); + this.holder = holder; } diff --git a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/anvil/AnvilView.java b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/anvil/AnvilView.java index 51609c93..de14f8fa 100644 --- a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/anvil/AnvilView.java +++ b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/anvil/AnvilView.java @@ -19,7 +19,6 @@ import java.util.logging.Level; import java.util.logging.Logger; public class AnvilView extends ContainerAnvil implements CustomAnvil { - private final EntityPlayer entity; private final Inventory inventory; private String title = "Repairing"; @@ -36,8 +35,10 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { try { mc_ContainerAnvil_repairInventory = ContainerAnvil.class.getDeclaredField("h"); mc_ContainerAnvil_repairInventory.setAccessible(true); + mc_ContainerAnvil_resultInventory = ContainerAnvil.class.getDeclaredField("g"); mc_ContainerAnvil_resultInventory.setAccessible(true); + mc_ContainerAnvil_bukkitEntity = ContainerAnvil.class.getDeclaredField("bukkitEntity"); mc_ContainerAnvil_bukkitEntity.setAccessible(true); } catch (Exception ex) { @@ -60,11 +61,13 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { public AnvilView(EntityPlayer entity, InventoryHolder holder) { super(entity.inventory, entity.world, new BlockPosition(0, 0, 0), entity); this.entity = entity; + if (holder != null) { this.inventory = getBukkitView(entity, holder).getTopInventory(); - } else { - this.inventory = getBukkitView().getTopInventory(); + return; } + + this.inventory = getBukkitView().getTopInventory(); } public CraftInventoryView getBukkitView(EntityHuman player, InventoryHolder holder) { @@ -74,10 +77,12 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { (IInventory) mc_ContainerAnvil_resultInventory.get(this)); CraftInventoryView view = new CraftInventoryView(player.getBukkitEntity(), craftInventory, this); mc_ContainerAnvil_bukkitEntity.set(this, view); + return view; } catch (Exception ex) { Logger.getLogger(AnvilView.class.getName()).log(Level.SEVERE, "Anvil Setup Error", ex); } + return getBukkitView(); } @@ -89,6 +94,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void e() { super.e(); + if (cost >= 0) { this.a = cost; } @@ -107,6 +113,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { } catch (Exception ex) { Logger.getLogger(AnvilView.class.getName()).log(Level.SEVERE, "Anvil Error", ex); } + return null; } @@ -182,7 +189,6 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void open() { - // Counter stuff that the game uses to keep track of inventories int id = entity.nextContainerCounter(); diff --git a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/nbt/NBTCompoundImpl.java b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/nbt/NBTCompoundImpl.java index ba94a666..21fdcf63 100644 --- a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/nbt/NBTCompoundImpl.java +++ b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/nbt/NBTCompoundImpl.java @@ -15,7 +15,6 @@ import java.util.Set; import java.util.UUID; public class NBTCompoundImpl implements NBTCompound { - protected NBTTagCompound compound; protected NBTCompoundImpl(NBTTagCompound compound) { @@ -84,6 +83,7 @@ public class NBTCompoundImpl implements NBTCompound { public NBTCompound set(String tag, UUID u) { set(tag + "Most", u.getMostSignificantBits()); set(tag + "Least", u.getLeastSignificantBits()); + return this; } @@ -152,11 +152,11 @@ public class NBTCompoundImpl implements NBTCompound { public NBTCompound getCompound(String tag) { if (has(tag)) { return getNBTObject(tag).asCompound(); - } else { - NBTTagCompound newCompound = new NBTTagCompound(); - compound.set(tag, newCompound); - return new NBTCompoundImpl(newCompound); } + + NBTTagCompound newCompound = new NBTTagCompound(); + compound.set(tag, newCompound); + return new NBTCompoundImpl(newCompound); } @Override @@ -176,15 +176,17 @@ public class NBTCompoundImpl implements NBTCompound { addExtras(); NBTTagCompound compound = (NBTTagCompound) this.compound.clone(); // Changed in 1.12 // Changed in 1.9.4 - for (String exclusion : exclusions) + for (String exclusion : exclusions) { compound.remove(exclusion); + } NBTCompressedStreamTools.a(compound, (OutputStream) dataOutput); return outputStream.toByteArray(); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } + return null; } @@ -193,8 +195,8 @@ public class NBTCompoundImpl implements NBTCompound { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(serialized); ObjectInputStream dataInput = new ObjectInputStream(inputStream)) { compound = NBTCompressedStreamTools.a((InputStream) dataInput); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } } diff --git a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/nbt/NBTCoreImpl.java b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/nbt/NBTCoreImpl.java index d6a8c58d..d13f7785 100644 --- a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/nbt/NBTCoreImpl.java +++ b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/nbt/NBTCoreImpl.java @@ -10,7 +10,6 @@ import org.bukkit.entity.Entity; import org.bukkit.inventory.ItemStack; public class NBTCoreImpl implements NBTCore { - @Override public NBTItem of(ItemStack item) { return new NBTItemImpl(CraftItemStack.asNMSCopy(item)); @@ -26,6 +25,7 @@ public class NBTCoreImpl implements NBTCore { net.minecraft.server.v1_8_R1.Entity nmsEntity = ((CraftEntity) entity).getHandle(); NBTTagCompound nbt = new NBTTagCompound(); nmsEntity.e(nbt); // Method name changed in 1.11 + return new NBTEntityImpl(nbt, nmsEntity); } diff --git a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/nbt/NBTEntityImpl.java b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/nbt/NBTEntityImpl.java index af58e3ea..d793ef3e 100644 --- a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/nbt/NBTEntityImpl.java +++ b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/nbt/NBTEntityImpl.java @@ -13,13 +13,13 @@ import java.lang.reflect.Field; import java.util.Map; public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { - private static Field fieldG; private Entity nmsEntity; public NBTEntityImpl(NBTTagCompound entityNBT, Entity nmsEntity) { super(entityNBT); + this.nmsEntity = nmsEntity; } @@ -27,8 +27,8 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { try { fieldG = EntityTypes.class.getDeclaredField("g"); fieldG.setAccessible(true); - } catch (NoSuchFieldException e) { - e.printStackTrace(); + } catch (NoSuchFieldException ex) { + ex.printStackTrace(); } } @@ -50,11 +50,13 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { spawned.setLocation(location.getX(), location.getY(), location.getZ(), location.getPitch(), location.getYaw()); nmsEntity = spawned; + return entity; } - } catch (IllegalAccessException e) { - e.printStackTrace(); + } catch (IllegalAccessException ex) { + ex.printStackTrace(); } + return null; } @@ -67,7 +69,9 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { @Override public void addExtras() { String key = EntityTypes.b(nmsEntity); // Changed in 1.12 - if (key != null) + + if (key != null) { compound.setString("entity_type", key); // Changed in 1.13 + } } } diff --git a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/nbt/NBTItemImpl.java b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/nbt/NBTItemImpl.java index 4df19aa6..6cba3c6d 100644 --- a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/nbt/NBTItemImpl.java @@ -6,20 +6,20 @@ import org.bukkit.craftbukkit.v1_8_R1.inventory.CraftItemStack; import org.bukkit.inventory.ItemStack; public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { - private final net.minecraft.server.v1_8_R1.ItemStack nmsItem; public NBTItemImpl(net.minecraft.server.v1_8_R1.ItemStack nmsItem) { super(nmsItem != null && nmsItem.hasTag() ? nmsItem.getTag() : new NBTTagCompound()); + this.nmsItem = nmsItem; } public ItemStack finish() { if (nmsItem == null) { return CraftItemStack.asBukkitCopy(net.minecraft.server.v1_8_R1.ItemStack.createStack(compound)); - } else { - return CraftItemStack.asBukkitCopy(nmsItem); } + + return CraftItemStack.asBukkitCopy(nmsItem); } @Override diff --git a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/nbt/NBTObjectImpl.java b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/nbt/NBTObjectImpl.java index 235cb615..e7fb7f62 100644 --- a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/nbt/NBTObjectImpl.java +++ b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/nbt/NBTObjectImpl.java @@ -7,7 +7,6 @@ import net.minecraft.server.v1_8_R1.NBTTagCompound; import java.util.Set; public class NBTObjectImpl implements NBTObject { - private final NBTTagCompound compound; private final String tag; diff --git a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/world/SItemStackImpl.java b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/world/SItemStackImpl.java index cd3b8640..0e460077 100644 --- a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/world/SItemStackImpl.java +++ b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/world/SItemStackImpl.java @@ -11,7 +11,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public class SItemStackImpl implements SItemStack { - private final ItemStack item; public SItemStackImpl(ItemStack item) { @@ -21,11 +20,14 @@ public class SItemStackImpl implements SItemStack { @Override public void breakItem(Player player, int amount) { EntityPlayer entityPlayer = ((CraftPlayer) player).getHandle(); + for (int i = 0; i < 5; ++i) { Vec3D vec3d = new Vec3D(((double) random.nextFloat() - 0.5D) * 0.1D, Math.random() * 0.1D + 0.1D, 0.0D); vec3d = vec3d.a(-entityPlayer.pitch * 0.017453292F); vec3d = vec3d.b(-entityPlayer.yaw * 0.017453292F); + double d0 = (double) (-random.nextFloat()) * 0.6D - 0.3D; + Vec3D vec3d1 = new Vec3D(((double) random.nextFloat() - 0.5D) * 0.3D, d0, 0.6D); vec3d1 = vec3d1.a(-entityPlayer.pitch * 0.017453292F); vec3d1 = vec3d1.b(-entityPlayer.yaw * 0.017453292F); diff --git a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/world/SSpawnerImpl.java b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/world/SSpawnerImpl.java index 1ac40f2c..aeb6f0ed 100644 --- a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/world/SSpawnerImpl.java +++ b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/world/SSpawnerImpl.java @@ -21,7 +21,6 @@ import java.util.Random; import java.util.Set; public class SSpawnerImpl implements SSpawner { - private final Location spawnerLocation; public SSpawnerImpl(Location location) { @@ -36,7 +35,6 @@ public class SSpawnerImpl implements SSpawner { @Override public LivingEntity spawnEntity(EntityType type, String particleType, SpawnedEntity spawned, Set canSpawnOn) { - short spawnRange = 4; for (int i = 0; i < 50; i++) { WorldServer world = ((CraftWorld) spawnerLocation.getWorld()).getHandle(); @@ -52,27 +50,30 @@ public class SSpawnerImpl implements SSpawner { BlockPosition position = entity.getChunkCoordinates(); DifficultyDamageScaler damageScaler = world.E(position); - if (!(entity instanceof EntityInsentient)) + if (!(entity instanceof EntityInsentient)) { continue; + } EntityInsentient entityInsentient = (EntityInsentient) entity; Location spot = new Location(spawnerLocation.getWorld(), x, y, z); - if (!canSpawn(entityInsentient, spot, canSpawnOn)) + if (!canSpawn(entityInsentient, spot, canSpawnOn)) { continue; + } entityInsentient.prepare(damageScaler, null); LivingEntity craftEntity = (LivingEntity) entity.getBukkitEntity(); - if (spawned != null) - if (!spawned.onSpawn(craftEntity)) - return null; + if (spawned != null && !spawned.onSpawn(craftEntity)) { + return null; + } if (particleType != null) { float xx = (float) (0 + (Math.random() * 1)); float yy = (float) (0 + (Math.random() * 2)); float zz = (float) (0 + (Math.random() * 1)); + CompatibleParticleHandler.spawnParticles(CompatibleParticleHandler.ParticleType.getParticle(particleType), spot, 5, xx, yy, zz, 0); } @@ -84,32 +85,37 @@ public class SSpawnerImpl implements SSpawner { return craftEntity; } + return null; } private boolean canSpawn(EntityInsentient entityInsentient, Location location, Set canSpawnOn) { - if (!entityInsentient.canSpawn()) + if (!entityInsentient.canSpawn()) { return false; + } CompatibleMaterial spawnedIn = CompatibleMaterial.getMaterial(location.getBlock()); CompatibleMaterial spawnedOn = CompatibleMaterial.getMaterial(location.getBlock().getRelative(BlockFace.DOWN)); - if (spawnedIn == null || spawnedOn == null) + if (spawnedIn == null || spawnedOn == null) { return false; + } - if (!spawnedIn.isAir() - && spawnedIn != CompatibleMaterial.WATER - && !spawnedIn.name().contains("PRESSURE") - && !spawnedIn.name().contains("SLAB")) { + if (!spawnedIn.isAir() && + spawnedIn != CompatibleMaterial.WATER && + !spawnedIn.name().contains("PRESSURE") && + !spawnedIn.name().contains("SLAB")) { return false; } for (CompatibleMaterial material : canSpawnOn) { if (material == null) continue; - if (spawnedOn.equals(material) || material.isAir()) + if (spawnedOn.equals(material) || material.isAir()) { return true; + } } + return false; } } diff --git a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/world/SWorldImpl.java b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/world/SWorldImpl.java index 9022ab05..2518d072 100644 --- a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/world/SWorldImpl.java +++ b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/world/SWorldImpl.java @@ -7,7 +7,6 @@ import java.util.ArrayList; import java.util.List; public class SWorldImpl implements SWorld { - public SWorldImpl() { } diff --git a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/world/WorldCoreImpl.java b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/world/WorldCoreImpl.java index 3a7048d7..2c024638 100644 --- a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/world/WorldCoreImpl.java +++ b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/world/WorldCoreImpl.java @@ -56,31 +56,32 @@ public class WorldCoreImpl implements WorldCore { public void randomTickChunk(org.bukkit.Chunk bukkitChunk, int tickAmount) throws NoSuchFieldException, IllegalAccessException { Chunk chunk = ((CraftChunk) bukkitChunk).getHandle(); - if (tickAmount > 0) { - int k = chunk.locX * 16; - int l = chunk.locZ * 16; + if (tickAmount <= 0) { + return; + } - for (ChunkSection cSection : chunk.getSections()) { - if (cSection != null && cSection.shouldTick()) { + int k = chunk.locX * 16; + int l = chunk.locZ * 16; - for (int i = 0; i < tickAmount; ++i) { - int m = (int) ReflectionUtils.getFieldValue(chunk.world, "m"); + for (ChunkSection cSection : chunk.getSections()) { + if (cSection != null && cSection.shouldTick()) { + for (int i = 0; i < tickAmount; ++i) { + int m = (int) ReflectionUtils.getFieldValue(chunk.world, "m"); - m = m * 3 + 1013904223; - ReflectionUtils.setFieldValue(chunk.world, "m", m); + m = m * 3 + 1013904223; + ReflectionUtils.setFieldValue(chunk.world, "m", m); - int i2 = m >> 2; - int j2 = i2 & 15; - int k2 = i2 >> 8 & 15; - int l2 = i2 >> 16 & 15; + int i2 = m >> 2; + int j2 = i2 & 15; + int k2 = i2 >> 8 & 15; + int l2 = i2 >> 16 & 15; - BlockPosition blockposition2 = new BlockPosition(j2 + k, l2 + cSection.getYPosition(), k2 + l); - IBlockData iblockdata = cSection.getType(j2, l2, k2); - Block block = iblockdata.getBlock(); + BlockPosition blockposition2 = new BlockPosition(j2 + k, l2 + cSection.getYPosition(), k2 + l); + IBlockData iblockdata = cSection.getType(j2, l2, k2); + Block block = iblockdata.getBlock(); - if (block.isTicking()) { - block.a(chunk.world, blockposition2, iblockdata, chunk.world.random); - } + if (block.isTicking()) { + block.a(chunk.world, blockposition2, iblockdata, chunk.world.random); } } } diff --git a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/world/spawner/BBaseSpawnerImpl.java b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/world/spawner/BBaseSpawnerImpl.java index 69237cf4..14787f50 100644 --- a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/world/spawner/BBaseSpawnerImpl.java +++ b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/world/spawner/BBaseSpawnerImpl.java @@ -69,70 +69,71 @@ public class BBaseSpawnerImpl implements BBaseSpawner { ReflectionUtils.setFieldValue(spawner, "f", spawnerE); ReflectionUtils.setFieldValue(spawner, "e", (spawnerE + (double) (1000F / ((float) spawner.spawnDelay + 200F))) % 360D); - } else { - if (spawner.spawnDelay == -1) { - delay(spawner); + return; + } + + if (spawner.spawnDelay == -1) { + delay(spawner); + } + + if (spawner.spawnDelay > 0) { + --spawner.spawnDelay; + return; + } + + boolean flag = false; + int i = 0; + + int spawnCount = (int) ReflectionUtils.getFieldValue(spawner, "spawnCount"); + int spawnRange = (int) ReflectionUtils.getFieldValue(spawner, "spawnRange"); + int maxNearbyEntities = (int) ReflectionUtils.getFieldValue(spawner, "maxNearbyEntities"); + while (true) { + if (i >= spawnCount) { + if (flag) { + delay(spawner); + } + + break; } - if (spawner.spawnDelay > 0) { - --spawner.spawnDelay; + Entity entity = EntityTypes.createEntityByName(spawner.getMobName(), spawner.a()); + if (entity == null) { return; } - boolean flag = false; - int i = 0; + int j = spawner.a() + .a(entity.getClass(), (new AxisAlignedBB(blockposition.getX(), + blockposition.getY(), + blockposition.getZ(), + blockposition.getX() + 1, + blockposition.getY() + 1, + blockposition.getZ() + 1)) + .grow(spawnRange, spawnRange, spawnRange)).size(); - int spawnCount = (int) ReflectionUtils.getFieldValue(spawner, "spawnCount"); - int spawnRange = (int) ReflectionUtils.getFieldValue(spawner, "spawnRange"); - int maxNearbyEntities = (int) ReflectionUtils.getFieldValue(spawner, "maxNearbyEntities"); - while (true) { - if (i >= spawnCount) { - if (flag) { - delay(spawner); - } - - break; - } - - Entity entity = EntityTypes.createEntityByName(spawner.getMobName(), spawner.a()); - if (entity == null) { - return; - } - - int j = spawner.a() - .a(entity.getClass(), (new AxisAlignedBB(blockposition.getX(), - blockposition.getY(), - blockposition.getZ(), - blockposition.getX() + 1, - blockposition.getY() + 1, - blockposition.getZ() + 1)) - .grow(spawnRange, spawnRange, spawnRange)).size(); - - if (j >= maxNearbyEntities) { - delay(spawner); - return; - } - - double d0 = (double) blockposition.getX() + (spawner.a().random.nextDouble() - spawner.a().random.nextDouble()) * (double) spawnRange + 0.5D; - double d3 = blockposition.getY() + spawner.a().random.nextInt(3) - 1; - double d4 = (double) blockposition.getZ() + (spawner.a().random.nextDouble() - spawner.a().random.nextDouble()) * (double) spawnRange + 0.5D; - - EntityInsentient entityinsentient = entity instanceof EntityInsentient ? (EntityInsentient) entity : null; - entity.setPositionRotation(d0, d3, d4, spawner.a().random.nextFloat() * 360.0F, 0.0F); - - if (entityinsentient == null || entityinsentient.bQ() && entityinsentient.canSpawn()) { - aEntityBooleanMethod.invoke(spawner, entity, true); - spawner.a().triggerEffect(2004, blockposition, 0); - - if (entityinsentient != null) { - entityinsentient.y(); - } - - flag = true; - } - - ++i; + if (j >= maxNearbyEntities) { + delay(spawner); + return; } + + double d0 = (double) blockposition.getX() + (spawner.a().random.nextDouble() - spawner.a().random.nextDouble()) * (double) spawnRange + 0.5D; + double d3 = blockposition.getY() + spawner.a().random.nextInt(3) - 1; + double d4 = (double) blockposition.getZ() + (spawner.a().random.nextDouble() - spawner.a().random.nextDouble()) * (double) spawnRange + 0.5D; + + EntityInsentient entityinsentient = entity instanceof EntityInsentient ? (EntityInsentient) entity : null; + entity.setPositionRotation(d0, d3, d4, spawner.a().random.nextFloat() * 360.0F, 0.0F); + + if (entityinsentient == null || entityinsentient.bQ() && entityinsentient.canSpawn()) { + aEntityBooleanMethod.invoke(spawner, entity, true); + spawner.a().triggerEffect(2004, blockposition, 0); + + if (entityinsentient != null) { + entityinsentient.y(); + } + + flag = true; + } + + ++i; } } diff --git a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/anvil/AnvilCore.java b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/anvil/AnvilCore.java index 8b9387ad..09325be3 100644 --- a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/anvil/AnvilCore.java +++ b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/anvil/AnvilCore.java @@ -6,7 +6,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; public class AnvilCore implements com.songoda.core.nms.anvil.AnvilCore { - @Override public CustomAnvil createAnvil(Player player) { return new AnvilView(((CraftPlayer) player).getHandle(), null); diff --git a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/anvil/AnvilInventoryCustom.java b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/anvil/AnvilInventoryCustom.java index b5824b4a..db7fd4d9 100644 --- a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/anvil/AnvilInventoryCustom.java +++ b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/anvil/AnvilInventoryCustom.java @@ -5,11 +5,11 @@ import org.bukkit.craftbukkit.v1_8_R2.inventory.CraftInventoryAnvil; import org.bukkit.inventory.InventoryHolder; public class AnvilInventoryCustom extends CraftInventoryAnvil { - final InventoryHolder holder; public AnvilInventoryCustom(InventoryHolder holder, IInventory inventory, IInventory resultInventory) { super(inventory, resultInventory); + this.holder = holder; } diff --git a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/anvil/AnvilView.java b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/anvil/AnvilView.java index dd55b1f8..9b769bf5 100644 --- a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/anvil/AnvilView.java +++ b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/anvil/AnvilView.java @@ -19,7 +19,6 @@ import java.util.logging.Level; import java.util.logging.Logger; public class AnvilView extends ContainerAnvil implements CustomAnvil { - private final EntityPlayer entity; private final Inventory inventory; private String title = "Repairing"; @@ -36,8 +35,10 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { try { mc_ContainerAnvil_repairInventory = ContainerAnvil.class.getDeclaredField("h"); mc_ContainerAnvil_repairInventory.setAccessible(true); + mc_ContainerAnvil_resultInventory = ContainerAnvil.class.getDeclaredField("g"); mc_ContainerAnvil_resultInventory.setAccessible(true); + mc_ContainerAnvil_bukkitEntity = ContainerAnvil.class.getDeclaredField("bukkitEntity"); mc_ContainerAnvil_bukkitEntity.setAccessible(true); } catch (Exception ex) { @@ -60,11 +61,13 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { public AnvilView(EntityPlayer entity, InventoryHolder holder) { super(entity.inventory, entity.world, new BlockPosition(0, 0, 0), entity); this.entity = entity; + if (holder != null) { this.inventory = getBukkitView(entity, holder).getTopInventory(); - } else { - this.inventory = getBukkitView().getTopInventory(); + return; } + + this.inventory = getBukkitView().getTopInventory(); } public CraftInventoryView getBukkitView(EntityHuman player, InventoryHolder holder) { @@ -74,10 +77,12 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { (IInventory) mc_ContainerAnvil_resultInventory.get(this)); CraftInventoryView view = new CraftInventoryView(player.getBukkitEntity(), craftInventory, this); mc_ContainerAnvil_bukkitEntity.set(this, view); + return view; } catch (Exception ex) { Logger.getLogger(AnvilView.class.getName()).log(Level.SEVERE, "Anvil Setup Error", ex); } + return getBukkitView(); } @@ -89,6 +94,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void e() { super.e(); + if (cost >= 0) { this.a = cost; } @@ -107,6 +113,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { } catch (Exception ex) { Logger.getLogger(AnvilView.class.getName()).log(Level.SEVERE, "Anvil Error", ex); } + return null; } @@ -182,7 +189,6 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void open() { - // Counter stuff that the game uses to keep track of inventories int id = entity.nextContainerCounter(); diff --git a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/nbt/NBTCompoundImpl.java b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/nbt/NBTCompoundImpl.java index 9b70e8e0..97966c83 100644 --- a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/nbt/NBTCompoundImpl.java +++ b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/nbt/NBTCompoundImpl.java @@ -15,7 +15,6 @@ import java.util.Set; import java.util.UUID; public class NBTCompoundImpl implements NBTCompound { - protected NBTTagCompound compound; protected NBTCompoundImpl(NBTTagCompound compound) { @@ -84,6 +83,7 @@ public class NBTCompoundImpl implements NBTCompound { public NBTCompound set(String tag, UUID u) { set(tag + "Most", u.getMostSignificantBits()); set(tag + "Least", u.getLeastSignificantBits()); + return this; } @@ -152,11 +152,11 @@ public class NBTCompoundImpl implements NBTCompound { public NBTCompound getCompound(String tag) { if (has(tag)) { return getNBTObject(tag).asCompound(); - } else { - NBTTagCompound newCompound = new NBTTagCompound(); - compound.set(tag, newCompound); - return new NBTCompoundImpl(newCompound); } + + NBTTagCompound newCompound = new NBTTagCompound(); + compound.set(tag, newCompound); + return new NBTCompoundImpl(newCompound); } @Override @@ -176,15 +176,17 @@ public class NBTCompoundImpl implements NBTCompound { addExtras(); NBTTagCompound compound = (NBTTagCompound) this.compound.clone(); // Changed in 1.12 // Changed in 1.9.4 - for (String exclusion : exclusions) + for (String exclusion : exclusions) { compound.remove(exclusion); + } NBTCompressedStreamTools.a(compound, (OutputStream) dataOutput); return outputStream.toByteArray(); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } + return null; } @@ -193,8 +195,8 @@ public class NBTCompoundImpl implements NBTCompound { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(serialized); ObjectInputStream dataInput = new ObjectInputStream(inputStream)) { compound = NBTCompressedStreamTools.a((InputStream) dataInput); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } } diff --git a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/nbt/NBTCoreImpl.java b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/nbt/NBTCoreImpl.java index db563f3d..0d9785b8 100644 --- a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/nbt/NBTCoreImpl.java +++ b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/nbt/NBTCoreImpl.java @@ -10,7 +10,6 @@ import org.bukkit.entity.Entity; import org.bukkit.inventory.ItemStack; public class NBTCoreImpl implements NBTCore { - @Override public NBTItem of(ItemStack item) { return new NBTItemImpl(CraftItemStack.asNMSCopy(item)); @@ -26,6 +25,7 @@ public class NBTCoreImpl implements NBTCore { net.minecraft.server.v1_8_R2.Entity nmsEntity = ((CraftEntity) entity).getHandle(); NBTTagCompound nbt = new NBTTagCompound(); nmsEntity.e(nbt); // Method name changed in 1.11 + return new NBTEntityImpl(nbt, nmsEntity); } diff --git a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/nbt/NBTEntityImpl.java b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/nbt/NBTEntityImpl.java index 1d17a0f7..6114833b 100644 --- a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/nbt/NBTEntityImpl.java +++ b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/nbt/NBTEntityImpl.java @@ -13,13 +13,13 @@ import java.lang.reflect.Field; import java.util.Map; public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { - private static Field fieldG; private Entity nmsEntity; public NBTEntityImpl(NBTTagCompound entityNBT, Entity nmsEntity) { super(entityNBT); + this.nmsEntity = nmsEntity; } @@ -27,8 +27,8 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { try { fieldG = EntityTypes.class.getDeclaredField("g"); fieldG.setAccessible(true); - } catch (NoSuchFieldException e) { - e.printStackTrace(); + } catch (NoSuchFieldException ex) { + ex.printStackTrace(); } } @@ -50,11 +50,13 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { spawned.setLocation(location.getX(), location.getY(), location.getZ(), location.getPitch(), location.getYaw()); nmsEntity = spawned; + return entity; } - } catch (IllegalAccessException e) { - e.printStackTrace(); + } catch (IllegalAccessException ex) { + ex.printStackTrace(); } + return null; } @@ -67,7 +69,9 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { @Override public void addExtras() { String key = EntityTypes.b(nmsEntity); // Changed in 1.12 - if (key != null) + + if (key != null) { compound.setString("entity_type", key); // Changed in 1.13 + } } } diff --git a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/nbt/NBTItemImpl.java b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/nbt/NBTItemImpl.java index d44d6952..d07730c2 100644 --- a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/nbt/NBTItemImpl.java @@ -6,20 +6,20 @@ import org.bukkit.craftbukkit.v1_8_R2.inventory.CraftItemStack; import org.bukkit.inventory.ItemStack; public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { - private final net.minecraft.server.v1_8_R2.ItemStack nmsItem; public NBTItemImpl(net.minecraft.server.v1_8_R2.ItemStack nmsItem) { super(nmsItem != null && nmsItem.hasTag() ? nmsItem.getTag() : new NBTTagCompound()); + this.nmsItem = nmsItem; } public ItemStack finish() { if (nmsItem == null) { return CraftItemStack.asBukkitCopy(net.minecraft.server.v1_8_R2.ItemStack.createStack(compound)); - } else { - return CraftItemStack.asBukkitCopy(nmsItem); } + + return CraftItemStack.asBukkitCopy(nmsItem); } @Override diff --git a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/nbt/NBTObjectImpl.java b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/nbt/NBTObjectImpl.java index deaf3e4d..e78037c4 100644 --- a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/nbt/NBTObjectImpl.java +++ b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/nbt/NBTObjectImpl.java @@ -7,7 +7,6 @@ import net.minecraft.server.v1_8_R2.NBTTagCompound; import java.util.Set; public class NBTObjectImpl implements NBTObject { - private final NBTTagCompound compound; private final String tag; diff --git a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/world/SItemStackImpl.java b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/world/SItemStackImpl.java index 7e87d059..7a324712 100644 --- a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/world/SItemStackImpl.java +++ b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/world/SItemStackImpl.java @@ -11,7 +11,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public class SItemStackImpl implements SItemStack { - private final ItemStack item; public SItemStackImpl(ItemStack item) { @@ -21,11 +20,14 @@ public class SItemStackImpl implements SItemStack { @Override public void breakItem(Player player, int amount) { EntityPlayer entityPlayer = ((CraftPlayer) player).getHandle(); + for (int i = 0; i < 5; ++i) { Vec3D vec3d = new Vec3D(((double) random.nextFloat() - 0.5D) * 0.1D, Math.random() * 0.1D + 0.1D, 0.0D); vec3d = vec3d.a(-entityPlayer.pitch * 0.017453292F); vec3d = vec3d.b(-entityPlayer.yaw * 0.017453292F); + double d0 = (double) (-random.nextFloat()) * 0.6D - 0.3D; + Vec3D vec3d1 = new Vec3D(((double) random.nextFloat() - 0.5D) * 0.3D, d0, 0.6D); vec3d1 = vec3d1.a(-entityPlayer.pitch * 0.017453292F); vec3d1 = vec3d1.b(-entityPlayer.yaw * 0.017453292F); diff --git a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/world/SSpawnerImpl.java b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/world/SSpawnerImpl.java index 8198d654..31d629cc 100644 --- a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/world/SSpawnerImpl.java +++ b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/world/SSpawnerImpl.java @@ -21,7 +21,6 @@ import java.util.Random; import java.util.Set; public class SSpawnerImpl implements SSpawner { - private final Location spawnerLocation; public SSpawnerImpl(Location location) { @@ -36,7 +35,6 @@ public class SSpawnerImpl implements SSpawner { @Override public LivingEntity spawnEntity(EntityType type, String particleType, SpawnedEntity spawned, Set canSpawnOn) { - short spawnRange = 4; for (int i = 0; i < 50; i++) { WorldServer world = ((CraftWorld) spawnerLocation.getWorld()).getHandle(); @@ -52,27 +50,30 @@ public class SSpawnerImpl implements SSpawner { BlockPosition position = entity.getChunkCoordinates(); DifficultyDamageScaler damageScaler = world.E(position); - if (!(entity instanceof EntityInsentient)) + if (!(entity instanceof EntityInsentient)) { continue; + } EntityInsentient entityInsentient = (EntityInsentient) entity; Location spot = new Location(spawnerLocation.getWorld(), x, y, z); - if (!canSpawn(entityInsentient, spot, canSpawnOn)) + if (!canSpawn(entityInsentient, spot, canSpawnOn)) { continue; + } entityInsentient.prepare(damageScaler, null); LivingEntity craftEntity = (LivingEntity) entity.getBukkitEntity(); - if (spawned != null) - if (!spawned.onSpawn(craftEntity)) - return null; + if (spawned != null && !spawned.onSpawn(craftEntity)) { + return null; + } if (particleType != null) { float xx = (float) (0 + (Math.random() * 1)); float yy = (float) (0 + (Math.random() * 2)); float zz = (float) (0 + (Math.random() * 1)); + CompatibleParticleHandler.spawnParticles(CompatibleParticleHandler.ParticleType.getParticle(particleType), spot, 5, xx, yy, zz, 0); } @@ -84,32 +85,37 @@ public class SSpawnerImpl implements SSpawner { return craftEntity; } + return null; } private boolean canSpawn(EntityInsentient entityInsentient, Location location, Set canSpawnOn) { - if (!entityInsentient.canSpawn()) + if (!entityInsentient.canSpawn()) { return false; + } CompatibleMaterial spawnedIn = CompatibleMaterial.getMaterial(location.getBlock()); CompatibleMaterial spawnedOn = CompatibleMaterial.getMaterial(location.getBlock().getRelative(BlockFace.DOWN)); - if (spawnedIn == null || spawnedOn == null) + if (spawnedIn == null || spawnedOn == null) { return false; + } - if (!spawnedIn.isAir() - && spawnedIn != CompatibleMaterial.WATER - && !spawnedIn.name().contains("PRESSURE") - && !spawnedIn.name().contains("SLAB")) { + if (!spawnedIn.isAir() && + spawnedIn != CompatibleMaterial.WATER && + !spawnedIn.name().contains("PRESSURE") && + !spawnedIn.name().contains("SLAB")) { return false; } for (CompatibleMaterial material : canSpawnOn) { if (material == null) continue; - if (spawnedOn.equals(material) || material.isAir()) + if (spawnedOn.equals(material) || material.isAir()) { return true; + } } + return false; } } diff --git a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/world/SWorldImpl.java b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/world/SWorldImpl.java index aaaeb584..fa2fc439 100644 --- a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/world/SWorldImpl.java +++ b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/world/SWorldImpl.java @@ -7,7 +7,6 @@ import java.util.ArrayList; import java.util.List; public class SWorldImpl implements SWorld { - public SWorldImpl() { } diff --git a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/world/WorldCoreImpl.java b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/world/WorldCoreImpl.java index 6e4db821..bd0d76bc 100644 --- a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/world/WorldCoreImpl.java +++ b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/world/WorldCoreImpl.java @@ -56,30 +56,32 @@ public class WorldCoreImpl implements WorldCore { public void randomTickChunk(org.bukkit.Chunk bukkitChunk, int tickAmount) throws NoSuchFieldException, IllegalAccessException { Chunk chunk = ((CraftChunk) bukkitChunk).getHandle(); - if (tickAmount > 0) { - int k = chunk.locX * 16; - int l = chunk.locZ * 16; + if (tickAmount <= 0) { + return; + } - for (ChunkSection cSection : chunk.getSections()) { - if (cSection != null && cSection.shouldTick()) { - for (int i = 0; i < tickAmount; ++i) { - int m = (int) ReflectionUtils.getFieldValue(chunk.world, "m"); + int k = chunk.locX * 16; + int l = chunk.locZ * 16; - m = m * 3 + 1013904223; - ReflectionUtils.setFieldValue(chunk.world, "m", m); + for (ChunkSection cSection : chunk.getSections()) { + if (cSection != null && cSection.shouldTick()) { + for (int i = 0; i < tickAmount; ++i) { + int m = (int) ReflectionUtils.getFieldValue(chunk.world, "m"); - int i2 = m >> 2; - int j2 = i2 & 15; - int k2 = i2 >> 8 & 15; - int l2 = i2 >> 16 & 15; + m = m * 3 + 1013904223; + ReflectionUtils.setFieldValue(chunk.world, "m", m); - BlockPosition blockposition2 = new BlockPosition(j2 + k, l2 + cSection.getYPosition(), k2 + l); - IBlockData iblockdata = cSection.getType(j2, l2, k2); - Block block = iblockdata.getBlock(); + int i2 = m >> 2; + int j2 = i2 & 15; + int k2 = i2 >> 8 & 15; + int l2 = i2 >> 16 & 15; - if (block.isTicking()) { - block.a(chunk.world, blockposition2, iblockdata, chunk.world.random); - } + BlockPosition blockposition2 = new BlockPosition(j2 + k, l2 + cSection.getYPosition(), k2 + l); + IBlockData iblockdata = cSection.getType(j2, l2, k2); + Block block = iblockdata.getBlock(); + + if (block.isTicking()) { + block.a(chunk.world, blockposition2, iblockdata, chunk.world.random); } } } diff --git a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/world/spawner/BBaseSpawnerImpl.java b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/world/spawner/BBaseSpawnerImpl.java index d9b6cabd..441c011b 100644 --- a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/world/spawner/BBaseSpawnerImpl.java +++ b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/world/spawner/BBaseSpawnerImpl.java @@ -66,66 +66,68 @@ public class BBaseSpawnerImpl implements BBaseSpawner { ReflectionUtils.setFieldValue(spawner, "f", spawnerE); ReflectionUtils.setFieldValue(spawner, "e", (spawnerE + (double) (1000F / ((float) spawner.spawnDelay + 200.0F))) % 360D); - } else { - if (spawner.spawnDelay == -1) { - delay(spawner); + return; + } + + if (spawner.spawnDelay == -1) { + delay(spawner); + } + + if (spawner.spawnDelay > 0) { + --spawner.spawnDelay; + return; + } + + boolean flag = false; + int i = 0; + + int spawnCount = (int) ReflectionUtils.getFieldValue(spawner, "spawnCount"); + int spawnRange = (int) ReflectionUtils.getFieldValue(spawner, "spawnRange"); + int maxNearbyEntities = (int) ReflectionUtils.getFieldValue(spawner, "maxNearbyEntities"); + + while (true) { + if (i >= spawnCount) { + if (flag) { + delay(spawner); + } + + break; } - if (spawner.spawnDelay > 0) { - --spawner.spawnDelay; + Entity entity = EntityTypes.createEntityByName(spawner.getMobName(), spawner.a()); + if (entity == null) { return; } - boolean flag = false; - int i = 0; - - int spawnCount = (int) ReflectionUtils.getFieldValue(spawner, "spawnCount"); - int spawnRange = (int) ReflectionUtils.getFieldValue(spawner, "spawnRange"); - int maxNearbyEntities = (int) ReflectionUtils.getFieldValue(spawner, "maxNearbyEntities"); - - while (true) { - if (i >= spawnCount) { - if (flag) { - delay(spawner); - } - break; - } - - Entity entity = EntityTypes.createEntityByName(spawner.getMobName(), spawner.a()); - if (entity == null) { - return; - } - - int j = spawner.a().a(entity.getClass(), (new AxisAlignedBB( - blockposition.getX(), - blockposition.getY(), - blockposition.getZ(), - blockposition.getX() + 1, - blockposition.getY() + 1, - blockposition.getZ() + 1)) - .grow(spawnRange, spawnRange, spawnRange)).size(); - if (j >= maxNearbyEntities) { - delay(spawner); - return; - } - - double d0 = (double) blockposition.getX() + (spawner.a().random.nextDouble() - spawner.a().random.nextDouble()) * (double) spawnRange + .5D; - double d3 = blockposition.getY() + spawner.a().random.nextInt(3) - 1; - double d4 = (double) blockposition.getZ() + (spawner.a().random.nextDouble() - spawner.a().random.nextDouble()) * (double) spawnRange + .5D; - EntityInsentient entityinsentient = entity instanceof EntityInsentient ? (EntityInsentient) entity : null; - entity.setPositionRotation(d0, d3, d4, spawner.a().random.nextFloat() * 360F, 0F); - if (entityinsentient == null || entityinsentient.bR() && entityinsentient.canSpawn()) { - aEntityBooleanMethod.invoke(spawner, entity, true); - spawner.a().triggerEffect(2004, blockposition, 0); - if (entityinsentient != null) { - entityinsentient.y(); - } - - flag = true; - } - - ++i; + int j = spawner.a().a(entity.getClass(), (new AxisAlignedBB( + blockposition.getX(), + blockposition.getY(), + blockposition.getZ(), + blockposition.getX() + 1, + blockposition.getY() + 1, + blockposition.getZ() + 1)) + .grow(spawnRange, spawnRange, spawnRange)).size(); + if (j >= maxNearbyEntities) { + delay(spawner); + return; } + + double d0 = (double) blockposition.getX() + (spawner.a().random.nextDouble() - spawner.a().random.nextDouble()) * (double) spawnRange + .5D; + double d3 = blockposition.getY() + spawner.a().random.nextInt(3) - 1; + double d4 = (double) blockposition.getZ() + (spawner.a().random.nextDouble() - spawner.a().random.nextDouble()) * (double) spawnRange + .5D; + EntityInsentient entityinsentient = entity instanceof EntityInsentient ? (EntityInsentient) entity : null; + entity.setPositionRotation(d0, d3, d4, spawner.a().random.nextFloat() * 360F, 0F); + if (entityinsentient == null || entityinsentient.bR() && entityinsentient.canSpawn()) { + aEntityBooleanMethod.invoke(spawner, entity, true); + spawner.a().triggerEffect(2004, blockposition, 0); + if (entityinsentient != null) { + entityinsentient.y(); + } + + flag = true; + } + + ++i; } } @@ -136,4 +138,4 @@ public class BBaseSpawnerImpl implements BBaseSpawner { private void delay(MobSpawnerAbstract spawner) throws InvocationTargetException, IllegalAccessException { hMethod.invoke(spawner); } -} \ No newline at end of file +} diff --git a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/anvil/AnvilCore.java b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/anvil/AnvilCore.java index 47b8399b..a2b88946 100644 --- a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/anvil/AnvilCore.java +++ b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/anvil/AnvilCore.java @@ -6,7 +6,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; public class AnvilCore implements com.songoda.core.nms.anvil.AnvilCore { - @Override public CustomAnvil createAnvil(Player player) { return new AnvilView(((CraftPlayer) player).getHandle(), null); diff --git a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/anvil/AnvilInventoryCustom.java b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/anvil/AnvilInventoryCustom.java index 3fe1e044..90b1354d 100644 --- a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/anvil/AnvilInventoryCustom.java +++ b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/anvil/AnvilInventoryCustom.java @@ -5,11 +5,11 @@ import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftInventoryAnvil; import org.bukkit.inventory.InventoryHolder; public class AnvilInventoryCustom extends CraftInventoryAnvil { - final InventoryHolder holder; public AnvilInventoryCustom(InventoryHolder holder, IInventory inventory, IInventory resultInventory) { super(inventory, resultInventory); + this.holder = holder; } diff --git a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/anvil/AnvilView.java b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/anvil/AnvilView.java index 2ff86a6b..8c065247 100644 --- a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/anvil/AnvilView.java +++ b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/anvil/AnvilView.java @@ -19,7 +19,6 @@ import java.util.logging.Level; import java.util.logging.Logger; public class AnvilView extends ContainerAnvil implements CustomAnvil { - private final EntityPlayer entity; private final Inventory inventory; private String title = "Repairing"; @@ -36,8 +35,10 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { try { mc_ContainerAnvil_repairInventory = ContainerAnvil.class.getDeclaredField("h"); mc_ContainerAnvil_repairInventory.setAccessible(true); + mc_ContainerAnvil_resultInventory = ContainerAnvil.class.getDeclaredField("g"); mc_ContainerAnvil_resultInventory.setAccessible(true); + mc_ContainerAnvil_bukkitEntity = ContainerAnvil.class.getDeclaredField("bukkitEntity"); mc_ContainerAnvil_bukkitEntity.setAccessible(true); } catch (Exception ex) { @@ -60,11 +61,13 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { public AnvilView(EntityPlayer entity, InventoryHolder holder) { super(entity.inventory, entity.world, new BlockPosition(0, 0, 0), entity); this.entity = entity; + if (holder != null) { this.inventory = getBukkitView(entity, holder).getTopInventory(); - } else { - this.inventory = getBukkitView().getTopInventory(); + return; } + + this.inventory = getBukkitView().getTopInventory(); } public CraftInventoryView getBukkitView(EntityHuman player, InventoryHolder holder) { @@ -74,10 +77,12 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { (IInventory) mc_ContainerAnvil_resultInventory.get(this)); CraftInventoryView view = new CraftInventoryView(player.getBukkitEntity(), craftInventory, this); mc_ContainerAnvil_bukkitEntity.set(this, view); + return view; } catch (Exception ex) { Logger.getLogger(AnvilView.class.getName()).log(Level.SEVERE, "Anvil Setup Error", ex); } + return getBukkitView(); } @@ -89,6 +94,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void e() { super.e(); + if (cost >= 0) { this.a = cost; } @@ -107,6 +113,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { } catch (Exception ex) { Logger.getLogger(AnvilView.class.getName()).log(Level.SEVERE, "Anvil Error", ex); } + return null; } @@ -182,7 +189,6 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void open() { - // Counter stuff that the game uses to keep track of inventories int id = entity.nextContainerCounter(); diff --git a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/nbt/NBTCompoundImpl.java b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/nbt/NBTCompoundImpl.java index 01422252..a39aca33 100644 --- a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/nbt/NBTCompoundImpl.java +++ b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/nbt/NBTCompoundImpl.java @@ -15,7 +15,6 @@ import java.util.Set; import java.util.UUID; public class NBTCompoundImpl implements NBTCompound { - protected NBTTagCompound compound; protected NBTCompoundImpl(NBTTagCompound compound) { @@ -176,15 +175,17 @@ public class NBTCompoundImpl implements NBTCompound { addExtras(); NBTTagCompound compound = (NBTTagCompound) this.compound.clone(); // Changed in 1.12 // Changed in 1.9.4 - for (String exclusion : exclusions) + for (String exclusion : exclusions) { compound.remove(exclusion); + } NBTCompressedStreamTools.a(compound, (OutputStream) dataOutput); return outputStream.toByteArray(); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } + return null; } @@ -193,8 +194,8 @@ public class NBTCompoundImpl implements NBTCompound { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(serialized); ObjectInputStream dataInput = new ObjectInputStream(inputStream)) { compound = NBTCompressedStreamTools.a((InputStream) dataInput); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } } diff --git a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/nbt/NBTCoreImpl.java b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/nbt/NBTCoreImpl.java index d9bbb3f9..8af4de92 100644 --- a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/nbt/NBTCoreImpl.java +++ b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/nbt/NBTCoreImpl.java @@ -10,7 +10,6 @@ import org.bukkit.entity.Entity; import org.bukkit.inventory.ItemStack; public class NBTCoreImpl implements NBTCore { - @Override public NBTItem of(ItemStack item) { return new NBTItemImpl(CraftItemStack.asNMSCopy(item)); @@ -26,6 +25,7 @@ public class NBTCoreImpl implements NBTCore { net.minecraft.server.v1_8_R3.Entity nmsEntity = ((CraftEntity) entity).getHandle(); NBTTagCompound nbt = new NBTTagCompound(); nmsEntity.e(nbt); // Method name changed in 1.11 + return new NBTEntityImpl(nbt, nmsEntity); } diff --git a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/nbt/NBTEntityImpl.java b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/nbt/NBTEntityImpl.java index a087aefb..29d726f7 100644 --- a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/nbt/NBTEntityImpl.java +++ b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/nbt/NBTEntityImpl.java @@ -14,13 +14,13 @@ import java.lang.reflect.Field; import java.util.Map; public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { - private static Field fieldG; private Entity nmsEntity; public NBTEntityImpl(NBTTagCompound entityNBT, Entity nmsEntity) { super(entityNBT); + this.nmsEntity = nmsEntity; } @@ -28,8 +28,8 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { try { fieldG = EntityTypes.class.getDeclaredField("g"); fieldG.setAccessible(true); - } catch (NoSuchFieldException e) { - e.printStackTrace(); + } catch (NoSuchFieldException ex) { + ex.printStackTrace(); } } @@ -51,11 +51,13 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { spawned.setLocation(location.getX(), location.getY(), location.getZ(), location.getPitch(), location.getYaw()); nmsEntity = spawned; + return entity; } - } catch (IllegalAccessException e) { - e.printStackTrace(); + } catch (IllegalAccessException ex) { + ex.printStackTrace(); } + return null; } @@ -79,7 +81,9 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { @Override public void addExtras() { String key = EntityTypes.b(nmsEntity); // Changed in 1.12 - if (key != null) + + if (key != null) { compound.setString("entity_type", key); // Changed in 1.13 + } } } diff --git a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/nbt/NBTItemImpl.java b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/nbt/NBTItemImpl.java index 181c5e3d..cd7ec969 100644 --- a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/nbt/NBTItemImpl.java @@ -6,7 +6,6 @@ import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack; import org.bukkit.inventory.ItemStack; public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { - private final net.minecraft.server.v1_8_R3.ItemStack nmsItem; public NBTItemImpl(net.minecraft.server.v1_8_R3.ItemStack nmsItem) { diff --git a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/nbt/NBTObjectImpl.java b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/nbt/NBTObjectImpl.java index 1ee72562..18f1ebe2 100644 --- a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/nbt/NBTObjectImpl.java +++ b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/nbt/NBTObjectImpl.java @@ -7,7 +7,6 @@ import net.minecraft.server.v1_8_R3.NBTTagCompound; import java.util.Set; public class NBTObjectImpl implements NBTObject { - private final NBTTagCompound compound; private final String tag; diff --git a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/world/SItemStackImpl.java b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/world/SItemStackImpl.java index 66a8e299..42948e8d 100644 --- a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/world/SItemStackImpl.java +++ b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/world/SItemStackImpl.java @@ -11,7 +11,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public class SItemStackImpl implements SItemStack { - private final ItemStack item; public SItemStackImpl(ItemStack item) { @@ -21,11 +20,14 @@ public class SItemStackImpl implements SItemStack { @Override public void breakItem(Player player, int amount) { EntityPlayer entityPlayer = ((CraftPlayer) player).getHandle(); + for (int i = 0; i < 5; ++i) { Vec3D vec3d = new Vec3D(((double) random.nextFloat() - 0.5D) * 0.1D, Math.random() * 0.1D + 0.1D, 0.0D); vec3d = vec3d.a(-entityPlayer.pitch * 0.017453292F); vec3d = vec3d.b(-entityPlayer.yaw * 0.017453292F); + double d0 = (double) (-random.nextFloat()) * 0.6D - 0.3D; + Vec3D vec3d1 = new Vec3D(((double) random.nextFloat() - 0.5D) * 0.3D, d0, 0.6D); vec3d1 = vec3d1.a(-entityPlayer.pitch * 0.017453292F); vec3d1 = vec3d1.b(-entityPlayer.yaw * 0.017453292F); diff --git a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/world/SSpawnerImpl.java b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/world/SSpawnerImpl.java index 48f8ed22..b1cbe695 100644 --- a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/world/SSpawnerImpl.java +++ b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/world/SSpawnerImpl.java @@ -21,7 +21,6 @@ import java.util.Random; import java.util.Set; public class SSpawnerImpl implements SSpawner { - private final Location spawnerLocation; public SSpawnerImpl(Location location) { @@ -36,7 +35,6 @@ public class SSpawnerImpl implements SSpawner { @Override public LivingEntity spawnEntity(EntityType type, String particleType, SpawnedEntity spawned, Set canSpawnOn) { - short spawnRange = 4; for (int i = 0; i < 50; i++) { WorldServer world = ((CraftWorld) spawnerLocation.getWorld()).getHandle(); @@ -52,8 +50,9 @@ public class SSpawnerImpl implements SSpawner { BlockPosition position = entity.getChunkCoordinates(); DifficultyDamageScaler damageScaler = world.E(position); - if (!(entity instanceof EntityInsentient)) + if (!(entity instanceof EntityInsentient)) { continue; + } EntityInsentient entityInsentient = (EntityInsentient) entity; @@ -65,14 +64,15 @@ public class SSpawnerImpl implements SSpawner { LivingEntity craftEntity = (LivingEntity) entity.getBukkitEntity(); - if (spawned != null) - if (!spawned.onSpawn(craftEntity)) - return null; + if (spawned != null && !spawned.onSpawn(craftEntity)) { + return null; + } if (particleType != null) { float xx = (float) (0 + (Math.random() * 1)); float yy = (float) (0 + (Math.random() * 2)); float zz = (float) (0 + (Math.random() * 1)); + CompatibleParticleHandler.spawnParticles(CompatibleParticleHandler.ParticleType.getParticle(particleType), spot, 5, xx, yy, zz, 0); } @@ -84,32 +84,37 @@ public class SSpawnerImpl implements SSpawner { return craftEntity; } + return null; } private boolean canSpawn(EntityInsentient entityInsentient, Location location, Set canSpawnOn) { - if (!entityInsentient.canSpawn()) + if (!entityInsentient.canSpawn()) { return false; + } CompatibleMaterial spawnedIn = CompatibleMaterial.getMaterial(location.getBlock()); CompatibleMaterial spawnedOn = CompatibleMaterial.getMaterial(location.getBlock().getRelative(BlockFace.DOWN)); - if (spawnedIn == null || spawnedOn == null) + if (spawnedIn == null || spawnedOn == null) { return false; + } - if (!spawnedIn.isAir() - && spawnedIn != CompatibleMaterial.WATER - && !spawnedIn.name().contains("PRESSURE") - && !spawnedIn.name().contains("SLAB")) { + if (!spawnedIn.isAir() && + spawnedIn != CompatibleMaterial.WATER && + !spawnedIn.name().contains("PRESSURE") && + !spawnedIn.name().contains("SLAB")) { return false; } for (CompatibleMaterial material : canSpawnOn) { if (material == null) continue; - if (spawnedOn.equals(material) || material.isAir()) + if (spawnedOn.equals(material) || material.isAir()) { return true; + } } + return false; } } diff --git a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/world/SWorldImpl.java b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/world/SWorldImpl.java index cc811416..f8430d5c 100644 --- a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/world/SWorldImpl.java +++ b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/world/SWorldImpl.java @@ -7,7 +7,6 @@ import java.util.ArrayList; import java.util.List; public class SWorldImpl implements SWorld { - public SWorldImpl() { } diff --git a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/world/WorldCoreImpl.java b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/world/WorldCoreImpl.java index a3388af5..45fcb655 100644 --- a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/world/WorldCoreImpl.java +++ b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/world/WorldCoreImpl.java @@ -56,29 +56,31 @@ public class WorldCoreImpl implements WorldCore { public void randomTickChunk(org.bukkit.Chunk bukkitChunk, int tickAmount) throws NoSuchFieldException, IllegalAccessException { Chunk chunk = ((CraftChunk) bukkitChunk).getHandle(); - if (tickAmount > 0) { - int k = chunk.locX * 16; - int l = chunk.locZ * 16; + if (tickAmount <= 0) { + return; + } - for (ChunkSection chunksection : chunk.getSections()) { - if (chunksection != null && chunksection.shouldTick()) { - for (int l1 = 0; l1 < tickAmount; ++l1) { - int m = (int) ReflectionUtils.getFieldValue(chunk.world, "m"); + int k = chunk.locX * 16; + int l = chunk.locZ * 16; - m = m * 3 + 1013904223; - ReflectionUtils.setFieldValue(chunk.world, "m", m); + for (ChunkSection chunksection : chunk.getSections()) { + if (chunksection != null && chunksection.shouldTick()) { + for (int l1 = 0; l1 < tickAmount; ++l1) { + int m = (int) ReflectionUtils.getFieldValue(chunk.world, "m"); - int i2 = m >> 2; - int j2 = i2 & 15; - int k2 = i2 >> 8 & 15; - int l2 = i2 >> 16 & 15; + m = m * 3 + 1013904223; + ReflectionUtils.setFieldValue(chunk.world, "m", m); - IBlockData iblockdata = chunksection.getType(j2, l2, k2); - Block block = iblockdata.getBlock(); + int i2 = m >> 2; + int j2 = i2 & 15; + int k2 = i2 >> 8 & 15; + int l2 = i2 >> 16 & 15; - if (block.isTicking()) { - block.a(chunk.world, new BlockPosition(j2 + k, l2 + chunksection.getYPosition(), k2 + l), iblockdata, chunk.world.random); - } + IBlockData iblockdata = chunksection.getType(j2, l2, k2); + Block block = iblockdata.getBlock(); + + if (block.isTicking()) { + block.a(chunk.world, new BlockPosition(j2 + k, l2 + chunksection.getYPosition(), k2 + l), iblockdata, chunk.world.random); } } } diff --git a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/world/spawner/BBaseSpawnerImpl.java b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/world/spawner/BBaseSpawnerImpl.java index f65e5502..096529bc 100644 --- a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/world/spawner/BBaseSpawnerImpl.java +++ b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/world/spawner/BBaseSpawnerImpl.java @@ -51,7 +51,6 @@ public class BBaseSpawnerImpl implements BBaseSpawner { */ @Override public void tick() throws NoSuchFieldException, IllegalAccessException, InvocationTargetException { - BlockPosition blockposition = spawner.b(); if (spawner.a().isClientSide) { @@ -68,68 +67,69 @@ public class BBaseSpawnerImpl implements BBaseSpawner { ReflectionUtils.setFieldValue(spawner, "f", spawnerE); ReflectionUtils.setFieldValue(spawner, "e", (spawnerE + (double) (1000F / ((float) spawner.spawnDelay + 200F))) % 360D); - } else { - if (spawner.spawnDelay == -1) { - delay(spawner); + return; + } + + if (spawner.spawnDelay == -1) { + delay(spawner); + } + + if (spawner.spawnDelay > 0) { + --spawner.spawnDelay; + return; + } + + boolean flag = false; + int i = 0; + + int spawnCount = (int) ReflectionUtils.getFieldValue(spawner, "spawnCount"); + int spawnRange = (int) ReflectionUtils.getFieldValue(spawner, "spawnRange"); + int maxNearbyEntities = (int) ReflectionUtils.getFieldValue(spawner, "maxNearbyEntities"); + + while (true) { + if (i >= spawnCount) { + if (flag) { + delay(spawner); + } + break; } - if (spawner.spawnDelay > 0) { - --spawner.spawnDelay; + Entity entity = EntityTypes.createEntityByName(spawner.getMobName(), spawner.a()); + if (entity == null) { return; } - boolean flag = false; - int i = 0; - - int spawnCount = (int) ReflectionUtils.getFieldValue(spawner, "spawnCount"); - int spawnRange = (int) ReflectionUtils.getFieldValue(spawner, "spawnRange"); - int maxNearbyEntities = (int) ReflectionUtils.getFieldValue(spawner, "maxNearbyEntities"); - - while (true) { - if (i >= spawnCount) { - if (flag) { - delay(spawner); - } - break; - } - - Entity entity = EntityTypes.createEntityByName(spawner.getMobName(), spawner.a()); - if (entity == null) { - return; - } - - int j = spawner.a().a(entity.getClass(), (new AxisAlignedBB( - blockposition.getX(), - blockposition.getY(), - blockposition.getZ(), - blockposition.getX() + 1, - blockposition.getY() + 1, - blockposition.getZ() + 1)) - .grow(spawnRange, spawnRange, spawnRange)).size(); - if (j >= maxNearbyEntities) { - delay(spawner); - return; - } - - double d0 = (double) blockposition.getX() + (spawner.a().random.nextDouble() - spawner.a().random.nextDouble()) * (double) spawnRange + .5D; - double d3 = blockposition.getY() + spawner.a().random.nextInt(3) - 1; - double d4 = (double) blockposition.getZ() + (spawner.a().random.nextDouble() - spawner.a().random.nextDouble()) * (double) spawnRange + .5D; - - EntityInsentient entityinsentient = entity instanceof EntityInsentient ? (EntityInsentient) entity : null; - entity.setPositionRotation(d0, d3, d4, spawner.a().random.nextFloat() * 360F, 0F); - - if (entityinsentient == null || entityinsentient.bR() && entityinsentient.canSpawn()) { - aEntityBooleanMethod.invoke(spawner, entity, true); - spawner.a().triggerEffect(2004, blockposition, 0); - if (entityinsentient != null) { - entityinsentient.y(); - } - - flag = true; - } - - ++i; + int j = spawner.a().a(entity.getClass(), (new AxisAlignedBB( + blockposition.getX(), + blockposition.getY(), + blockposition.getZ(), + blockposition.getX() + 1, + blockposition.getY() + 1, + blockposition.getZ() + 1)) + .grow(spawnRange, spawnRange, spawnRange)).size(); + if (j >= maxNearbyEntities) { + delay(spawner); + return; } + + double d0 = (double) blockposition.getX() + (spawner.a().random.nextDouble() - spawner.a().random.nextDouble()) * (double) spawnRange + .5D; + double d3 = blockposition.getY() + spawner.a().random.nextInt(3) - 1; + double d4 = (double) blockposition.getZ() + (spawner.a().random.nextDouble() - spawner.a().random.nextDouble()) * (double) spawnRange + .5D; + + EntityInsentient entityinsentient = entity instanceof EntityInsentient ? (EntityInsentient) entity : null; + entity.setPositionRotation(d0, d3, d4, spawner.a().random.nextFloat() * 360F, 0F); + + if (entityinsentient == null || entityinsentient.bR() && entityinsentient.canSpawn()) { + aEntityBooleanMethod.invoke(spawner, entity, true); + spawner.a().triggerEffect(2004, blockposition, 0); + if (entityinsentient != null) { + entityinsentient.y(); + } + + flag = true; + } + + ++i; } } @@ -140,4 +140,4 @@ public class BBaseSpawnerImpl implements BBaseSpawner { private void delay(MobSpawnerAbstract spawner) throws InvocationTargetException, IllegalAccessException { hMethod.invoke(spawner); } -} \ No newline at end of file +} diff --git a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/anvil/AnvilCore.java b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/anvil/AnvilCore.java index b0b3e7c4..1ab175e6 100644 --- a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/anvil/AnvilCore.java +++ b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/anvil/AnvilCore.java @@ -6,7 +6,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; public class AnvilCore implements com.songoda.core.nms.anvil.AnvilCore { - @Override public CustomAnvil createAnvil(Player player) { return new AnvilView(((CraftPlayer) player).getHandle(), null); diff --git a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/anvil/AnvilInventoryCustom.java b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/anvil/AnvilInventoryCustom.java index d6b06b06..ad931389 100644 --- a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/anvil/AnvilInventoryCustom.java +++ b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/anvil/AnvilInventoryCustom.java @@ -6,11 +6,11 @@ import org.bukkit.craftbukkit.v1_9_R1.inventory.CraftInventoryAnvil; import org.bukkit.inventory.InventoryHolder; public class AnvilInventoryCustom extends CraftInventoryAnvil { - final InventoryHolder holder; public AnvilInventoryCustom(InventoryHolder holder, Location location, IInventory inventory, IInventory resultInventory) { super(location, inventory, resultInventory); + this.holder = holder; } diff --git a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/anvil/AnvilView.java b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/anvil/AnvilView.java index 6a11d64a..f2f575c0 100644 --- a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/anvil/AnvilView.java +++ b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/anvil/AnvilView.java @@ -20,7 +20,6 @@ import java.util.logging.Level; import java.util.logging.Logger; public class AnvilView extends ContainerAnvil implements CustomAnvil { - private final EntityPlayer entity; private final Inventory inventory; private String title = "Repairing"; @@ -37,8 +36,10 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { try { mc_ContainerAnvil_repairInventory = ContainerAnvil.class.getDeclaredField("h"); mc_ContainerAnvil_repairInventory.setAccessible(true); + mc_ContainerAnvil_resultInventory = ContainerAnvil.class.getDeclaredField("g"); mc_ContainerAnvil_resultInventory.setAccessible(true); + mc_ContainerAnvil_bukkitEntity = ContainerAnvil.class.getDeclaredField("bukkitEntity"); mc_ContainerAnvil_bukkitEntity.setAccessible(true); } catch (Exception ex) { @@ -61,11 +62,13 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { public AnvilView(EntityPlayer entity, InventoryHolder holder) { super(entity.inventory, entity.world, new BlockPosition(0, 0, 0), entity); this.entity = entity; + if (holder != null) { this.inventory = getBukkitView(entity, holder).getTopInventory(); - } else { - this.inventory = getBukkitView().getTopInventory(); + return; } + + this.inventory = getBukkitView().getTopInventory(); } public CraftInventoryView getBukkitView(EntityHuman player, InventoryHolder holder) { @@ -91,6 +94,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void e() { super.e(); + if (cost >= 0) { this.a = cost; } @@ -109,6 +113,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { } catch (Exception ex) { Logger.getLogger(AnvilView.class.getName()).log(Level.SEVERE, "Anvil Error", ex); } + return null; } @@ -184,7 +189,6 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void open() { - // Counter stuff that the game uses to keep track of inventories int id = entity.nextContainerCounter(); diff --git a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/nbt/NBTCompoundImpl.java b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/nbt/NBTCompoundImpl.java index f0e71d77..659dc034 100644 --- a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/nbt/NBTCompoundImpl.java +++ b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/nbt/NBTCompoundImpl.java @@ -15,7 +15,6 @@ import java.util.Set; import java.util.UUID; public class NBTCompoundImpl implements NBTCompound { - protected NBTTagCompound compound; protected NBTCompoundImpl(NBTTagCompound compound) { @@ -151,11 +150,11 @@ public class NBTCompoundImpl implements NBTCompound { public NBTCompound getCompound(String tag) { if (has(tag)) { return getNBTObject(tag).asCompound(); - } else { - NBTTagCompound newCompound = new NBTTagCompound(); - compound.set(tag, newCompound); - return new NBTCompoundImpl(newCompound); } + + NBTTagCompound newCompound = new NBTTagCompound(); + compound.set(tag, newCompound); + return new NBTCompoundImpl(newCompound); } @Override @@ -181,9 +180,10 @@ public class NBTCompoundImpl implements NBTCompound { NBTCompressedStreamTools.a(compound, (OutputStream) dataOutput); return outputStream.toByteArray(); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } + return null; } @@ -192,8 +192,8 @@ public class NBTCompoundImpl implements NBTCompound { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(serialized); ObjectInputStream dataInput = new ObjectInputStream(inputStream)) { compound = NBTCompressedStreamTools.a((InputStream) dataInput); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } } diff --git a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/nbt/NBTCoreImpl.java b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/nbt/NBTCoreImpl.java index 01dc2338..6d07a9a8 100644 --- a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/nbt/NBTCoreImpl.java +++ b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/nbt/NBTCoreImpl.java @@ -10,7 +10,6 @@ import org.bukkit.entity.Entity; import org.bukkit.inventory.ItemStack; public class NBTCoreImpl implements NBTCore { - @Override public NBTItem of(ItemStack item) { return new NBTItemImpl(CraftItemStack.asNMSCopy(item)); @@ -26,6 +25,7 @@ public class NBTCoreImpl implements NBTCore { net.minecraft.server.v1_9_R1.Entity nmsEntity = ((CraftEntity) entity).getHandle(); NBTTagCompound nbt = new NBTTagCompound(); nmsEntity.e(nbt); // Method name changed in 1.11 + return new NBTEntityImpl(nbt, nmsEntity); } diff --git a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/nbt/NBTEntityImpl.java b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/nbt/NBTEntityImpl.java index e363e858..f5341176 100644 --- a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/nbt/NBTEntityImpl.java +++ b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/nbt/NBTEntityImpl.java @@ -10,11 +10,11 @@ import org.bukkit.craftbukkit.v1_9_R1.CraftWorld; import org.bukkit.event.entity.CreatureSpawnEvent; public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { - private Entity nmsEntity; public NBTEntityImpl(NBTTagCompound entityNBT, Entity nmsEntity) { super(entityNBT); + this.nmsEntity = nmsEntity; } @@ -35,8 +35,10 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { spawned.setLocation(location.getX(), location.getY(), location.getZ(), location.getPitch(), location.getYaw()); nmsEntity = spawned; + return entity; } + return null; } @@ -49,7 +51,9 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { @Override public void addExtras() { String key = EntityTypes.b(nmsEntity); // Changed in 1.12 - if (key != null) + + if (key != null) { compound.setString("entity_type", key); // Changed in 1.13 + } } } diff --git a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/nbt/NBTItemImpl.java b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/nbt/NBTItemImpl.java index 701630de..181f423a 100644 --- a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/nbt/NBTItemImpl.java @@ -6,20 +6,20 @@ import org.bukkit.craftbukkit.v1_9_R1.inventory.CraftItemStack; import org.bukkit.inventory.ItemStack; public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { - private final net.minecraft.server.v1_9_R1.ItemStack nmsItem; public NBTItemImpl(net.minecraft.server.v1_9_R1.ItemStack nmsItem) { super(nmsItem != null && nmsItem.hasTag() ? nmsItem.getTag() : new NBTTagCompound()); + this.nmsItem = nmsItem; } public ItemStack finish() { if (nmsItem == null) { return CraftItemStack.asBukkitCopy(net.minecraft.server.v1_9_R1.ItemStack.createStack(compound)); - } else { - return CraftItemStack.asBukkitCopy(nmsItem); } + + return CraftItemStack.asBukkitCopy(nmsItem); } @Override diff --git a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/nbt/NBTObjectImpl.java b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/nbt/NBTObjectImpl.java index 7af6dab3..cd9b9596 100644 --- a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/nbt/NBTObjectImpl.java +++ b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/nbt/NBTObjectImpl.java @@ -7,7 +7,6 @@ import net.minecraft.server.v1_9_R1.NBTTagCompound; import java.util.Set; public class NBTObjectImpl implements NBTObject { - private final NBTTagCompound compound; private final String tag; diff --git a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/world/SItemStackImpl.java b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/world/SItemStackImpl.java index 097cc6d6..7fe84c62 100644 --- a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/world/SItemStackImpl.java +++ b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/world/SItemStackImpl.java @@ -11,7 +11,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public class SItemStackImpl implements SItemStack { - private final ItemStack item; public SItemStackImpl(ItemStack item) { @@ -21,11 +20,14 @@ public class SItemStackImpl implements SItemStack { @Override public void breakItem(Player player, int amount) { EntityPlayer entityPlayer = ((CraftPlayer) player).getHandle(); + for (int i = 0; i < 5; ++i) { Vec3D vec3d = new Vec3D(((double) random.nextFloat() - 0.5D) * 0.1D, Math.random() * 0.1D + 0.1D, 0.0D); vec3d = vec3d.a(-entityPlayer.pitch * 0.017453292F); vec3d = vec3d.b(-entityPlayer.yaw * 0.017453292F); + double d0 = (double) (-random.nextFloat()) * 0.6D - 0.3D; + Vec3D vec3d1 = new Vec3D(((double) random.nextFloat() - 0.5D) * 0.3D, d0, 0.6D); vec3d1 = vec3d1.a(-entityPlayer.pitch * 0.017453292F); vec3d1 = vec3d1.b(-entityPlayer.yaw * 0.017453292F); diff --git a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/world/SSpawnerImpl.java b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/world/SSpawnerImpl.java index 9752efe7..a9559f43 100644 --- a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/world/SSpawnerImpl.java +++ b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/world/SSpawnerImpl.java @@ -23,7 +23,6 @@ import java.util.Random; import java.util.Set; public class SSpawnerImpl implements SSpawner { - private final Location spawnerLocation; public SSpawnerImpl(Location location) { @@ -38,7 +37,6 @@ public class SSpawnerImpl implements SSpawner { @Override public LivingEntity spawnEntity(EntityType type, String particleType, SpawnedEntity spawned, Set canSpawnOn) { - MobSpawnerData data = new MobSpawnerData(); NBTTagCompound compound = data.b(); @@ -58,22 +56,24 @@ public class SSpawnerImpl implements SSpawner { BlockPosition position = entity.getChunkCoordinates(); DifficultyDamageScaler damageScaler = world.D(position); - if (!(entity instanceof EntityInsentient)) + if (!(entity instanceof EntityInsentient)) { continue; + } EntityInsentient entityInsentient = (EntityInsentient) entity; Location spot = new Location(spawnerLocation.getWorld(), x, y, z); - if (!canSpawn(entityInsentient, spot, canSpawnOn)) + if (!canSpawn(entityInsentient, spot, canSpawnOn)) { continue; + } entityInsentient.prepare(damageScaler, null); LivingEntity craftEntity = (LivingEntity) entity.getBukkitEntity(); - if (spawned != null) - if (!spawned.onSpawn(craftEntity)) - return null; + if (spawned != null && !spawned.onSpawn(craftEntity)) { + return null; + } if (particleType != null) { float xx = (float) (0 + (Math.random() * 1)); @@ -90,32 +90,37 @@ public class SSpawnerImpl implements SSpawner { return craftEntity; } + return null; } private boolean canSpawn(EntityInsentient entityInsentient, Location location, Set canSpawnOn) { - if (!entityInsentient.canSpawn()) + if (!entityInsentient.canSpawn()) { return false; + } CompatibleMaterial spawnedIn = CompatibleMaterial.getMaterial(location.getBlock()); CompatibleMaterial spawnedOn = CompatibleMaterial.getMaterial(location.getBlock().getRelative(BlockFace.DOWN)); - if (spawnedIn == null || spawnedOn == null) + if (spawnedIn == null || spawnedOn == null) { return false; + } - if (!spawnedIn.isAir() - && spawnedIn != CompatibleMaterial.WATER - && !spawnedIn.name().contains("PRESSURE") - && !spawnedIn.name().contains("SLAB")) { + if (!spawnedIn.isAir() && + spawnedIn != CompatibleMaterial.WATER && + !spawnedIn.name().contains("PRESSURE") && + !spawnedIn.name().contains("SLAB")) { return false; } for (CompatibleMaterial material : canSpawnOn) { if (material == null) continue; - if (spawnedOn.equals(material) || material.isAir()) + if (spawnedOn.equals(material) || material.isAir()) { return true; + } } + return false; } } diff --git a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/world/SWorldImpl.java b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/world/SWorldImpl.java index 50a61171..fdfe63fa 100644 --- a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/world/SWorldImpl.java +++ b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/world/SWorldImpl.java @@ -7,7 +7,6 @@ import java.util.ArrayList; import java.util.List; public class SWorldImpl implements SWorld { - public SWorldImpl() { } diff --git a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/world/WorldCoreImpl.java b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/world/WorldCoreImpl.java index bacf9a37..66c3e421 100644 --- a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/world/WorldCoreImpl.java +++ b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/world/WorldCoreImpl.java @@ -56,29 +56,31 @@ public class WorldCoreImpl implements WorldCore { public void randomTickChunk(org.bukkit.Chunk bukkitChunk, int tickAmount) throws NoSuchFieldException, IllegalAccessException { Chunk chunk = ((CraftChunk) bukkitChunk).getHandle(); - if (tickAmount > 0) { - int j = chunk.locX * 16; - int k = chunk.locZ * 16; + if (tickAmount <= 0) { + return; + } - for (ChunkSection chunksection : chunk.getSections()) { - if (chunksection != net.minecraft.server.v1_9_R1.Chunk.a && chunksection.shouldTick()) { - for (int i = 0; i < tickAmount; ++i) { - int worldL = (int) ReflectionUtils.getFieldValue(chunk.world, "l"); + int j = chunk.locX * 16; + int k = chunk.locZ * 16; - worldL = worldL * 3 + 1013904223; - ReflectionUtils.setFieldValue(chunk.world, "l", worldL); + for (ChunkSection chunksection : chunk.getSections()) { + if (chunksection != net.minecraft.server.v1_9_R1.Chunk.a && chunksection.shouldTick()) { + for (int i = 0; i < tickAmount; ++i) { + int worldL = (int) ReflectionUtils.getFieldValue(chunk.world, "l"); - int l1 = worldL >> 2; - int i2 = l1 & 15; - int j2 = l1 >> 8 & 15; - int k2 = l1 >> 16 & 15; + worldL = worldL * 3 + 1013904223; + ReflectionUtils.setFieldValue(chunk.world, "l", worldL); - IBlockData iblockdata = chunksection.getType(i2, k2, j2); - Block block = iblockdata.getBlock(); + int l1 = worldL >> 2; + int i2 = l1 & 15; + int j2 = l1 >> 8 & 15; + int k2 = l1 >> 16 & 15; - if (block.isTicking()) { - block.a(chunk.world, new BlockPosition(i2 + j, k2 + chunksection.getYPosition(), j2 + k), iblockdata, chunk.world.random); - } + IBlockData iblockdata = chunksection.getType(i2, k2, j2); + Block block = iblockdata.getBlock(); + + if (block.isTicking()) { + block.a(chunk.world, new BlockPosition(i2 + j, k2 + chunksection.getYPosition(), j2 + k), iblockdata, chunk.world.random); } } } diff --git a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/world/spawner/BBaseSpawnerImpl.java b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/world/spawner/BBaseSpawnerImpl.java index da587db1..bb8da244 100644 --- a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/world/spawner/BBaseSpawnerImpl.java +++ b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/world/spawner/BBaseSpawnerImpl.java @@ -54,6 +54,7 @@ public class BBaseSpawnerImpl implements BBaseSpawner { @Override public void tick() throws NoSuchFieldException, IllegalAccessException, InvocationTargetException { BlockPosition blockposition = spawner.b(); + if (spawner.a().isClientSide) { double d0 = (float) blockposition.getX() + spawner.a().random.nextFloat(); double d1 = (float) blockposition.getY() + spawner.a().random.nextFloat(); @@ -68,81 +69,83 @@ public class BBaseSpawnerImpl implements BBaseSpawner { ReflectionUtils.setFieldValue(spawner, "e", spawnerD); ReflectionUtils.setFieldValue(spawner, "d", (spawnerD + (double) (1000F / ((float) spawner.spawnDelay + 200F))) % 360D); - } else { - if (spawner.spawnDelay == -1) { - delay(spawner); + return; + } + + if (spawner.spawnDelay == -1) { + delay(spawner); + } + + if (spawner.spawnDelay > 0) { + --spawner.spawnDelay; + return; + } + + boolean flag = false; + int i = 0; + + int spawnCount = (int) ReflectionUtils.getFieldValue(spawner, "spawnCount"); + int spawnRange = (int) ReflectionUtils.getFieldValue(spawner, "spawnRange"); + int maxNearbyEntities = (int) ReflectionUtils.getFieldValue(spawner, "maxNearbyEntities"); + MobSpawnerData spawnData = (MobSpawnerData) ReflectionUtils.getFieldValue(spawner, "spawnData"); + + while (true) { + if (i >= spawnCount) { + if (flag) { + delay(spawner); + } + + break; } - if (spawner.spawnDelay > 0) { - --spawner.spawnDelay; + NBTTagCompound nbttagcompound = spawnData.b(); + NBTTagList nbttaglist = nbttagcompound.getList("Pos", 6); + net.minecraft.server.v1_9_R1.World world = spawner.a(); + int j = nbttaglist.size(); + double d3 = j >= 1 ? nbttaglist.e(0) : (double) blockposition.getX() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawnRange + .5D; + double d4 = j >= 2 ? nbttaglist.e(1) : (double) (blockposition.getY() + world.random.nextInt(3) - 1); + double d5 = j >= 3 ? nbttaglist.e(2) : (double) blockposition.getZ() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawnRange + .5D; + Entity entity = ChunkRegionLoader.a(nbttagcompound, world, d3, d4, d5, false); + if (entity == null) { return; } - boolean flag = false; - int i = 0; - - int spawnCount = (int) ReflectionUtils.getFieldValue(spawner, "spawnCount"); - int spawnRange = (int) ReflectionUtils.getFieldValue(spawner, "spawnRange"); - int maxNearbyEntities = (int) ReflectionUtils.getFieldValue(spawner, "maxNearbyEntities"); - MobSpawnerData spawnData = (MobSpawnerData) ReflectionUtils.getFieldValue(spawner, "spawnData"); - - while (true) { - if (i >= spawnCount) { - if (flag) { - delay(spawner); - } - break; - } - - NBTTagCompound nbttagcompound = spawnData.b(); - NBTTagList nbttaglist = nbttagcompound.getList("Pos", 6); - net.minecraft.server.v1_9_R1.World world = spawner.a(); - int j = nbttaglist.size(); - double d3 = j >= 1 ? nbttaglist.e(0) : (double) blockposition.getX() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawnRange + .5D; - double d4 = j >= 2 ? nbttaglist.e(1) : (double) (blockposition.getY() + world.random.nextInt(3) - 1); - double d5 = j >= 3 ? nbttaglist.e(2) : (double) blockposition.getZ() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawnRange + .5D; - Entity entity = ChunkRegionLoader.a(nbttagcompound, world, d3, d4, d5, false); - if (entity == null) { - return; - } - - int k = world.a(entity.getClass(), (new AxisAlignedBB( - blockposition.getX(), - blockposition.getY(), - blockposition.getZ(), - blockposition.getX() + 1, - blockposition.getY() + 1, - blockposition.getZ() + 1)) - .g(spawnRange)).size(); - if (k >= maxNearbyEntities) { - delay(spawner); - return; - } - - EntityInsentient entityinsentient = entity instanceof EntityInsentient ? (EntityInsentient) entity : null; - entity.setPositionRotation(entity.locX, entity.locY, entity.locZ, world.random.nextFloat() * 360F, 0F); - if (entityinsentient == null || entityinsentient.cF() && entityinsentient.canSpawn()) { - if (spawnData.b().d() == 1 && spawnData.b().hasKeyOfType("id", 8) && entity instanceof EntityInsentient) { - ((EntityInsentient) entity).prepare(world.D(new BlockPosition(entity)), null); - } - - if (entity.world.spigotConfig.nerfSpawnerMobs) { - entity.fromMobSpawner = true; - } - - if (!CraftEventFactory.callSpawnerSpawnEvent(entity, blockposition).isCancelled()) { - ChunkRegionLoader.a(entity, world, CreatureSpawnEvent.SpawnReason.SPAWNER); - world.triggerEffect(2004, blockposition, 0); - if (entityinsentient != null) { - entityinsentient.doSpawnEffect(); - } - - flag = true; - } - } - - ++i; + int k = world.a(entity.getClass(), (new AxisAlignedBB( + blockposition.getX(), + blockposition.getY(), + blockposition.getZ(), + blockposition.getX() + 1, + blockposition.getY() + 1, + blockposition.getZ() + 1)) + .g(spawnRange)).size(); + if (k >= maxNearbyEntities) { + delay(spawner); + return; } + + EntityInsentient entityinsentient = entity instanceof EntityInsentient ? (EntityInsentient) entity : null; + entity.setPositionRotation(entity.locX, entity.locY, entity.locZ, world.random.nextFloat() * 360F, 0F); + if (entityinsentient == null || entityinsentient.cF() && entityinsentient.canSpawn()) { + if (spawnData.b().d() == 1 && spawnData.b().hasKeyOfType("id", 8) && entity instanceof EntityInsentient) { + ((EntityInsentient) entity).prepare(world.D(new BlockPosition(entity)), null); + } + + if (entity.world.spigotConfig.nerfSpawnerMobs) { + entity.fromMobSpawner = true; + } + + if (!CraftEventFactory.callSpawnerSpawnEvent(entity, blockposition).isCancelled()) { + ChunkRegionLoader.a(entity, world, CreatureSpawnEvent.SpawnReason.SPAWNER); + world.triggerEffect(2004, blockposition, 0); + if (entityinsentient != null) { + entityinsentient.doSpawnEffect(); + } + + flag = true; + } + } + + ++i; } } @@ -153,4 +156,4 @@ public class BBaseSpawnerImpl implements BBaseSpawner { private void delay(MobSpawnerAbstract spawner) throws InvocationTargetException, IllegalAccessException { iMethod.invoke(spawner); } -} \ No newline at end of file +} diff --git a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/anvil/AnvilCore.java b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/anvil/AnvilCore.java index 76ed1882..b2e73c35 100644 --- a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/anvil/AnvilCore.java +++ b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/anvil/AnvilCore.java @@ -6,7 +6,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; public class AnvilCore implements com.songoda.core.nms.anvil.AnvilCore { - @Override public CustomAnvil createAnvil(Player player) { return new AnvilView(((CraftPlayer) player).getHandle(), null); diff --git a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/anvil/AnvilInventoryCustom.java b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/anvil/AnvilInventoryCustom.java index 77392cb6..38f3704e 100644 --- a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/anvil/AnvilInventoryCustom.java +++ b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/anvil/AnvilInventoryCustom.java @@ -6,7 +6,6 @@ import org.bukkit.craftbukkit.v1_9_R2.inventory.CraftInventoryAnvil; import org.bukkit.inventory.InventoryHolder; public class AnvilInventoryCustom extends CraftInventoryAnvil { - final InventoryHolder holder; public AnvilInventoryCustom(InventoryHolder holder, Location location, IInventory inventory, IInventory resultInventory) { diff --git a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/anvil/AnvilView.java b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/anvil/AnvilView.java index fd0c4d09..3602392a 100644 --- a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/anvil/AnvilView.java +++ b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/anvil/AnvilView.java @@ -20,7 +20,6 @@ import java.util.logging.Level; import java.util.logging.Logger; public class AnvilView extends ContainerAnvil implements CustomAnvil { - private final EntityPlayer entity; private final Inventory inventory; private String title = "Repairing"; @@ -37,8 +36,10 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { try { mc_ContainerAnvil_repairInventory = ContainerAnvil.class.getDeclaredField("h"); mc_ContainerAnvil_repairInventory.setAccessible(true); + mc_ContainerAnvil_resultInventory = ContainerAnvil.class.getDeclaredField("g"); mc_ContainerAnvil_resultInventory.setAccessible(true); + mc_ContainerAnvil_bukkitEntity = ContainerAnvil.class.getDeclaredField("bukkitEntity"); mc_ContainerAnvil_bukkitEntity.setAccessible(true); } catch (Exception ex) { @@ -60,12 +61,15 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { public AnvilView(EntityPlayer entity, InventoryHolder holder) { super(entity.inventory, entity.world, new BlockPosition(0, 0, 0), entity); + this.entity = entity; + if (holder != null) { this.inventory = getBukkitView(entity, holder).getTopInventory(); - } else { - this.inventory = getBukkitView().getTopInventory(); + return; } + + this.inventory = getBukkitView().getTopInventory(); } public CraftInventoryView getBukkitView(EntityHuman player, InventoryHolder holder) { @@ -76,10 +80,12 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { (IInventory) mc_ContainerAnvil_resultInventory.get(this)); CraftInventoryView view = new CraftInventoryView(player.getBukkitEntity(), craftInventory, this); mc_ContainerAnvil_bukkitEntity.set(this, view); + return view; } catch (Exception ex) { Logger.getLogger(AnvilView.class.getName()).log(Level.SEVERE, "Anvil Setup Error", ex); } + return getBukkitView(); } @@ -91,6 +97,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void e() { super.e(); + if (cost >= 0) { this.a = cost; } @@ -109,6 +116,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { } catch (Exception ex) { Logger.getLogger(AnvilView.class.getName()).log(Level.SEVERE, "Anvil Error", ex); } + return null; } @@ -184,7 +192,6 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { @Override public void open() { - // Counter stuff that the game uses to keep track of inventories int id = entity.nextContainerCounter(); diff --git a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/nbt/NBTCompoundImpl.java b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/nbt/NBTCompoundImpl.java index 76d51382..784cdc64 100644 --- a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/nbt/NBTCompoundImpl.java +++ b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/nbt/NBTCompoundImpl.java @@ -15,7 +15,6 @@ import java.util.Set; import java.util.UUID; public class NBTCompoundImpl implements NBTCompound { - protected NBTTagCompound compound; protected NBTCompoundImpl(NBTTagCompound compound) { @@ -151,11 +150,11 @@ public class NBTCompoundImpl implements NBTCompound { public NBTCompound getCompound(String tag) { if (has(tag)) { return getNBTObject(tag).asCompound(); - } else { - NBTTagCompound newCompound = new NBTTagCompound(); - compound.set(tag, newCompound); - return new NBTCompoundImpl(newCompound); } + + NBTTagCompound newCompound = new NBTTagCompound(); + compound.set(tag, newCompound); + return new NBTCompoundImpl(newCompound); } @Override @@ -175,15 +174,17 @@ public class NBTCompoundImpl implements NBTCompound { addExtras(); NBTTagCompound compound = (NBTTagCompound) this.compound.clone(); // Changed in 1.12 // Changed in 1.9.4 - for (String exclusion : exclusions) + for (String exclusion : exclusions) { compound.remove(exclusion); + } NBTCompressedStreamTools.a(compound, (OutputStream) dataOutput); return outputStream.toByteArray(); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } + return null; } @@ -192,8 +193,8 @@ public class NBTCompoundImpl implements NBTCompound { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(serialized); ObjectInputStream dataInput = new ObjectInputStream(inputStream)) { compound = NBTCompressedStreamTools.a((InputStream) dataInput); - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } } diff --git a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/nbt/NBTCoreImpl.java b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/nbt/NBTCoreImpl.java index dcf38406..2541d993 100644 --- a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/nbt/NBTCoreImpl.java +++ b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/nbt/NBTCoreImpl.java @@ -10,7 +10,6 @@ import org.bukkit.entity.Entity; import org.bukkit.inventory.ItemStack; public class NBTCoreImpl implements NBTCore { - @Override public NBTItem of(ItemStack item) { return new NBTItemImpl(CraftItemStack.asNMSCopy(item)); @@ -26,6 +25,7 @@ public class NBTCoreImpl implements NBTCore { net.minecraft.server.v1_9_R2.Entity nmsEntity = ((CraftEntity) entity).getHandle(); NBTTagCompound nbt = new NBTTagCompound(); nmsEntity.e(nbt); // Method name changed in 1.11 + return new NBTEntityImpl(nbt, nmsEntity); } diff --git a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/nbt/NBTEntityImpl.java b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/nbt/NBTEntityImpl.java index 776556b7..5c705453 100644 --- a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/nbt/NBTEntityImpl.java +++ b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/nbt/NBTEntityImpl.java @@ -10,11 +10,11 @@ import org.bukkit.craftbukkit.v1_9_R2.CraftWorld; import org.bukkit.event.entity.CreatureSpawnEvent; public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { - private Entity nmsEntity; public NBTEntityImpl(NBTTagCompound entityNBT, Entity nmsEntity) { super(entityNBT); + this.nmsEntity = nmsEntity; } @@ -35,8 +35,10 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { spawned.setLocation(location.getX(), location.getY(), location.getZ(), location.getPitch(), location.getYaw()); nmsEntity = spawned; + return entity; } + return null; } @@ -49,7 +51,9 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { @Override public void addExtras() { String key = EntityTypes.b(nmsEntity); // Changed in 1.12 - if (key != null) + + if (key != null) { compound.setString("entity_type", key); // Changed in 1.13 + } } } diff --git a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/nbt/NBTItemImpl.java b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/nbt/NBTItemImpl.java index fedf0fe6..d4309ca7 100644 --- a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/nbt/NBTItemImpl.java @@ -6,20 +6,20 @@ import org.bukkit.craftbukkit.v1_9_R2.inventory.CraftItemStack; import org.bukkit.inventory.ItemStack; public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { - private final net.minecraft.server.v1_9_R2.ItemStack nmsItem; public NBTItemImpl(net.minecraft.server.v1_9_R2.ItemStack nmsItem) { super(nmsItem != null && nmsItem.hasTag() ? nmsItem.getTag() : new NBTTagCompound()); + this.nmsItem = nmsItem; } public ItemStack finish() { if (nmsItem == null) { return CraftItemStack.asBukkitCopy(net.minecraft.server.v1_9_R2.ItemStack.createStack(compound)); - } else { - return CraftItemStack.asBukkitCopy(nmsItem); } + + return CraftItemStack.asBukkitCopy(nmsItem); } @Override diff --git a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/nbt/NBTObjectImpl.java b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/nbt/NBTObjectImpl.java index 5e2e339c..d9ddf95b 100644 --- a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/nbt/NBTObjectImpl.java +++ b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/nbt/NBTObjectImpl.java @@ -7,7 +7,6 @@ import net.minecraft.server.v1_9_R2.NBTTagCompound; import java.util.Set; public class NBTObjectImpl implements NBTObject { - private final NBTTagCompound compound; private final String tag; diff --git a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/world/SItemStackImpl.java b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/world/SItemStackImpl.java index c08d8446..859238b6 100644 --- a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/world/SItemStackImpl.java +++ b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/world/SItemStackImpl.java @@ -11,7 +11,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public class SItemStackImpl implements SItemStack { - private final ItemStack item; public SItemStackImpl(ItemStack item) { @@ -21,11 +20,14 @@ public class SItemStackImpl implements SItemStack { @Override public void breakItem(Player player, int amount) { EntityPlayer entityPlayer = ((CraftPlayer) player).getHandle(); + for (int i = 0; i < 5; ++i) { Vec3D vec3d = new Vec3D(((double) random.nextFloat() - 0.5D) * 0.1D, Math.random() * 0.1D + 0.1D, 0.0D); vec3d = vec3d.a(-entityPlayer.pitch * 0.017453292F); vec3d = vec3d.b(-entityPlayer.yaw * 0.017453292F); + double d0 = (double) (-random.nextFloat()) * 0.6D - 0.3D; + Vec3D vec3d1 = new Vec3D(((double) random.nextFloat() - 0.5D) * 0.3D, d0, 0.6D); vec3d1 = vec3d1.a(-entityPlayer.pitch * 0.017453292F); vec3d1 = vec3d1.b(-entityPlayer.yaw * 0.017453292F); diff --git a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/world/SSpawnerImpl.java b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/world/SSpawnerImpl.java index fab9234b..c4c78fc3 100644 --- a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/world/SSpawnerImpl.java +++ b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/world/SSpawnerImpl.java @@ -23,7 +23,6 @@ import java.util.Random; import java.util.Set; public class SSpawnerImpl implements SSpawner { - private final Location spawnerLocation; public SSpawnerImpl(Location location) { @@ -38,7 +37,6 @@ public class SSpawnerImpl implements SSpawner { @Override public LivingEntity spawnEntity(EntityType type, String particleType, SpawnedEntity spawned, Set canSpawnOn) { - MobSpawnerData data = new MobSpawnerData(); NBTTagCompound compound = data.b(); @@ -58,27 +56,30 @@ public class SSpawnerImpl implements SSpawner { BlockPosition position = entity.getChunkCoordinates(); DifficultyDamageScaler damageScaler = world.D(position); - if (!(entity instanceof EntityInsentient)) + if (!(entity instanceof EntityInsentient)) { continue; + } EntityInsentient entityInsentient = (EntityInsentient) entity; Location spot = new Location(spawnerLocation.getWorld(), x, y, z); - if (!canSpawn(entityInsentient, spot, canSpawnOn)) + if (!canSpawn(entityInsentient, spot, canSpawnOn)) { continue; + } entityInsentient.prepare(damageScaler, null); LivingEntity craftEntity = (LivingEntity) entity.getBukkitEntity(); - if (spawned != null) - if (!spawned.onSpawn(craftEntity)) - return null; + if (spawned != null && !spawned.onSpawn(craftEntity)) { + return null; + } if (particleType != null) { float xx = (float) (0 + (Math.random() * 1)); float yy = (float) (0 + (Math.random() * 2)); float zz = (float) (0 + (Math.random() * 1)); + CompatibleParticleHandler.spawnParticles(CompatibleParticleHandler.ParticleType.getParticle(particleType), spot, 5, xx, yy, zz, 0); } @@ -90,32 +91,37 @@ public class SSpawnerImpl implements SSpawner { return craftEntity; } + return null; } private boolean canSpawn(EntityInsentient entityInsentient, Location location, Set canSpawnOn) { - if (!entityInsentient.canSpawn()) + if (!entityInsentient.canSpawn()) { return false; + } CompatibleMaterial spawnedIn = CompatibleMaterial.getMaterial(location.getBlock()); CompatibleMaterial spawnedOn = CompatibleMaterial.getMaterial(location.getBlock().getRelative(BlockFace.DOWN)); - if (spawnedIn == null || spawnedOn == null) + if (spawnedIn == null || spawnedOn == null) { return false; + } - if (!spawnedIn.isAir() - && spawnedIn != CompatibleMaterial.WATER - && !spawnedIn.name().contains("PRESSURE") - && !spawnedIn.name().contains("SLAB")) { + if (!spawnedIn.isAir() && + spawnedIn != CompatibleMaterial.WATER && + !spawnedIn.name().contains("PRESSURE") && + !spawnedIn.name().contains("SLAB")) { return false; } for (CompatibleMaterial material : canSpawnOn) { if (material == null) continue; - if (spawnedOn.equals(material) || material.isAir()) + if (spawnedOn.equals(material) || material.isAir()) { return true; + } } + return false; } } diff --git a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/world/SWorldImpl.java b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/world/SWorldImpl.java index d980a7fc..4e118871 100644 --- a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/world/SWorldImpl.java +++ b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/world/SWorldImpl.java @@ -7,7 +7,6 @@ import java.util.ArrayList; import java.util.List; public class SWorldImpl implements SWorld { - public SWorldImpl() { } diff --git a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/world/WorldCoreImpl.java b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/world/WorldCoreImpl.java index e1645038..5dfeba18 100644 --- a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/world/WorldCoreImpl.java +++ b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/world/WorldCoreImpl.java @@ -56,28 +56,30 @@ public class WorldCoreImpl implements WorldCore { public void randomTickChunk(org.bukkit.Chunk bukkitChunk, int tickAmount) throws NoSuchFieldException, IllegalAccessException { Chunk chunk = ((CraftChunk) bukkitChunk).getHandle(); - if (tickAmount > 0) { - int j = chunk.locX * 16; - int k = chunk.locZ * 16; + if (tickAmount <= 0) { + return; + } - for (ChunkSection chunksection : chunk.getSections()) { - if (chunksection != net.minecraft.server.v1_9_R2.Chunk.a && chunksection.shouldTick()) { - for (int k1 = 0; k1 < tickAmount; ++k1) { - int worldL = (int) ReflectionUtils.getFieldValue(chunk.world, "l"); - worldL = worldL * 3 + 1013904223; - ReflectionUtils.setFieldValue(chunk.world, "l", worldL); + int j = chunk.locX * 16; + int k = chunk.locZ * 16; - int l1 = worldL >> 2; - int i2 = l1 & 15; - int j2 = l1 >> 8 & 15; - int k2 = l1 >> 16 & 15; + for (ChunkSection chunksection : chunk.getSections()) { + if (chunksection != net.minecraft.server.v1_9_R2.Chunk.a && chunksection.shouldTick()) { + for (int k1 = 0; k1 < tickAmount; ++k1) { + int worldL = (int) ReflectionUtils.getFieldValue(chunk.world, "l"); + worldL = worldL * 3 + 1013904223; + ReflectionUtils.setFieldValue(chunk.world, "l", worldL); - IBlockData iblockdata = chunksection.getType(i2, k2, j2); - Block block = iblockdata.getBlock(); + int l1 = worldL >> 2; + int i2 = l1 & 15; + int j2 = l1 >> 8 & 15; + int k2 = l1 >> 16 & 15; - if (block.isTicking()) { - block.a(chunk.world, new BlockPosition(i2 + j, k2 + chunksection.getYPosition(), j2 + k), iblockdata, chunk.world.random); - } + IBlockData iblockdata = chunksection.getType(i2, k2, j2); + Block block = iblockdata.getBlock(); + + if (block.isTicking()) { + block.a(chunk.world, new BlockPosition(i2 + j, k2 + chunksection.getYPosition(), j2 + k), iblockdata, chunk.world.random); } } } diff --git a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/world/spawner/BBaseSpawnerImpl.java b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/world/spawner/BBaseSpawnerImpl.java index d6a95f09..f4e99aee 100644 --- a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/world/spawner/BBaseSpawnerImpl.java +++ b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/world/spawner/BBaseSpawnerImpl.java @@ -71,81 +71,82 @@ public class BBaseSpawnerImpl implements BBaseSpawner { ReflectionUtils.setFieldValue(spawner, "e", spawnerD); ReflectionUtils.setFieldValue(spawner, "d", (spawnerD + (double) (1000F / ((float) spawner.spawnDelay + 200F))) % 360D); - } else { - if (spawner.spawnDelay == -1) { - delay(spawner); + return; + } + + if (spawner.spawnDelay == -1) { + delay(spawner); + } + + if (spawner.spawnDelay > 0) { + --spawner.spawnDelay; + return; + } + + boolean flag = false; + int i = 0; + + int spawnCount = (int) ReflectionUtils.getFieldValue(spawner, "spawnCount"); + int spawnRange = (int) ReflectionUtils.getFieldValue(spawner, "spawnRange"); + int maxNearbyEntities = (int) ReflectionUtils.getFieldValue(spawner, "maxNearbyEntities"); + MobSpawnerData spawnData = (MobSpawnerData) ReflectionUtils.getFieldValue(spawner, "spawnData"); + + while (true) { + if (i >= spawnCount) { + if (flag) { + delay(spawner); + } + break; } - if (spawner.spawnDelay > 0) { - --spawner.spawnDelay; + NBTTagCompound nbttagcompound = spawnData.b(); + NBTTagList nbttaglist = nbttagcompound.getList("Pos", 6); + net.minecraft.server.v1_9_R2.World world = spawner.a(); + int j = nbttaglist.size(); + double d3 = j >= 1 ? nbttaglist.e(0) : (double) blockposition.getX() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawnRange + .5D; + double d4 = j >= 2 ? nbttaglist.e(1) : (double) (blockposition.getY() + world.random.nextInt(3) - 1); + double d5 = j >= 3 ? nbttaglist.e(2) : (double) blockposition.getZ() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawnRange + .5D; + Entity entity = ChunkRegionLoader.a(nbttagcompound, world, d3, d4, d5, false); + if (entity == null) { return; } - boolean flag = false; - int i = 0; - - int spawnCount = (int) ReflectionUtils.getFieldValue(spawner, "spawnCount"); - int spawnRange = (int) ReflectionUtils.getFieldValue(spawner, "spawnRange"); - int maxNearbyEntities = (int) ReflectionUtils.getFieldValue(spawner, "maxNearbyEntities"); - MobSpawnerData spawnData = (MobSpawnerData) ReflectionUtils.getFieldValue(spawner, "spawnData"); - - while (true) { - if (i >= spawnCount) { - if (flag) { - delay(spawner); - } - break; - } - - NBTTagCompound nbttagcompound = spawnData.b(); - NBTTagList nbttaglist = nbttagcompound.getList("Pos", 6); - net.minecraft.server.v1_9_R2.World world = spawner.a(); - int j = nbttaglist.size(); - double d3 = j >= 1 ? nbttaglist.e(0) : (double) blockposition.getX() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawnRange + .5D; - double d4 = j >= 2 ? nbttaglist.e(1) : (double) (blockposition.getY() + world.random.nextInt(3) - 1); - double d5 = j >= 3 ? nbttaglist.e(2) : (double) blockposition.getZ() + (world.random.nextDouble() - world.random.nextDouble()) * (double) spawnRange + .5D; - Entity entity = ChunkRegionLoader.a(nbttagcompound, world, d3, d4, d5, false); - if (entity == null) { - return; - } - - int k = world.a(entity.getClass(), (new AxisAlignedBB( - blockposition.getX(), - blockposition.getY(), - blockposition.getZ(), - blockposition.getX() + 1, - blockposition.getY() + 1, - blockposition.getZ() + 1)) - .g(spawnRange)).size(); - if (k >= maxNearbyEntities) { - delay(spawner); - return; - } - - EntityInsentient entityinsentient = entity instanceof EntityInsentient ? (EntityInsentient) entity : null; - entity.setPositionRotation(entity.locX, entity.locY, entity.locZ, world.random.nextFloat() * 360.0F, 0.0F); - if (entityinsentient == null || entityinsentient.cG() && entityinsentient.canSpawn()) { - if (spawnData.b().d() == 1 && spawnData.b().hasKeyOfType("id", 8) && entity instanceof EntityInsentient) { - ((EntityInsentient) entity).prepare(world.D(new BlockPosition(entity)), null); - } - - if (entity.world.spigotConfig.nerfSpawnerMobs) { - entity.fromMobSpawner = true; - } - - if (!CraftEventFactory.callSpawnerSpawnEvent(entity, blockposition).isCancelled()) { - ChunkRegionLoader.a(entity, world, CreatureSpawnEvent.SpawnReason.SPAWNER); - world.triggerEffect(2004, blockposition, 0); - if (entityinsentient != null) { - entityinsentient.doSpawnEffect(); - } - - flag = true; - } - } - - ++i; + int k = world.a(entity.getClass(), (new AxisAlignedBB( + blockposition.getX(), + blockposition.getY(), + blockposition.getZ(), + blockposition.getX() + 1, + blockposition.getY() + 1, + blockposition.getZ() + 1)) + .g(spawnRange)).size(); + if (k >= maxNearbyEntities) { + delay(spawner); + return; } + + EntityInsentient entityinsentient = entity instanceof EntityInsentient ? (EntityInsentient) entity : null; + entity.setPositionRotation(entity.locX, entity.locY, entity.locZ, world.random.nextFloat() * 360.0F, 0.0F); + if (entityinsentient == null || entityinsentient.cG() && entityinsentient.canSpawn()) { + if (spawnData.b().d() == 1 && spawnData.b().hasKeyOfType("id", 8) && entity instanceof EntityInsentient) { + ((EntityInsentient) entity).prepare(world.D(new BlockPosition(entity)), null); + } + + if (entity.world.spigotConfig.nerfSpawnerMobs) { + entity.fromMobSpawner = true; + } + + if (!CraftEventFactory.callSpawnerSpawnEvent(entity, blockposition).isCancelled()) { + ChunkRegionLoader.a(entity, world, CreatureSpawnEvent.SpawnReason.SPAWNER); + world.triggerEffect(2004, blockposition, 0); + if (entityinsentient != null) { + entityinsentient.doSpawnEffect(); + } + + flag = true; + } + } + + ++i; } } @@ -156,4 +157,4 @@ public class BBaseSpawnerImpl implements BBaseSpawner { private void delay(MobSpawnerAbstract spawner) throws InvocationTargetException, IllegalAccessException { iMethod.invoke(spawner); } -} \ No newline at end of file +} From 97feaf3b9c26d2460b6b580b4277c1e9463ce4a8 Mon Sep 17 00:00:00 2001 From: Christian Koop Date: Sun, 26 Sep 2021 01:47:30 +0200 Subject: [PATCH 05/18] Removes `@author` and `@since` from class comments These kind of information can easily be found in git/on GitHub --- .../com/songoda/core/compatibility/CompatibleBiome.java | 3 --- .../java/com/songoda/core/compatibility/CompatibleHand.java | 3 --- .../com/songoda/core/compatibility/CompatibleMaterial.java | 3 --- .../com/songoda/core/compatibility/CompatibleSound.java | 3 --- .../songoda/core/compatibility/LegacyMaterialAnalouge.java | 3 --- .../songoda/core/compatibility/LegacyMaterialBlockType.java | 3 --- .../songoda/core/compatibility/LegacyParticleEffects.java | 3 --- Core/src/main/java/com/songoda/core/SongodaPlugin.java | 2 -- .../main/java/com/songoda/core/configuration/Comment.java | 3 --- .../main/java/com/songoda/core/configuration/Config.java | 3 --- .../java/com/songoda/core/configuration/ConfigSection.java | 3 --- .../com/songoda/core/configuration/SimpleDataStore.java | 3 --- .../songoda/core/configuration/editor/ConfigEditorGui.java | 3 --- .../configuration/editor/ConfigEditorListEditorGui.java | 3 --- .../songoda/core/configuration/editor/PluginConfigGui.java | 3 --- Core/src/main/java/com/songoda/core/gui/AnvilGui.java | 3 --- Core/src/main/java/com/songoda/core/gui/DoubleGui.java | 3 --- Core/src/main/java/com/songoda/core/gui/Gui.java | 3 --- Core/src/main/java/com/songoda/core/gui/GuiHolder.java | 3 --- Core/src/main/java/com/songoda/core/gui/GuiManager.java | 3 --- Core/src/main/java/com/songoda/core/gui/GuiUtils.java | 4 ---- Core/src/main/java/com/songoda/core/gui/SimplePagedGui.java | 3 --- Core/src/main/java/com/songoda/core/locale/Locale.java | 6 +----- .../main/java/com/songoda/core/nms/anvil/CustomAnvil.java | 3 --- 24 files changed, 1 insertion(+), 74 deletions(-) diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleBiome.java b/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleBiome.java index 83c6a2ac..143df25e 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleBiome.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleBiome.java @@ -19,9 +19,6 @@ import java.util.Set; /** * Biomes that are compatible with server versions 1.7+ - * - * @author Brianna - * @since 2020-03-27 */ public enum CompatibleBiome { /* 1.17 */ diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleHand.java b/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleHand.java index 2ca62063..dd18b26f 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleHand.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleHand.java @@ -11,9 +11,6 @@ import java.util.Map; /** * Get which hand is being used. - * - * @author Brianna - * @since 2020-03-24 */ public enum CompatibleHand { MAIN_HAND, OFF_HAND; diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleMaterial.java b/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleMaterial.java index 261ac45a..cb5585c4 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleMaterial.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleMaterial.java @@ -16,9 +16,6 @@ import java.util.Set; /** * Items that are compatible with server versions 1.7+ - * - * @author jascotty2 - * @since 2019-08-23 */ public enum CompatibleMaterial { /* diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleSound.java b/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleSound.java index 89f36e05..be586cd1 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleSound.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleSound.java @@ -13,9 +13,6 @@ import org.bukkit.entity.Player; * sounds were renamed. New sounds have been added by different versions, as * well. The intent of this class is to provide either the correct sound or a * near equivalent for the current server. - * - * @author jascotty2 - * @since 2019-08-25 */ public enum CompatibleSound { // some of these values are missing an API value.. diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyMaterialAnalouge.java b/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyMaterialAnalouge.java index c4e0fca5..578bb4fb 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyMaterialAnalouge.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyMaterialAnalouge.java @@ -8,9 +8,6 @@ import java.util.Map; /** * Near-Materials for older servers 1.7+ - * - * @author jascotty2 - * @since 2019-08-23 */ public enum LegacyMaterialAnalouge { /* 1.17 */ diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyMaterialBlockType.java b/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyMaterialBlockType.java index abcc507c..5499f31e 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyMaterialBlockType.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyMaterialBlockType.java @@ -8,9 +8,6 @@ import java.util.Map; /** * Starting in Minecraft 1.13, separate materials for blocks and items were * phased out. This provides a translation for those values. - * - * @author jascotty2 - * @since 2019-09-12 */ public enum LegacyMaterialBlockType { OAK_LEAVES("LEAVES", (byte) 8, true), diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyParticleEffects.java b/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyParticleEffects.java index 6e26bf90..33a65099 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyParticleEffects.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyParticleEffects.java @@ -15,9 +15,6 @@ import java.util.logging.Logger; /** * Particle effects for servers 1.8 and below - * - * @author jascotty2 - * @since 2019-08-23 */ public class LegacyParticleEffects { public static enum Type { diff --git a/Core/src/main/java/com/songoda/core/SongodaPlugin.java b/Core/src/main/java/com/songoda/core/SongodaPlugin.java index 9fa5757c..432ca56c 100644 --- a/Core/src/main/java/com/songoda/core/SongodaPlugin.java +++ b/Core/src/main/java/com/songoda/core/SongodaPlugin.java @@ -17,8 +17,6 @@ import java.util.logging.Level; /** * REMINDER: When converting plugins to use this, REMOVE METRICS
* Must not have two instances of Metrics enabled! - * - * @author jascotty2 */ public abstract class SongodaPlugin extends JavaPlugin { protected Locale locale; diff --git a/Core/src/main/java/com/songoda/core/configuration/Comment.java b/Core/src/main/java/com/songoda/core/configuration/Comment.java index 7f1304ba..dd4c3c34 100644 --- a/Core/src/main/java/com/songoda/core/configuration/Comment.java +++ b/Core/src/main/java/com/songoda/core/configuration/Comment.java @@ -11,9 +11,6 @@ import java.util.stream.Collectors; /** * A comment for a configuration key - * - * @author jascotty2 - * @since 2019-08-28 */ public class Comment { final List lines = new ArrayList(); diff --git a/Core/src/main/java/com/songoda/core/configuration/Config.java b/Core/src/main/java/com/songoda/core/configuration/Config.java index 8439cda5..d171a9d7 100644 --- a/Core/src/main/java/com/songoda/core/configuration/Config.java +++ b/Core/src/main/java/com/songoda/core/configuration/Config.java @@ -45,9 +45,6 @@ import java.util.stream.Collectors; /** * Configuration settings for a plugin - * - * @author jascotty2 - * @since 2019-08-28 */ public class Config extends ConfigSection { /* diff --git a/Core/src/main/java/com/songoda/core/configuration/ConfigSection.java b/Core/src/main/java/com/songoda/core/configuration/ConfigSection.java index 82438ede..0c226bcd 100644 --- a/Core/src/main/java/com/songoda/core/configuration/ConfigSection.java +++ b/Core/src/main/java/com/songoda/core/configuration/ConfigSection.java @@ -20,9 +20,6 @@ import java.util.stream.Collectors; /** * Configuration for a specific node - * - * @author jascotty2 - * @since 2019-08-28 */ public class ConfigSection extends MemoryConfiguration { final String fullPath, nodeKey; diff --git a/Core/src/main/java/com/songoda/core/configuration/SimpleDataStore.java b/Core/src/main/java/com/songoda/core/configuration/SimpleDataStore.java index 99a736ab..013d4882 100644 --- a/Core/src/main/java/com/songoda/core/configuration/SimpleDataStore.java +++ b/Core/src/main/java/com/songoda/core/configuration/SimpleDataStore.java @@ -21,9 +21,6 @@ import java.util.logging.Level; * Used to easily store a set of one data value * * @param DataObject class that is used to store the data - * - * @author jascotty2 - * @since 2019-09-06 */ public class SimpleDataStore { protected final Plugin plugin; diff --git a/Core/src/main/java/com/songoda/core/configuration/editor/ConfigEditorGui.java b/Core/src/main/java/com/songoda/core/configuration/editor/ConfigEditorGui.java index ffa947cf..dc707b77 100644 --- a/Core/src/main/java/com/songoda/core/configuration/editor/ConfigEditorGui.java +++ b/Core/src/main/java/com/songoda/core/configuration/editor/ConfigEditorGui.java @@ -27,9 +27,6 @@ import java.util.logging.Level; /** * Edit a configuration file for a specific plugin - * - * @author jascotty2 - * @since 2019-08-31 */ public class ConfigEditorGui extends SimplePagedGui { final JavaPlugin plugin; diff --git a/Core/src/main/java/com/songoda/core/configuration/editor/ConfigEditorListEditorGui.java b/Core/src/main/java/com/songoda/core/configuration/editor/ConfigEditorListEditorGui.java index 79b5c2dc..94583de3 100644 --- a/Core/src/main/java/com/songoda/core/configuration/editor/ConfigEditorListEditorGui.java +++ b/Core/src/main/java/com/songoda/core/configuration/editor/ConfigEditorListEditorGui.java @@ -12,9 +12,6 @@ import java.util.List; /** * Edit a string list - * - * @author jascotty2 - * @since 2019-08-31 */ public class ConfigEditorListEditorGui extends SimplePagedGui { final ConfigEditorGui current; diff --git a/Core/src/main/java/com/songoda/core/configuration/editor/PluginConfigGui.java b/Core/src/main/java/com/songoda/core/configuration/editor/PluginConfigGui.java index 60880bb0..9e5eafe7 100644 --- a/Core/src/main/java/com/songoda/core/configuration/editor/PluginConfigGui.java +++ b/Core/src/main/java/com/songoda/core/configuration/editor/PluginConfigGui.java @@ -19,9 +19,6 @@ import java.util.Map; /** * Edit all configuration files for a specific plugin - * - * @author jascotty2 - * @since 2019-08-31 */ public class PluginConfigGui extends SimplePagedGui { final JavaPlugin plugin; diff --git a/Core/src/main/java/com/songoda/core/gui/AnvilGui.java b/Core/src/main/java/com/songoda/core/gui/AnvilGui.java index 6483a775..49996176 100644 --- a/Core/src/main/java/com/songoda/core/gui/AnvilGui.java +++ b/Core/src/main/java/com/songoda/core/gui/AnvilGui.java @@ -17,9 +17,6 @@ import java.util.List; /** * Anvil GUI for text prompts - * - * @author jascotty2 - * @since 2019-09-15 */ public class AnvilGui extends Gui { final Player player; diff --git a/Core/src/main/java/com/songoda/core/gui/DoubleGui.java b/Core/src/main/java/com/songoda/core/gui/DoubleGui.java index 81729873..197ccbc6 100644 --- a/Core/src/main/java/com/songoda/core/gui/DoubleGui.java +++ b/Core/src/main/java/com/songoda/core/gui/DoubleGui.java @@ -24,9 +24,6 @@ import java.util.Map; * TODO: does not restore inventory if server crashes while player inventory is open * Method to fix: save inv + ender slot to file, store paper in ender inv with name of cache file, check for paper item in slot when loading * Or just manually manage all inventories in a file and remove when restored - * - * @author jascotty2 - * @since 2019-08-25 */ public class DoubleGui extends Gui { protected boolean startStashed = true; diff --git a/Core/src/main/java/com/songoda/core/gui/Gui.java b/Core/src/main/java/com/songoda/core/gui/Gui.java index 862966d9..bd3b5f0a 100644 --- a/Core/src/main/java/com/songoda/core/gui/Gui.java +++ b/Core/src/main/java/com/songoda/core/gui/Gui.java @@ -33,9 +33,6 @@ import java.util.stream.Collectors; /** * TODO: animated buttons - * - * @author jascotty2 - * @since 2019-08-25 */ public class Gui { protected Inventory inventory; diff --git a/Core/src/main/java/com/songoda/core/gui/GuiHolder.java b/Core/src/main/java/com/songoda/core/gui/GuiHolder.java index 8cf884fc..cdd568f8 100644 --- a/Core/src/main/java/com/songoda/core/gui/GuiHolder.java +++ b/Core/src/main/java/com/songoda/core/gui/GuiHolder.java @@ -7,9 +7,6 @@ import org.bukkit.inventory.InventoryHolder; /** * Internal class for marking an inventory as a GUI inventory - * - * @author jascotty2 - * @since 2019-08-25 */ class GuiHolder implements InventoryHolder { final Gui gui; diff --git a/Core/src/main/java/com/songoda/core/gui/GuiManager.java b/Core/src/main/java/com/songoda/core/gui/GuiManager.java index 151a1fac..48a3dae5 100644 --- a/Core/src/main/java/com/songoda/core/gui/GuiManager.java +++ b/Core/src/main/java/com/songoda/core/gui/GuiManager.java @@ -28,9 +28,6 @@ import java.util.stream.Collectors; /** * Manages events for GUI screens - * - * @author jascotty2 - * @since 2019-08-25 */ public class GuiManager { final Plugin plugin; diff --git a/Core/src/main/java/com/songoda/core/gui/GuiUtils.java b/Core/src/main/java/com/songoda/core/gui/GuiUtils.java index c812b822..55c46e6f 100644 --- a/Core/src/main/java/com/songoda/core/gui/GuiUtils.java +++ b/Core/src/main/java/com/songoda/core/gui/GuiUtils.java @@ -10,10 +10,6 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; -/** - * @author jascotty2 - * @since 2019-08-25 - */ public class GuiUtils { public static ItemStack getBorderGlassItem() { ItemStack glass = CompatibleMaterial.LIGHT_BLUE_STAINED_GLASS_PANE.getItem(); diff --git a/Core/src/main/java/com/songoda/core/gui/SimplePagedGui.java b/Core/src/main/java/com/songoda/core/gui/SimplePagedGui.java index 2ea84098..d1612962 100644 --- a/Core/src/main/java/com/songoda/core/gui/SimplePagedGui.java +++ b/Core/src/main/java/com/songoda/core/gui/SimplePagedGui.java @@ -15,9 +15,6 @@ import java.util.Map; /** * Paged GUI for when you aren't going to be making too many pages - * - * @author jascotty2 - * @since 2019-08-31 */ public class SimplePagedGui extends Gui { protected boolean useHeader; diff --git a/Core/src/main/java/com/songoda/core/locale/Locale.java b/Core/src/main/java/com/songoda/core/locale/Locale.java index a1c7c505..0dbf2519 100644 --- a/Core/src/main/java/com/songoda/core/locale/Locale.java +++ b/Core/src/main/java/com/songoda/core/locale/Locale.java @@ -30,11 +30,7 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; /** - * Assists in the utilization of localization files.
- * Created to be used by the Songoda Team.
- * Updated 2019-09-01 to support UTF encoded lang files - jascotty2 - * - * @author Brianna O'Keefe - Songoda + * Assists in the utilization of localization files. */ public class Locale { private static final Pattern OLD_NODE_PATTERN = Pattern.compile("^([^ ]+)\\s*=\\s*\"?(.*?)\"?$"); diff --git a/NMS/NMS-API/src/main/java/com/songoda/core/nms/anvil/CustomAnvil.java b/NMS/NMS-API/src/main/java/com/songoda/core/nms/anvil/CustomAnvil.java index a2792370..a81fe891 100644 --- a/NMS/NMS-API/src/main/java/com/songoda/core/nms/anvil/CustomAnvil.java +++ b/NMS/NMS-API/src/main/java/com/songoda/core/nms/anvil/CustomAnvil.java @@ -6,9 +6,6 @@ import org.bukkit.inventory.ItemStack; /** * NMS interface for creating an anvil view for a single player - * - * @author jascotty2 - * @since 2019-09-13 */ public interface CustomAnvil { public void setLevelCost(int cost); From 93fbc6463f1c985437b85cc093be9706df9c1cdb Mon Sep 17 00:00:00 2001 From: Christian Koop Date: Sun, 26 Sep 2021 15:26:57 +0200 Subject: [PATCH 06/18] General code cleanup [DEV-2] Hopefully no breaking changes --- .../core/compatibility/CompatibleBiome.java | 2 +- .../core/compatibility/CompatibleHand.java | 2 +- .../compatibility/CompatibleMaterial.java | 13 ++-- .../CompatibleParticleHandler.java | 6 +- .../core/compatibility/CompatibleSound.java | 16 ++--- .../core/compatibility/EntityNamespace.java | 4 +- .../compatibility/LegacyMaterialAnalouge.java | 26 ++++---- .../LegacyMaterialBlockType.java | 14 ++-- .../compatibility/LegacyParticleEffects.java | 22 +++---- .../compatibility/LegacyPotionEffects.java | 2 +- .../java/com/songoda/core/SongodaCore.java | 26 ++++---- .../java/com/songoda/core/SongodaPlugin.java | 16 ++--- .../java/com/songoda/core/chat/ColorCode.java | 6 +- .../core/commands/AbstractCommand.java | 4 +- .../songoda/core/commands/CommandManager.java | 4 +- .../songoda/core/commands/MainCommand.java | 2 +- .../core/commands/SelectorArguments.java | 16 +++-- .../songoda/core/configuration/Comment.java | 7 +- .../songoda/core/configuration/Config.java | 22 +++---- .../ConfigFileConfigurationAdapter.java | 3 +- .../configuration/ConfigFormattingRules.java | 16 ++--- .../configuration/ConfigOptionsAdapter.java | 6 +- .../core/configuration/ConfigSection.java | 64 +++++++++---------- .../core/configuration/DataStoreObject.java | 10 +-- .../core/configuration/SimpleDataStore.java | 20 +++--- .../configuration/editor/ConfigEditorGui.java | 29 ++++----- .../editor/ConfigEditorListEditorGui.java | 5 +- .../configuration/editor/PluginConfigGui.java | 10 +-- .../com/songoda/core/core/LocaleModule.java | 7 +- .../core/database/DataManagerAbstract.java | 2 +- .../java/com/songoda/core/gui/AnvilGui.java | 26 ++++++-- .../com/songoda/core/gui/BackgroundType.java | 2 +- .../com/songoda/core/gui/CustomizableGui.java | 4 +- .../java/com/songoda/core/gui/DoubleGui.java | 6 +- .../main/java/com/songoda/core/gui/Gui.java | 16 ++--- .../java/com/songoda/core/gui/GuiManager.java | 2 +- .../java/com/songoda/core/gui/GuiType.java | 2 +- .../java/com/songoda/core/gui/GuiUtils.java | 42 ++++++------ .../com/songoda/core/gui/PopupMessage.java | 20 +++--- .../com/songoda/core/gui/SimplePagedGui.java | 4 +- .../java/com/songoda/core/hooks/Hook.java | 4 +- .../com/songoda/core/hooks/HookManager.java | 4 +- .../java/com/songoda/core/hooks/JobsHook.java | 4 +- .../com/songoda/core/hooks/McMMOHook.java | 22 +++---- .../com/songoda/core/hooks/PluginHook.java | 2 +- .../songoda/core/hooks/WorldGuardHook.java | 4 +- .../core/hooks/economies/ReserveEconomy.java | 6 +- .../hooks/holograms/HologramsHolograms.java | 4 +- .../songoda/core/hooks/jobs/JobsHandler.java | 3 +- .../core/hooks/jobs/JobsPlayerHandler.java | 2 +- .../core/hooks/mcmmo/McMMOHandler.java | 8 +-- .../worldguard/WorldGuardFlagHandler.java | 19 +++--- .../worldguard/WorldGuardRegionHandler.java | 18 +++--- .../com/songoda/core/input/ChatPrompt.java | 10 +-- .../java/com/songoda/core/locale/Locale.java | 8 +-- .../java/com/songoda/core/locale/Message.java | 4 +- .../lootables/gui/AbstractGuiListEditor.java | 2 +- .../core/lootables/gui/GuiEnchantEditor.java | 2 +- .../core/lootables/loot/LootManager.java | 5 +- .../main/java/com/songoda/core/math/Eval.java | 25 +++++--- .../java/com/songoda/core/nms/NmsManager.java | 10 +-- .../com/songoda/core/utils/BlockUtils.java | 12 ++-- .../com/songoda/core/utils/ColorUtils.java | 7 +- .../com/songoda/core/utils/ItemUtils.java | 28 +++----- .../java/com/songoda/core/utils/Metrics.java | 36 ++++------- .../com/songoda/core/utils/PlayerUtils.java | 14 ++-- .../songoda/core/utils/ReflectionUtils.java | 8 +-- .../com/songoda/core/utils/RotationUtils.java | 14 ++-- .../com/songoda/core/utils/TextUtils.java | 26 +++++--- .../com/songoda/core/utils/TimeUtils.java | 3 + .../com/songoda/core/world/SItemStack.java | 2 +- .../com/songoda/core/nms/ReflectionUtils.java | 2 + .../com/songoda/core/nms/anvil/AnvilCore.java | 4 +- .../songoda/core/nms/anvil/CustomAnvil.java | 36 +++++------ .../core/nms/v1_10_R1/anvil/AnvilView.java | 2 +- .../nms/v1_10_R1/nbt/NBTCompoundImpl.java | 3 +- .../core/nms/v1_10_R1/nbt/NBTItemImpl.java | 4 -- .../nms/v1_10_R1/world/SItemStackImpl.java | 3 +- .../core/nms/v1_10_R1/world/SSpawnerImpl.java | 1 + .../core/nms/v1_11_R1/anvil/AnvilView.java | 2 +- .../nms/v1_11_R1/nbt/NBTCompoundImpl.java | 3 +- .../core/nms/v1_11_R1/nbt/NBTItemImpl.java | 4 -- .../nms/v1_11_R1/world/SItemStackImpl.java | 3 +- .../core/nms/v1_11_R1/world/SSpawnerImpl.java | 1 + .../core/nms/v1_12_R1/anvil/AnvilView.java | 2 +- .../nms/v1_12_R1/nbt/NBTCompoundImpl.java | 3 +- .../core/nms/v1_12_R1/nbt/NBTItemImpl.java | 4 -- .../nms/v1_12_R1/world/SItemStackImpl.java | 3 +- .../core/nms/v1_12_R1/world/SSpawnerImpl.java | 1 + .../core/nms/v1_13_R1/anvil/AnvilView.java | 2 +- .../nms/v1_13_R1/nbt/NBTCompoundImpl.java | 3 +- .../core/nms/v1_13_R1/nbt/NBTItemImpl.java | 4 -- .../core/nms/v1_13_R1/world/SSpawnerImpl.java | 1 + .../core/nms/v1_13_R2/anvil/AnvilView.java | 2 +- .../nms/v1_13_R2/nbt/NBTCompoundImpl.java | 3 +- .../core/nms/v1_13_R2/nbt/NBTItemImpl.java | 4 -- .../core/nms/v1_13_R2/world/SSpawnerImpl.java | 1 + .../core/nms/v1_14_R1/anvil/AnvilView.java | 7 +- .../nms/v1_14_R1/nbt/NBTCompoundImpl.java | 3 +- .../core/nms/v1_14_R1/nbt/NBTEntityImpl.java | 2 + .../core/nms/v1_14_R1/nbt/NBTItemImpl.java | 4 -- .../core/nms/v1_14_R1/world/SSpawnerImpl.java | 1 + .../core/nms/v1_15_R1/anvil/AnvilView.java | 2 +- .../nms/v1_15_R1/nbt/NBTCompoundImpl.java | 3 +- .../core/nms/v1_15_R1/nbt/NBTEntityImpl.java | 2 + .../core/nms/v1_15_R1/nbt/NBTItemImpl.java | 4 -- .../core/nms/v1_15_R1/world/SSpawnerImpl.java | 1 + .../core/nms/v1_16_R1/anvil/AnvilView.java | 7 +- .../nms/v1_16_R1/nbt/NBTCompoundImpl.java | 3 +- .../core/nms/v1_16_R1/nbt/NBTEntityImpl.java | 2 + .../core/nms/v1_16_R1/nbt/NBTItemImpl.java | 4 -- .../core/nms/v1_16_R1/world/SSpawnerImpl.java | 1 + .../core/nms/v1_16_R2/anvil/AnvilView.java | 2 +- .../core/nms/v1_16_R2/nbt/NBTEntityImpl.java | 2 + .../core/nms/v1_16_R2/nbt/NBTItemImpl.java | 4 -- .../core/nms/v1_16_R2/world/SSpawnerImpl.java | 1 + .../core/nms/v1_16_R3/anvil/AnvilView.java | 2 +- .../core/nms/v1_16_R3/nbt/NBTEntityImpl.java | 2 + .../core/nms/v1_16_R3/nbt/NBTItemImpl.java | 4 -- .../core/nms/v1_16_R3/world/SSpawnerImpl.java | 1 + .../core/nms/v1_17_R1/anvil/AnvilView.java | 2 +- .../core/nms/v1_17_R1/nbt/NBTEntityImpl.java | 2 + .../core/nms/v1_17_R1/nbt/NBTItemImpl.java | 4 -- .../core/nms/v1_17_R1/world/SSpawnerImpl.java | 3 +- .../core/nms/v1_17_R1/world/SWorldImpl.java | 2 +- .../world/spawner/BBaseSpawnerImpl.java | 2 +- .../core/nms/v1_8_R1/anvil/AnvilView.java | 2 +- .../core/nms/v1_8_R1/nbt/NBTCompoundImpl.java | 3 +- .../core/nms/v1_8_R1/nbt/NBTItemImpl.java | 4 -- .../nms/v1_8_R1/world/SItemStackImpl.java | 3 +- .../core/nms/v1_8_R2/anvil/AnvilView.java | 2 +- .../core/nms/v1_8_R2/nbt/NBTCompoundImpl.java | 3 +- .../core/nms/v1_8_R2/nbt/NBTItemImpl.java | 4 -- .../nms/v1_8_R2/world/SItemStackImpl.java | 3 +- .../core/nms/v1_8_R3/anvil/AnvilView.java | 2 +- .../core/nms/v1_8_R3/nbt/NBTCompoundImpl.java | 3 +- .../core/nms/v1_8_R3/nbt/NBTItemImpl.java | 4 -- .../nms/v1_8_R3/world/SItemStackImpl.java | 3 +- .../core/nms/v1_9_R1/anvil/AnvilView.java | 2 +- .../core/nms/v1_9_R1/nbt/NBTCompoundImpl.java | 3 +- .../core/nms/v1_9_R1/nbt/NBTItemImpl.java | 4 -- .../nms/v1_9_R1/world/SItemStackImpl.java | 3 +- .../core/nms/v1_9_R2/anvil/AnvilView.java | 2 +- .../core/nms/v1_9_R2/nbt/NBTCompoundImpl.java | 3 +- .../core/nms/v1_9_R2/nbt/NBTItemImpl.java | 4 -- .../nms/v1_9_R2/world/SItemStackImpl.java | 3 +- .../core/nms/v1_9_R2/world/SSpawnerImpl.java | 1 + 147 files changed, 516 insertions(+), 547 deletions(-) diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleBiome.java b/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleBiome.java index 143df25e..2b1b2230 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleBiome.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleBiome.java @@ -110,7 +110,7 @@ public enum CompatibleBiome { private static final boolean isAbove1_16_R1 = ServerVersion.isServerVersionAtLeast(ServerVersion.V1_16) && !ServerVersion.getServerVersionString().equals("v1_16_R1"); - private static final Map lookupMap = new HashMap(); + private static final Map lookupMap = new HashMap<>(); private static final Set compatibleBiomes = new HashSet<>(); private final Deque versions = new ArrayDeque<>(); private static Method methodGetHandle, methodMarkDirty, methodBiomeToBiomeBase, methodGetBiomeIndex, methodSetBiome; diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleHand.java b/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleHand.java index dd18b26f..0cb9c423 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleHand.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleHand.java @@ -15,7 +15,7 @@ import java.util.Map; public enum CompatibleHand { MAIN_HAND, OFF_HAND; - private static Map methodCache = new HashMap<>(); + private static final Map methodCache = new HashMap<>(); public static CompatibleHand getHand(Object event) { try { diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleMaterial.java b/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleMaterial.java index cb5585c4..5ad4cec8 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleMaterial.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleMaterial.java @@ -1293,7 +1293,7 @@ public enum CompatibleMaterial { // quick test to see if our version is < 1.13 protected static final boolean useLegacy = ServerVersion.isServerVersionBelow(ServerVersion.V1_13); // map to speed up name->material lookups - private static final Map lookupMap = new HashMap(); + private static final Map lookupMap = new HashMap<>(); static { for (CompatibleMaterial m : values()) { @@ -1904,7 +1904,7 @@ public enum CompatibleMaterial { * Checks if this Material can be used as fuel in a Furnace */ public boolean isFuel() { - // this function is not implemented in some older versions, so we need this here.. + // this function is not implemented in some older versions, so we need this here... switch (this) { case ACACIA_BOAT: case ACACIA_BUTTON: @@ -2318,7 +2318,7 @@ public enum CompatibleMaterial { * Checks if this Material is an obtainable item. */ public boolean isItem() { - // this function is not implemented in some older versions, so we need this here.. + // this function is not implemented in some older versions, so we need this here... switch (this) { case CAVE_AIR: case VOID_AIR: @@ -2423,7 +2423,7 @@ public enum CompatibleMaterial { * additional interact handling is performed for the material. */ public boolean isInteractable() { - // this function is not implemented in some older versions, so we need this here.. + // this function is not implemented in some older versions, so we need this here... switch (this) { case ACACIA_BUTTON: case ACACIA_DOOR: @@ -2793,8 +2793,9 @@ public enum CompatibleMaterial { return false; } + /** - * @return true if this material is a food that can be cooked and is in its cooked state + * @return true if this material is food that can be cooked and is in its cooked state */ public boolean isCooked() { switch (this) { @@ -2814,7 +2815,7 @@ public enum CompatibleMaterial { } /** - * @return true if this material is a food that can be cooked and is in its raw state + * @return true if this material is food that can be cooked and is in its raw state */ public boolean isRaw() { switch (this) { diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleParticleHandler.java b/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleParticleHandler.java index 9875c60a..fe10fd6c 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleParticleHandler.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleParticleHandler.java @@ -13,7 +13,7 @@ import java.util.Map; import java.util.stream.Stream; public class CompatibleParticleHandler { - public static enum ParticleType { + public enum ParticleType { EXPLOSION_NORMAL, EXPLOSION_LARGE, EXPLOSION_HUGE, @@ -131,7 +131,7 @@ public class CompatibleParticleHandler { } } - private ParticleType() { + ParticleType() { if (ServerVersion.isServerVersionAtOrBelow(ServerVersion.V1_8)) { this.compatibilityMode = true; this.particle = null; @@ -151,7 +151,7 @@ public class CompatibleParticleHandler { } } - private ParticleType(ServerVersion minVersion, String compatible) { + ParticleType(ServerVersion minVersion, String compatible) { // Particle class doesn't exist in 1.8 if (ServerVersion.isServerVersionAtOrBelow(ServerVersion.V1_8)) { this.compatibilityMode = true; diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleSound.java b/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleSound.java index be586cd1..52553630 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleSound.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/CompatibleSound.java @@ -15,7 +15,7 @@ import org.bukkit.entity.Player; * near equivalent for the current server. */ public enum CompatibleSound { - // some of these values are missing an API value.. + // some of these values are missing an API value... // would using the raw strings be better? // 1.8 list: // https://www.minecraftforum.net/forums/mapping-and-modding-java-edition/mapping-and-modding-tutorials/2213619-1-8-all-playsound-sound-arguments @@ -469,8 +469,8 @@ public enum CompatibleSound { BLOCK_CHEST_CLOSE(ServerVersion.V1_9, v("CHEST_CLOSE")), BLOCK_CHEST_LOCKED(ServerVersion.V1_9, v("CHEST_CLOSE", true)), BLOCK_CHEST_OPEN(ServerVersion.V1_9, v("CHEST_OPEN")), - BLOCK_CHORUS_FLOWER_DEATH(ServerVersion.V1_9, v(null, true)), // I have no idea.. - BLOCK_CHORUS_FLOWER_GROW(ServerVersion.V1_9, v(null, true)), // I have no idea.. + BLOCK_CHORUS_FLOWER_DEATH(ServerVersion.V1_9, v(null, true)), // I have no idea... + BLOCK_CHORUS_FLOWER_GROW(ServerVersion.V1_9, v(null, true)), // I have no idea... BLOCK_COMPARATOR_CLICK(ServerVersion.V1_9, v("WOOD_CLICK", true)), BLOCK_COMPOSTER_EMPTY, BLOCK_COMPOSTER_FILL, @@ -634,7 +634,7 @@ public enum CompatibleSound { ENTITY_ARMOR_STAND_FALL, ENTITY_ARMOR_STAND_HIT, ENTITY_ARMOR_STAND_PLACE, - ENTITY_ARROW_HIT("SUCCESSFUL_HIT"), // these may be reversed.. + ENTITY_ARROW_HIT("SUCCESSFUL_HIT"), // these may be reversed... ENTITY_ARROW_HIT_PLAYER("ARROW_HIT"), ENTITY_ARROW_SHOOT("SHOOT_ARROW"), ENTITY_BAT_AMBIENT("BAT_IDLE"), @@ -1222,7 +1222,7 @@ public enum CompatibleSound { protected /*final*/ boolean compatibilityMode; protected static final boolean DEBUG = false; - private CompatibleSound() { + CompatibleSound() { // This could get risky, since we haven't finished this //sound = Sound.valueOf(name()); Sound find = null; @@ -1240,7 +1240,7 @@ public enum CompatibleSound { } // if the sound ony ever changed from 1.8 -> 1.9 - private CompatibleSound(String compatibility_18) { + CompatibleSound(String compatibility_18) { try { compatibilityMode = false; @@ -1255,7 +1255,7 @@ public enum CompatibleSound { } } - private CompatibleSound(Version... versions) { + CompatibleSound(Version... versions) { try { for (Version v : versions) { if (v.sound != null && ServerVersion.isServerVersionAtLeast(v.version)) { @@ -1283,7 +1283,7 @@ public enum CompatibleSound { compatibilityMode = find == null; } - private CompatibleSound(ServerVersion minVersion, Version... versions) { + CompatibleSound(ServerVersion minVersion, Version... versions) { try { if (ServerVersion.isServerVersionAtLeast(minVersion)) { // should be good to use this sound diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/EntityNamespace.java b/Compatibility/src/main/java/com/songoda/core/compatibility/EntityNamespace.java index 4f83c87f..e8c6dce5 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/EntityNamespace.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/EntityNamespace.java @@ -6,8 +6,8 @@ import java.util.HashMap; import java.util.Map; public class EntityNamespace { - static final HashMap validTypes = new HashMap(); - static final HashMap legacyToModernTypes = new HashMap() { + static final HashMap validTypes = new HashMap<>(); + static final HashMap legacyToModernTypes = new HashMap() { { put("xporb", "experience_orb"); put("xp_orb", "experience_orb"); diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyMaterialAnalouge.java b/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyMaterialAnalouge.java index 578bb4fb..1e24b72b 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyMaterialAnalouge.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyMaterialAnalouge.java @@ -294,7 +294,7 @@ public enum LegacyMaterialAnalouge { BAMBOO(ServerVersion.V1_14, "SUGAR_CANE", "SUGAR_CANE_BLOCK"), BAMBOO_SAPLING(ServerVersion.V1_14, "SUGAR_CANE"), BARREL(ServerVersion.V1_14, "TRAPPED_CHEST"), - BARRIER(ServerVersion.V1_8, "STAINED_GLASS", (byte) 14), // plain glass would make more sense if this were to be a block.. + BARRIER(ServerVersion.V1_8, "STAINED_GLASS", (byte) 14), // plain glass would make more sense if this were to be a block... BEETROOT(ServerVersion.V1_9, "RAW_BEEF"), BEETROOT_SEEDS(ServerVersion.V1_9, "SEEDS"), BEETROOT_SOUP(ServerVersion.V1_9, "MUSHROOM_SOUP"), @@ -416,7 +416,7 @@ public enum LegacyMaterialAnalouge { DIORITE_WALL(ServerVersion.V1_14, "COBBLESTONE_WALL", "COBBLE_WALL"), DOLPHIN_SPAWN_EGG(ServerVersion.V1_13, "MONSTER_EGG", (byte) 0), DONKEY_SPAWN_EGG(ServerVersion.V1_11, "MONSTER_EGG", (byte) 100), - DRAGON_BREATH(ServerVersion.V1_9, "POTION", (byte) 0), // or maybe glowstone.. + DRAGON_BREATH(ServerVersion.V1_9, "POTION", (byte) 0), // or maybe glowstone... DRAGON_HEAD(ServerVersion.V1_9, "SKULL_ITEM", (byte) 4), DRAGON_WALL_HEAD(ServerVersion.V1_9, "SKULL", (byte) 4), DRIED_KELP(ServerVersion.V1_13, "POTATO_ITEM"), @@ -710,7 +710,7 @@ public enum LegacyMaterialAnalouge { TUBE_CORAL_FAN(ServerVersion.V1_13, "WOOL", (byte) 11), TUBE_CORAL_WALL_FAN(ServerVersion.V1_13, "WOOL", (byte) 11), TURTLE_EGG(ServerVersion.V1_13, "DRAGON_EGG"), - TURTLE_HELMET(ServerVersion.V1_13, "LEATHER_HELMET"), // would be cool to color it green.. + TURTLE_HELMET(ServerVersion.V1_13, "LEATHER_HELMET"), // would be cool to color it green... TURTLE_SPAWN_EGG(ServerVersion.V1_13, "MONSTER_EGG", (byte) 60), VEX_SPAWN_EGG(ServerVersion.V1_11, "MONSTER_EGG", (byte) 0), VINDICATOR_SPAWN_EGG(ServerVersion.V1_11, "MONSTER_EGG", (byte) 0), @@ -748,7 +748,7 @@ public enum LegacyMaterialAnalouge { final Byte data; // map to speed up name->material lookups - private static final Map lookupMap = new HashMap(); + private static final Map lookupMap = new HashMap<>(); static { for (LegacyMaterialAnalouge m : values()) { @@ -760,35 +760,35 @@ public enum LegacyMaterialAnalouge { return lookupMap.get(material); } - private LegacyMaterialAnalouge(ServerVersion versionLessThan, String legacyMaterial, byte legacyData) { + LegacyMaterialAnalouge(ServerVersion versionLessThan, String legacyMaterial, byte legacyData) { this(versionLessThan, null, legacyMaterial, legacyData, null, null, null); } - private LegacyMaterialAnalouge(ServerVersion versionLessThan, String legacyMaterial) { + LegacyMaterialAnalouge(ServerVersion versionLessThan, String legacyMaterial) { this(versionLessThan, null, legacyMaterial, null, null, null, null); } - private LegacyMaterialAnalouge(ServerVersion versionLessThan, String modernAnalouge, String legacyMaterial) { + LegacyMaterialAnalouge(ServerVersion versionLessThan, String modernAnalouge, String legacyMaterial) { this(versionLessThan, modernAnalouge, legacyMaterial, null, null, null, null); } - private LegacyMaterialAnalouge(ServerVersion versionLessThan, String modernAnalouge, String legacyMaterial, byte legacyData) { + LegacyMaterialAnalouge(ServerVersion versionLessThan, String modernAnalouge, String legacyMaterial, byte legacyData) { this(versionLessThan, modernAnalouge, legacyMaterial, legacyData, null, null, null); } - private LegacyMaterialAnalouge(ServerVersion versionLessThan, String legacyMaterial, byte legacyData, ServerVersion legacyMinimum, String compatMaterial, byte compatData) { + LegacyMaterialAnalouge(ServerVersion versionLessThan, String legacyMaterial, byte legacyData, ServerVersion legacyMinimum, String compatMaterial, byte compatData) { this(versionLessThan, null, legacyMaterial, legacyData, legacyMinimum, compatMaterial, compatData); } - private LegacyMaterialAnalouge(ServerVersion versionLessThan, String legacyMaterial, ServerVersion legacyMinimum, String compatMaterial, byte compatData) { + LegacyMaterialAnalouge(ServerVersion versionLessThan, String legacyMaterial, ServerVersion legacyMinimum, String compatMaterial, byte compatData) { this(versionLessThan, null, legacyMaterial, null, legacyMinimum, compatMaterial, compatData); } - private LegacyMaterialAnalouge(ServerVersion versionLessThan, String legacyMaterial, byte legacyData, ServerVersion legacyMinimum, String compatMaterial) { + LegacyMaterialAnalouge(ServerVersion versionLessThan, String legacyMaterial, byte legacyData, ServerVersion legacyMinimum, String compatMaterial) { this(versionLessThan, null, legacyMaterial, legacyData, legacyMinimum, compatMaterial, null); } - private LegacyMaterialAnalouge(ServerVersion versionLessThan, String legacyMaterial, ServerVersion legacyMinimum, String compatMaterial) { + LegacyMaterialAnalouge(ServerVersion versionLessThan, String legacyMaterial, ServerVersion legacyMinimum, String compatMaterial) { this(versionLessThan, null, legacyMaterial, null, legacyMinimum, compatMaterial, null); } @@ -798,7 +798,7 @@ public enum LegacyMaterialAnalouge { * @param legacyMaterial pre-1.13 material name * @param legacyData data for defining specific legacy items */ - private LegacyMaterialAnalouge(ServerVersion versionLessThan, String modernAnalouge, String legacyMaterial, Byte legacyData, ServerVersion legacyMinimum, String compatMaterial, Byte compatData) { + LegacyMaterialAnalouge(ServerVersion versionLessThan, String modernAnalouge, String legacyMaterial, Byte legacyData, ServerVersion legacyMinimum, String compatMaterial, Byte compatData) { this.versionLessThan = versionLessThan; this.modernMaterial = modernAnalouge; this.legacyMaterial = legacyMaterial; diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyMaterialBlockType.java b/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyMaterialBlockType.java index 5499f31e..49226b43 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyMaterialBlockType.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyMaterialBlockType.java @@ -52,8 +52,8 @@ public enum LegacyMaterialBlockType { final String alternateBlockMaterialName; final Material blockMaterial, alternateBlockMaterial; final boolean requiresData; // some blocks require data to render properly (double blocks) - final static Map lookupTable = new HashMap(); - final static Map reverseLookupTable = new HashMap(); + final static Map lookupTable = new HashMap<>(); + final static Map reverseLookupTable = new HashMap<>(); static { for (LegacyMaterialBlockType t : values()) { @@ -65,23 +65,23 @@ public enum LegacyMaterialBlockType { } } - private LegacyMaterialBlockType(String blockMaterial) { + LegacyMaterialBlockType(String blockMaterial) { this(blockMaterial, (byte) -1, null, false); } - private LegacyMaterialBlockType(String blockMaterial, boolean requiresData) { + LegacyMaterialBlockType(String blockMaterial, boolean requiresData) { this(blockMaterial, (byte) -1, null, requiresData); } - private LegacyMaterialBlockType(String blockMaterial, byte data, boolean requiresData) { + LegacyMaterialBlockType(String blockMaterial, byte data, boolean requiresData) { this(blockMaterial, data, null, requiresData); } - private LegacyMaterialBlockType(String blockMaterial, String alternateMaterial) { + LegacyMaterialBlockType(String blockMaterial, String alternateMaterial) { this(blockMaterial, (byte) -1, alternateMaterial, false); } - private LegacyMaterialBlockType(String blockMaterial, byte data, String alternateMaterial, boolean requiresData) { + LegacyMaterialBlockType(String blockMaterial, byte data, String alternateMaterial, boolean requiresData) { this.blockMaterialName = blockMaterial; this.alternateBlockMaterialName = alternateMaterial; this.requiresData = requiresData; diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyParticleEffects.java b/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyParticleEffects.java index 33a65099..7988cb5c 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyParticleEffects.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyParticleEffects.java @@ -17,7 +17,7 @@ import java.util.logging.Logger; * Particle effects for servers 1.8 and below */ public class LegacyParticleEffects { - public static enum Type { + public enum Type { EXPLOSION_NORMAL("explode"), EXPLOSION_LARGE("largeexplode"), EXPLOSION_HUGE("hugeexplosion"), @@ -69,19 +69,19 @@ public class LegacyParticleEffects { public final ServerVersion minVersion; public final ServerVersion maxVersion; - private Type(String name) { + Type(String name) { this.name = name; this.minVersion = ServerVersion.UNKNOWN; this.maxVersion = null; } - private Type(String name, ServerVersion minVersion) { + Type(String name, ServerVersion minVersion) { this.name = name; this.minVersion = minVersion; this.maxVersion = null; } - private Type(String name, ServerVersion minVersion, ServerVersion maxVersion) { + Type(String name, ServerVersion minVersion, ServerVersion maxVersion) { this.name = name; this.minVersion = minVersion; this.maxVersion = maxVersion; @@ -99,15 +99,15 @@ public class LegacyParticleEffects { private static final String version = getNMSVersion(); private static boolean enabled = true; - private static Class mc_packetPlayOutWorldParticlesClazz; - private static Class cb_craftPlayerClazz; + private static Class mc_packetPlayOutWorldParticlesClazz; + private static Class cb_craftPlayerClazz; private static Method cb_craftPlayer_getHandle; - private static Class mc_entityPlayerClazz; - private static Class mc_playerConnectionClazz; + private static Class mc_entityPlayerClazz; + private static Class mc_playerConnectionClazz; private static Field mc_entityPlayer_playerConnection; - private static Class mc_PacketInterface; + private static Class mc_PacketInterface; private static Method mc_playerConnection_sendPacket; - private static Class mc_EnumParticle; + private static Class mc_EnumParticle; private static Method mc_EnumParticle_valueOf; static { @@ -158,7 +158,7 @@ public class LegacyParticleEffects { * @param e particle effect type * @param xx for notes, this is a value 0-1 for the color ([0-24]/24), for * redstone this is the red value 0-1 ([0-255]/255). - * Otherwise this is the distance for particles to fly on the x-axis. + * Otherwise, this is the distance for particles to fly on the x-axis. * @param yy for redstone this is the green value 0-1 ([0-255]/255) * Otherwise this is the distance for particles to fly on the y-axis. * @param zz for redstone this is the blue value 0-1 ([0-255]/255) diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyPotionEffects.java b/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyPotionEffects.java index b96f9c8a..632b4f85 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyPotionEffects.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/LegacyPotionEffects.java @@ -11,7 +11,7 @@ public class LegacyPotionEffects { protected final static Random rand = new Random(); - private final static HashMap potionEffectNames = new HashMap() { + private final static HashMap potionEffectNames = new HashMap() { { put(PotionEffectType.SPEED.getId(), "Speed"); put(PotionEffectType.SLOW.getId(), "Slowness"); diff --git a/Core/src/main/java/com/songoda/core/SongodaCore.java b/Core/src/main/java/com/songoda/core/SongodaCore.java index f05ccea1..81335872 100644 --- a/Core/src/main/java/com/songoda/core/SongodaCore.java +++ b/Core/src/main/java/com/songoda/core/SongodaCore.java @@ -111,7 +111,7 @@ public class SongodaCore { // we are newer than the registered service: steal all of its registrations // grab the old core's registrations - List otherPlugins = (List) clazz.getMethod("getPlugins").invoke(null); + List otherPlugins = (List) clazz.getMethod("getPlugins").invoke(null); // destroy the old core Object oldCore = clazz.getMethod("getInstance").invoke(null); @@ -177,15 +177,15 @@ public class SongodaCore { Bukkit.getPluginManager().registerEvents(shadingListener, piggybackedPlugin); // we aggressively want to own this command - tasks.add(Bukkit.getScheduler().runTaskLaterAsynchronously(piggybackedPlugin, () -> { - CommandManager.registerCommandDynamically(piggybackedPlugin, "songoda", commandManager, commandManager); - }, 10 * 60 * 1)); - tasks.add(Bukkit.getScheduler().runTaskLaterAsynchronously(piggybackedPlugin, () -> { - CommandManager.registerCommandDynamically(piggybackedPlugin, "songoda", commandManager, commandManager); - }, 20 * 60 * 1)); - tasks.add(Bukkit.getScheduler().runTaskLaterAsynchronously(piggybackedPlugin, () -> { - CommandManager.registerCommandDynamically(piggybackedPlugin, "songoda", commandManager, commandManager); - }, 20 * 60 * 2)); + tasks.add(Bukkit.getScheduler().runTaskLaterAsynchronously(piggybackedPlugin, () -> + CommandManager.registerCommandDynamically(piggybackedPlugin, "songoda", commandManager, commandManager), + 10 * 60)); + tasks.add(Bukkit.getScheduler().runTaskLaterAsynchronously(piggybackedPlugin, () -> + CommandManager.registerCommandDynamically(piggybackedPlugin, "songoda", commandManager, commandManager), + 20 * 60)); + tasks.add(Bukkit.getScheduler().runTaskLaterAsynchronously(piggybackedPlugin, () -> + CommandManager.registerCommandDynamically(piggybackedPlugin, "songoda", commandManager, commandManager), + 20 * 60 * 2)); } /** @@ -207,7 +207,7 @@ public class SongodaCore { loginListener = null; } - private ArrayList tasks = new ArrayList(); + private ArrayList tasks = new ArrayList<>(); private void register(JavaPlugin plugin, int pluginID, String icon, String libraryVersion) { logger.info(getPrefix() + "Hooked " + plugin.getName() + "."); @@ -297,7 +297,7 @@ public class SongodaCore { } private static class ShadedEventListener implements Listener { - boolean via = false; + boolean via; boolean proto = false; ShadedEventListener() { @@ -345,7 +345,7 @@ public class SongodaCore { } private class EventListener implements Listener { - final HashMap lastCheck = new HashMap(); + final HashMap lastCheck = new HashMap<>(); @EventHandler void onLogin(PlayerLoginEvent event) { diff --git a/Core/src/main/java/com/songoda/core/SongodaPlugin.java b/Core/src/main/java/com/songoda/core/SongodaPlugin.java index 432ca56c..e703f9c6 100644 --- a/Core/src/main/java/com/songoda/core/SongodaPlugin.java +++ b/Core/src/main/java/com/songoda/core/SongodaPlugin.java @@ -91,10 +91,10 @@ public abstract class SongodaPlugin extends JavaPlugin { console.sendMessage(" "); // blank line to separate chatter console.sendMessage(ChatColor.GREEN + "============================="); - console.sendMessage(String.format("%s%s %s by %sSongoda <3!", ChatColor.GRAY.toString(), - getDescription().getName(), getDescription().getVersion(), ChatColor.DARK_PURPLE.toString())); - console.sendMessage(String.format("%sAction: %s%s%s...", ChatColor.GRAY.toString(), - ChatColor.GREEN.toString(), "Enabling", ChatColor.GRAY.toString())); + console.sendMessage(String.format("%s%s %s by %sSongoda <3!", ChatColor.GRAY, + getDescription().getName(), getDescription().getVersion(), ChatColor.DARK_PURPLE)); + console.sendMessage(String.format("%sAction: %s%s%s...", ChatColor.GRAY, + ChatColor.GREEN, "Enabling", ChatColor.GRAY)); try { locale = Locale.loadDefaultLocale(this, "en_US"); @@ -146,10 +146,10 @@ public abstract class SongodaPlugin extends JavaPlugin { console.sendMessage(" "); // blank line to speparate chatter console.sendMessage(ChatColor.GREEN + "============================="); - console.sendMessage(String.format("%s%s %s by %sSongoda <3!", ChatColor.GRAY.toString(), - getDescription().getName(), getDescription().getVersion(), ChatColor.DARK_PURPLE.toString())); - console.sendMessage(String.format("%sAction: %s%s%s...", ChatColor.GRAY.toString(), - ChatColor.RED.toString(), "Disabling", ChatColor.GRAY.toString())); + console.sendMessage(String.format("%s%s %s by %sSongoda <3!", ChatColor.GRAY, + getDescription().getName(), getDescription().getVersion(), ChatColor.DARK_PURPLE)); + console.sendMessage(String.format("%sAction: %s%s%s...", ChatColor.GRAY, + ChatColor.RED, "Disabling", ChatColor.GRAY)); onPluginDisable(); diff --git a/Core/src/main/java/com/songoda/core/chat/ColorCode.java b/Core/src/main/java/com/songoda/core/chat/ColorCode.java index b6b1d299..23462f46 100644 --- a/Core/src/main/java/com/songoda/core/chat/ColorCode.java +++ b/Core/src/main/java/com/songoda/core/chat/ColorCode.java @@ -42,11 +42,7 @@ public enum ColorCode { } static { - ColorCode[] var0 = values(); - int l = var0.length; - - for (int i = 0; i < l; ++i) { - ColorCode color = var0[i]; + for (ColorCode color : values()) { BY_CHAR.put(color.code, color); } } diff --git a/Core/src/main/java/com/songoda/core/commands/AbstractCommand.java b/Core/src/main/java/com/songoda/core/commands/AbstractCommand.java index 2a2d17aa..c41bbe7f 100644 --- a/Core/src/main/java/com/songoda/core/commands/AbstractCommand.java +++ b/Core/src/main/java/com/songoda/core/commands/AbstractCommand.java @@ -64,8 +64,8 @@ public abstract class AbstractCommand { return _cmdType == CommandType.PLAYER_ONLY; } - public static enum ReturnType {SUCCESS, NEEDS_PLAYER, FAILURE, SYNTAX_ERROR} + public enum ReturnType {SUCCESS, NEEDS_PLAYER, FAILURE, SYNTAX_ERROR} - public static enum CommandType {PLAYER_ONLY, CONSOLE_OK} + public enum CommandType {PLAYER_ONLY, CONSOLE_OK} } diff --git a/Core/src/main/java/com/songoda/core/commands/CommandManager.java b/Core/src/main/java/com/songoda/core/commands/CommandManager.java index fc801c1b..7ddc6e98 100644 --- a/Core/src/main/java/com/songoda/core/commands/CommandManager.java +++ b/Core/src/main/java/com/songoda/core/commands/CommandManager.java @@ -85,7 +85,7 @@ public class CommandManager implements CommandExecutor, TabCompleter { c.children.values().stream() .filter(s -> !all.contains(s)) - .forEach(s -> all.add(s)); + .forEach(all::add); }); return all; @@ -302,7 +302,7 @@ public class CommandManager implements CommandExecutor, TabCompleter { .filter(e -> !console || !e.getValue().isNoConsole()) .filter(e -> e.getKey().startsWith(arg)) .filter(e -> op || e.getValue().getPermissionNode() == null || sender.hasPermission(e.getValue().getPermissionNode())) - .map(e -> e.getKey()) + .map(Map.Entry::getKey) .collect(Collectors.toList()); } diff --git a/Core/src/main/java/com/songoda/core/commands/MainCommand.java b/Core/src/main/java/com/songoda/core/commands/MainCommand.java index 21aa99a4..3675a5a3 100644 --- a/Core/src/main/java/com/songoda/core/commands/MainCommand.java +++ b/Core/src/main/java/com/songoda/core/commands/MainCommand.java @@ -90,7 +90,7 @@ public class MainCommand extends AbstractCommand { chatMessage.addMessage(ChatColor.DARK_GRAY + "- ") .addPromptCommand(ChatColor.YELLOW + c + cmd.getSyntax(), ChatColor.YELLOW + c + cmdStr, c + cmdStr) .addMessage(ChatColor.GRAY + " - " + cmd.getDescription()); - chatMessage.sendTo((Player) sender); + chatMessage.sendTo(sender); } } } diff --git a/Core/src/main/java/com/songoda/core/commands/SelectorArguments.java b/Core/src/main/java/com/songoda/core/commands/SelectorArguments.java index 3f201da9..08e16097 100644 --- a/Core/src/main/java/com/songoda/core/commands/SelectorArguments.java +++ b/Core/src/main/java/com/songoda/core/commands/SelectorArguments.java @@ -20,7 +20,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; public class SelectorArguments { - static Pattern selectorPattern = Pattern.compile("^(@[apers])(\\[(.*?)\\])?$"); + static Pattern selectorPattern = Pattern.compile("^(@[apers])(\\[(.*?)])?$"); static Pattern selectorRangePattern = Pattern.compile("^([0-9]{1,9}(\\.[0-9]{1,9})?)?(\\.\\.)?([0-9]{1,9}(\\.[0-9]{1,9})?)?$"); /** @@ -141,7 +141,8 @@ public class SelectorArguments { switch (selector) { case PLAYER: - Collections.sort(list2, (o1, o2) -> (int) (o1.getLocation().distanceSquared(location) - o2.getLocation().distanceSquared(location))); + list2.sort((o1, o2) -> (int) (o1.getLocation().distanceSquared(location) - o2.getLocation().distanceSquared(location))); + return Arrays.asList(list2.get(0)); case RANDOM_PLAYER: Collections.shuffle(list2); @@ -163,7 +164,7 @@ public class SelectorArguments { return rangeMax == Double.POSITIVE_INFINITY ? location.getWorld().getEntitiesByClasses(Player.class) : location.getWorld().getNearbyEntities(location, rangeMax * 2, rangeMax * 2, rangeMax * 2).stream() - .filter(e -> e instanceof Player).collect(Collectors.toSet()); + .filter(Player.class::isInstance).collect(Collectors.toSet()); case ALL_ENTITIES: return rangeMax == Double.POSITIVE_INFINITY @@ -171,10 +172,10 @@ public class SelectorArguments { : location.getWorld().getNearbyEntities(location, rangeMax * 2, rangeMax * 2, rangeMax * 2); case SELF: - return sender instanceof Entity ? Arrays.asList((Entity) sender) : Collections.EMPTY_LIST; + return sender instanceof Entity ? Arrays.asList((Entity) sender) : Collections.emptyList(); } - return Collections.EMPTY_LIST; + return Collections.emptyList(); } protected List filter(Location location, Collection list) { @@ -185,9 +186,10 @@ public class SelectorArguments { return stream.collect(Collectors.toList()); } - public static enum SelectorType { + public enum SelectorType { PLAYER, RANDOM_PLAYER, ALL_PLAYER, ALL_ENTITIES, SELF; + // TODO: Store selector string in enum public static SelectorType getType(String str) { if (str != null) { switch (str.toLowerCase()) { @@ -201,6 +203,8 @@ public class SelectorArguments { return ALL_ENTITIES; case "@s": return SELF; + default: + break; } } diff --git a/Core/src/main/java/com/songoda/core/configuration/Comment.java b/Core/src/main/java/com/songoda/core/configuration/Comment.java index dd4c3c34..e04f2137 100644 --- a/Core/src/main/java/com/songoda/core/configuration/Comment.java +++ b/Core/src/main/java/com/songoda/core/configuration/Comment.java @@ -6,6 +6,7 @@ import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; +import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; @@ -13,7 +14,7 @@ import java.util.stream.Collectors; * A comment for a configuration key */ public class Comment { - final List lines = new ArrayList(); + final List lines = new ArrayList<>(); CommentStyle commentStyle = null; public Comment() { @@ -53,7 +54,7 @@ public class Comment { @Override public String toString() { - return lines.isEmpty() ? "" : lines.stream().collect(Collectors.joining("\n")); + return lines.isEmpty() ? "" : String.join("\n", lines); } public static Comment loadComment(List lines) { @@ -73,7 +74,7 @@ public class Comment { // first draw the top of the comment if (style.drawBorder) { // grab the longest line in the list of lines - minSpacing = lines.stream().max((s1, s2) -> s1.length() - s2.length()).get().length(); + minSpacing = lines.stream().max(Comparator.comparingInt(String::length)).orElse("").length(); borderSpacing = minSpacing + style.commentPrefix.length() + style.commentSuffix.length(); // draw the first line diff --git a/Core/src/main/java/com/songoda/core/configuration/Config.java b/Core/src/main/java/com/songoda/core/configuration/Config.java index d171a9d7..6445382d 100644 --- a/Core/src/main/java/com/songoda/core/configuration/Config.java +++ b/Core/src/main/java/com/songoda/core/configuration/Config.java @@ -21,7 +21,6 @@ import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; -import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.StringReader; @@ -390,7 +389,7 @@ public class Config extends ConfigSection { return headerComment.getLines(); } - return Collections.EMPTY_LIST; + return Collections.emptyList(); } public Config clearConfig(boolean clearDefaults) { @@ -459,10 +458,10 @@ public class Config extends ConfigSection { } public void loadFromString(@NotNull String contents) throws InvalidConfigurationException { - Map input; + Map input; try { - input = (Map) this.yaml.load(contents); + input = this.yaml.load(contents); } catch (YAMLException e2) { throw new InvalidConfigurationException(e2); } catch (ClassCastException e3) { @@ -485,7 +484,7 @@ public class Config extends ConfigSection { Object value = entry.getValue(); if (value instanceof Map) { - this.convertMapsToSections((Map) value, section.createSection(key)); + this.convertMapsToSections((Map) value, section.createSection(key)); continue; } @@ -503,8 +502,8 @@ public class Config extends ConfigSection { boolean insideScalar = false; boolean firstNode = true; int index = 0; - LinkedList currentPath = new LinkedList(); - ArrayList commentBlock = new ArrayList(); + LinkedList currentPath = new LinkedList<>(); + ArrayList commentBlock = new ArrayList<>(); try { while ((line = in.readLine()) != null) { @@ -558,6 +557,7 @@ public class Config extends ConfigSection { commentBlock.clear(); } } catch (IOException ex) { + Logger.getLogger(Config.class.getName()).log(Level.SEVERE, "Error parsing config comment", ex); } } @@ -642,9 +642,9 @@ public class Config extends ConfigSection { } String data = this.saveToString(); - try (OutputStreamWriter writer = new OutputStreamWriter((OutputStream) new FileOutputStream(file), defaultCharset)) { + try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), defaultCharset)) { writer.write(data); - } catch (IOException e) { + } catch (IOException ex) { return false; } @@ -689,7 +689,7 @@ public class Config extends ConfigSection { return ""; } - protected final Pattern yamlNode = Pattern.compile("^( *)([^:\\{\\}\\[\\],&\\*#\\?\\|\\-<>=!%@`]+):(.*)$"); + protected final Pattern yamlNode = Pattern.compile("^( *)([^:{}\\[\\],&*#?|\\-<>=!%@`]+):(.*)$"); protected void writeComments(String data, Writer out) throws IOException { // line-by-line apply line spacing formatting and comments per-node @@ -700,7 +700,7 @@ public class Config extends ConfigSection { boolean firstNode = true; int index = 0; - LinkedList currentPath = new LinkedList(); + LinkedList currentPath = new LinkedList<>(); while ((line = in.readLine()) != null) { // ignore comments and empty lines (there shouldn't be any, but just in case) if (line.trim().startsWith("#") || line.isEmpty()) { diff --git a/Core/src/main/java/com/songoda/core/configuration/ConfigFileConfigurationAdapter.java b/Core/src/main/java/com/songoda/core/configuration/ConfigFileConfigurationAdapter.java index 89141df5..d05dedfe 100644 --- a/Core/src/main/java/com/songoda/core/configuration/ConfigFileConfigurationAdapter.java +++ b/Core/src/main/java/com/songoda/core/configuration/ConfigFileConfigurationAdapter.java @@ -11,7 +11,6 @@ import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.stream.Collectors; public class ConfigFileConfigurationAdapter extends FileConfiguration { final Config config; @@ -38,7 +37,7 @@ public class ConfigFileConfigurationAdapter extends FileConfiguration { @Override protected String buildHeader() { - return "#" + config.getHeader().stream().collect(Collectors.joining("\n#")); + return "#" + String.join("\n#", config.getHeader()); } @Override diff --git a/Core/src/main/java/com/songoda/core/configuration/ConfigFormattingRules.java b/Core/src/main/java/com/songoda/core/configuration/ConfigFormattingRules.java index b6cf06cd..8e279925 100644 --- a/Core/src/main/java/com/songoda/core/configuration/ConfigFormattingRules.java +++ b/Core/src/main/java/com/songoda/core/configuration/ConfigFormattingRules.java @@ -8,7 +8,7 @@ public class ConfigFormattingRules { CommentStyle rootCommentStyle = CommentStyle.BLOCKSPACED; CommentStyle mainCategoryCommentStyle = CommentStyle.SPACED; - public static enum CommentStyle { + public enum CommentStyle { /** * # Comment */ @@ -39,10 +39,10 @@ public class ConfigFormattingRules { final String commentSuffix, spaceSuffixTop, spaceSuffixBottom; final char spaceCharTop, spaceCharBottom; - private CommentStyle(boolean drawBorder, boolean drawSpace, - String spacePrefixTop, char spaceCharTop, String spaceSuffixTop, - String commentPrefix, String commentSuffix, - String spacePrefixBottom, char spaceCharBottom, String spaceSuffixBottom) { + CommentStyle(boolean drawBorder, boolean drawSpace, + String spacePrefixTop, char spaceCharTop, String spaceSuffixTop, + String commentPrefix, String commentSuffix, + String spacePrefixBottom, char spaceCharBottom, String spaceSuffixBottom) { this.drawBorder = drawBorder; this.drawSpace = drawSpace; this.commentPrefix = commentPrefix; @@ -55,7 +55,7 @@ public class ConfigFormattingRules { this.spaceCharBottom = spaceCharBottom; } - private CommentStyle(boolean drawBorder, boolean drawSpace, String commentPrefix, String commentSuffix) { + CommentStyle(boolean drawBorder, boolean drawSpace, String commentPrefix, String commentSuffix) { this.drawBorder = drawBorder; this.drawSpace = drawSpace; this.commentPrefix = commentPrefix; @@ -71,11 +71,11 @@ public class ConfigFormattingRules { return CommentStyle.SIMPLE; } - if (lines.size() > 2 && lines.get(0).trim().equals("#") && lines.get(lines.size() - 1).trim().equals("#")) { + if (lines.get(0).trim().equals("#") && lines.get(lines.size() - 1).trim().equals("#")) { return CommentStyle.SPACED; } - boolean hasBorders = lines.size() > 2 && lines.get(0).trim().matches("^##+$") && lines.get(lines.size() - 1).trim().matches("^##+$"); + boolean hasBorders = lines.get(0).trim().matches("^##+$") && lines.get(lines.size() - 1).trim().matches("^##+$"); if (!hasBorders) { // default return return CommentStyle.SIMPLE; diff --git a/Core/src/main/java/com/songoda/core/configuration/ConfigOptionsAdapter.java b/Core/src/main/java/com/songoda/core/configuration/ConfigOptionsAdapter.java index 63e5d83f..f8df4b79 100644 --- a/Core/src/main/java/com/songoda/core/configuration/ConfigOptionsAdapter.java +++ b/Core/src/main/java/com/songoda/core/configuration/ConfigOptionsAdapter.java @@ -34,7 +34,7 @@ public class ConfigOptionsAdapter extends FileConfigurationOptions { @NotNull @Override public ConfigOptionsAdapter pathSeparator(char value) { - ((Config) config.root).setPathSeparator(value); + (config.root).setPathSeparator(value); return this; } @@ -61,12 +61,12 @@ public class ConfigOptionsAdapter extends FileConfigurationOptions { } public int indent() { - return ((Config) config.root).getIndent(); + return config.root.getIndent(); } @NotNull public ConfigOptionsAdapter indent(int value) { - ((Config) config.root).setIndent(value); + config.root.setIndent(value); return this; } } diff --git a/Core/src/main/java/com/songoda/core/configuration/ConfigSection.java b/Core/src/main/java/com/songoda/core/configuration/ConfigSection.java index 0c226bcd..25d37fb0 100644 --- a/Core/src/main/java/com/songoda/core/configuration/ConfigSection.java +++ b/Core/src/main/java/com/songoda/core/configuration/ConfigSection.java @@ -44,10 +44,10 @@ public class ConfigSection extends MemoryConfiguration { isDefault = false; nodeKey = fullPath = ""; - configComments = new HashMap(); - defaultComments = new HashMap(); - defaults = new LinkedHashMap(); - values = new LinkedHashMap(); + configComments = new HashMap<>(); + defaultComments = new HashMap<>(); + defaults = new LinkedHashMap<>(); + values = new LinkedHashMap<>(); } ConfigSection(ConfigSection root, ConfigSection parent, String nodeKey, boolean isDefault) { @@ -199,7 +199,7 @@ public class ConfigSection extends MemoryConfiguration { @NotNull public ConfigSection setDefaultComment(@NotNull String path, String... lines) { - return setDefaultComment(path, lines.length == 0 ? (List) null : Arrays.asList(lines)); + return setDefaultComment(path, lines.length == 0 ? null : Arrays.asList(lines)); } @NotNull @@ -213,7 +213,7 @@ public class ConfigSection extends MemoryConfiguration { @NotNull public ConfigSection setDefaultComment(@NotNull String path, ConfigFormattingRules.CommentStyle commentStyle, String... lines) { - return setDefaultComment(path, commentStyle, lines.length == 0 ? (List) null : Arrays.asList(lines)); + return setDefaultComment(path, commentStyle, lines.length == 0 ? null : Arrays.asList(lines)); } @NotNull @@ -268,7 +268,7 @@ public class ConfigSection extends MemoryConfiguration { @Override public void addDefaults(@NotNull Map defaults) { //defaults.entrySet().stream().forEach(m -> root.defaults.put(fullPath + m.getKey(), m.getValue())); - defaults.entrySet().stream().forEach(m -> addDefault(m.getKey(), m.getValue())); + defaults.entrySet().forEach(m -> addDefault(m.getKey(), m.getValue())); } @Override @@ -278,7 +278,7 @@ public class ConfigSection extends MemoryConfiguration { } else { root.defaults.keySet().stream() .filter(k -> k.startsWith(fullPath)) - .forEach(k -> root.defaults.remove(k)); + .forEach(root.defaults::remove); } addDefaults(c); @@ -302,7 +302,7 @@ public class ConfigSection extends MemoryConfiguration { @NotNull @Override public Set getKeys(boolean deep) { - LinkedHashSet result = new LinkedHashSet(); + LinkedHashSet result = new LinkedHashSet<>(); int pathIndex = fullPath.lastIndexOf(root.pathChar); if (deep) { @@ -331,7 +331,7 @@ public class ConfigSection extends MemoryConfiguration { @NotNull @Override public Map getValues(boolean deep) { - LinkedHashMap result = new LinkedHashMap(); + LinkedHashMap result = new LinkedHashMap<>(); int pathIndex = fullPath.lastIndexOf(root.pathChar); if (deep) { @@ -339,7 +339,7 @@ public class ConfigSection extends MemoryConfiguration { .filter(k -> k.getKey().startsWith(fullPath)) .collect(Collectors.toMap( e -> !e.getKey().endsWith(String.valueOf(root.pathChar)) ? e.getKey().substring(pathIndex + 1) : e.getKey().substring(pathIndex + 1, e.getKey().length() - 1), - e -> e.getValue(), + Map.Entry::getValue, (v1, v2) -> { throw new IllegalStateException(); }, // never going to be merging keys @@ -349,7 +349,7 @@ public class ConfigSection extends MemoryConfiguration { .filter(k -> k.getKey().startsWith(fullPath)) .collect(Collectors.toMap( e -> !e.getKey().endsWith(String.valueOf(root.pathChar)) ? e.getKey().substring(pathIndex + 1) : e.getKey().substring(pathIndex + 1, e.getKey().length() - 1), - e -> e.getValue(), + Map.Entry::getValue, (v1, v2) -> { throw new IllegalStateException(); }, // never going to be merging keys @@ -359,7 +359,7 @@ public class ConfigSection extends MemoryConfiguration { .filter(k -> k.getKey().startsWith(fullPath) && k.getKey().lastIndexOf(root.pathChar) == pathIndex) .collect(Collectors.toMap( e -> !e.getKey().endsWith(String.valueOf(root.pathChar)) ? e.getKey().substring(pathIndex + 1) : e.getKey().substring(pathIndex + 1, e.getKey().length() - 1), - e -> e.getValue(), + Map.Entry::getValue, (v1, v2) -> { throw new IllegalStateException(); }, // never going to be merging keys @@ -369,7 +369,7 @@ public class ConfigSection extends MemoryConfiguration { .filter(k -> k.getKey().startsWith(fullPath) && k.getKey().lastIndexOf(root.pathChar) == pathIndex) .collect(Collectors.toMap( e -> !e.getKey().endsWith(String.valueOf(root.pathChar)) ? e.getKey().substring(pathIndex + 1) : e.getKey().substring(pathIndex + 1, e.getKey().length() - 1), - e -> e.getValue(), + Map.Entry::getValue, (v1, v2) -> { throw new IllegalStateException(); }, // never going to be merging keys @@ -384,13 +384,13 @@ public class ConfigSection extends MemoryConfiguration { ConfigSection rootSection = getConfigurationSection(path); if (rootSection == null) { - return Collections.EMPTY_LIST; + return Collections.emptyList(); } - ArrayList result = new ArrayList(); + ArrayList result = new ArrayList<>(); rootSection.getKeys(false).stream() - .map(key -> rootSection.get(key)) - .filter(object -> object != null && object instanceof ConfigSection) + .map(rootSection::get) + .filter(ConfigSection.class::isInstance) .forEachOrdered(object -> result.add((ConfigSection) object)); return result; @@ -464,7 +464,7 @@ public class ConfigSection extends MemoryConfiguration { } createNodePath(path, false); - Object last = null; + Object last; synchronized (root.lock) { if (value != null) { root.changed |= (last = root.values.put(fullPath + path, value)) != value; @@ -473,12 +473,14 @@ public class ConfigSection extends MemoryConfiguration { } } - if (last != value && last != null && last instanceof ConfigSection) { + if (last != value && last instanceof ConfigSection) { // clean up orphaned nodes final String trim = fullPath + path + root.pathChar; synchronized (root.lock) { - root.values.keySet().stream().filter(k -> k.startsWith(trim)).collect(Collectors.toSet()).stream() - .forEach(k -> root.values.remove(k)); + root.values.keySet().stream() + .filter(k -> k.startsWith(trim)) + .collect(Collectors.toSet()) + .forEach(root.values::remove); } } @@ -557,7 +559,7 @@ public class ConfigSection extends MemoryConfiguration { @NotNull public ConfigSection createSection(@NotNull String path, String... comment) { - return createSection(path, null, comment.length == 0 ? (List) null : Arrays.asList(comment)); + return createSection(path, null, comment.length == 0 ? null : Arrays.asList(comment)); } @NotNull @@ -567,7 +569,7 @@ public class ConfigSection extends MemoryConfiguration { @NotNull public ConfigSection createSection(@NotNull String path, @Nullable ConfigFormattingRules.CommentStyle commentStyle, String... comment) { - return createSection(path, commentStyle, comment.length == 0 ? (List) null : Arrays.asList(comment)); + return createSection(path, commentStyle, comment.length == 0 ? null : Arrays.asList(comment)); } @NotNull @@ -598,7 +600,7 @@ public class ConfigSection extends MemoryConfiguration { for (Map.Entry entry : map.entrySet()) { if (entry.getValue() instanceof Map) { - section.createSection(entry.getKey().toString(), (Map) entry.getValue()); + section.createSection(entry.getKey().toString(), (Map) entry.getValue()); continue; } @@ -700,7 +702,7 @@ public class ConfigSection extends MemoryConfiguration { public List getList(@NotNull String path) { Object result = get(path); - return result instanceof List ? (List) result : null; + return result instanceof List ? (List) result : null; } @Nullable @@ -708,16 +710,14 @@ public class ConfigSection extends MemoryConfiguration { public List getList(@NotNull String path, @Nullable List def) { Object result = get(path); - return result instanceof List ? (List) result : def; + return result instanceof List ? (List) result : def; } @Nullable public CompatibleMaterial getMaterial(@NotNull String path) { String val = getString(path); - CompatibleMaterial mat = val != null ? CompatibleMaterial.getMaterial(val) : null; - - return mat; + return val != null ? CompatibleMaterial.getMaterial(val) : null; } @Nullable @@ -734,7 +734,7 @@ public class ConfigSection extends MemoryConfiguration { public T getObject(@NotNull String path, @NotNull Class clazz) { Object result = get(path); - return result != null && clazz.isInstance(result) ? clazz.cast(result) : null; + return clazz.isInstance(result) ? clazz.cast(result) : null; } @Nullable @@ -742,7 +742,7 @@ public class ConfigSection extends MemoryConfiguration { public T getObject(@NotNull String path, @NotNull Class clazz, @Nullable T def) { Object result = get(path); - return result != null && clazz.isInstance(result) ? clazz.cast(result) : def; + return clazz.isInstance(result) ? clazz.cast(result) : def; } @Override diff --git a/Core/src/main/java/com/songoda/core/configuration/DataStoreObject.java b/Core/src/main/java/com/songoda/core/configuration/DataStoreObject.java index 8c08d33a..243b1180 100644 --- a/Core/src/main/java/com/songoda/core/configuration/DataStoreObject.java +++ b/Core/src/main/java/com/songoda/core/configuration/DataStoreObject.java @@ -6,25 +6,25 @@ public interface DataStoreObject { /** * @return a unique hashable instance of T to store this value under */ - public abstract T getKey(); + T getKey(); /** * @return a unique identifier for saving this value with */ - public abstract String getConfigKey(); + String getConfigKey(); /** * Save this data to a ConfigurationSection */ - public abstract void saveToSection(ConfigurationSection sec); + void saveToSection(ConfigurationSection sec); /** * @return true if this data has changed from the state saved to file */ - public boolean hasChanged(); + boolean hasChanged(); /** * Mark this data as needing a save or not */ - public void setChanged(boolean isChanged); + void setChanged(boolean isChanged); } diff --git a/Core/src/main/java/com/songoda/core/configuration/SimpleDataStore.java b/Core/src/main/java/com/songoda/core/configuration/SimpleDataStore.java index 013d4882..9c656cf2 100644 --- a/Core/src/main/java/com/songoda/core/configuration/SimpleDataStore.java +++ b/Core/src/main/java/com/songoda/core/configuration/SimpleDataStore.java @@ -26,7 +26,7 @@ public class SimpleDataStore { protected final Plugin plugin; protected final String filename, dirName; private final Function getFromSection; - protected final HashMap data = new HashMap(); + protected final HashMap data = new HashMap<>(); private File file; private final Object lock = new Object(); SaveTask saveTask; @@ -163,16 +163,15 @@ public class SimpleDataStore { * * @param value values to be added */ - @Nullable public void addAll(@NotNull T[] value) { if (value == null) { return; } synchronized (lock) { - for (int i = 0; i < value.length; ++i) { - if (value[i] != null) { - data.put(value[i].getKey(), value[i]); + for (T t : value) { + if (t != null) { + data.put(t.getKey(), t); } } } @@ -219,9 +218,8 @@ public class SimpleDataStore { synchronized (lock) { data.clear(); - f.getValues(false).entrySet().stream() - .filter(d -> d.getValue() instanceof ConfigurationSection) - .map(Map.Entry::getValue) + f.getValues(false).values().stream() + .filter(ConfigurationSection.class::isInstance) .map(v -> getFromSection.apply((ConfigurationSection) v)) .forEach(v -> data.put(v.getKey(), v)); } @@ -235,7 +233,7 @@ public class SimpleDataStore { * made */ public void saveChanges() { - if (saveTask != null || data.values().stream().anyMatch(v -> v.hasChanged())) { + if (saveTask != null || data.values().stream().anyMatch(DataStoreObject::hasChanged)) { flushSave(); } } @@ -266,12 +264,12 @@ public class SimpleDataStore { YamlConfiguration f = new YamlConfiguration(); synchronized (lock) { - data.values().stream().forEach(e -> e.saveToSection(f.createSection(e.getConfigKey()))); + data.values().forEach(e -> e.saveToSection(f.createSection(e.getConfigKey()))); } try { f.save(getFile()); - data.values().stream().forEach(e -> e.setChanged(false)); + data.values().forEach(e -> e.setChanged(false)); } catch (IOException ex) { plugin.getLogger().log(Level.SEVERE, "Failed to save data to " + file.getName(), ex); } diff --git a/Core/src/main/java/com/songoda/core/configuration/editor/ConfigEditorGui.java b/Core/src/main/java/com/songoda/core/configuration/editor/ConfigEditorGui.java index dc707b77..d3649a7a 100644 --- a/Core/src/main/java/com/songoda/core/configuration/editor/ConfigEditorGui.java +++ b/Core/src/main/java/com/songoda/core/configuration/editor/ConfigEditorGui.java @@ -36,8 +36,8 @@ public class ConfigEditorGui extends SimplePagedGui { final Player player; Method configSection_getCommentString = null; boolean edits = false; - List sections = new ArrayList(); - List settings = new ArrayList(); + List sections = new ArrayList<>(); + List settings = new ArrayList<>(); protected ConfigEditorGui(Player player, JavaPlugin plugin, Gui parent, String file, MemoryConfiguration config) { this(player, plugin, parent, file, config, config); @@ -99,7 +99,7 @@ public class ConfigEditorGui extends SimplePagedGui { if (val instanceof Boolean) { // toggle switch - setButton(index, configItem(CompatibleMaterial.LEVER, ChatColor.YELLOW + settingKey, node, settingKey, String.valueOf((Boolean) val), "Click to toggle this setting"), + setButton(index, configItem(CompatibleMaterial.LEVER, ChatColor.YELLOW + settingKey, node, settingKey, String.valueOf(val), "Click to toggle this setting"), (event) -> this.toggle(event.slot, settingKey)); if ((Boolean) val) { @@ -107,7 +107,7 @@ public class ConfigEditorGui extends SimplePagedGui { } } else if (isNumber(val)) { // number dial - this.setButton(index, configItem(CompatibleMaterial.CLOCK, ChatColor.YELLOW + settingKey, node, settingKey, String.valueOf((Number) val), "Click to edit this setting"), + this.setButton(index, configItem(CompatibleMaterial.CLOCK, ChatColor.YELLOW + settingKey, node, settingKey, String.valueOf(val), "Click to edit this setting"), (event) -> { event.gui.exit(); ChatPrompt.showPrompt(plugin, event.player, "Enter a new number value for " + settingKey + ":", response -> { @@ -153,14 +153,13 @@ public class ConfigEditorGui extends SimplePagedGui { }); }); } else if (val instanceof List) { - setButton(index, configItem(CompatibleMaterial.WRITABLE_BOOK, ChatColor.YELLOW + settingKey, node, settingKey, String.format("(%d values)", ((List) val).size()), "Click to edit this setting"), - (event) -> { - event.manager.showGUI(event.player, (new ConfigEditorListEditorGui(this, settingKey, (List) val)).setOnClose((gui) -> { - if (((ConfigEditorListEditorGui) gui.gui).saveChanges) { - setList(event.slot, settingKey, ((ConfigEditorListEditorGui) gui.gui).values); - } - })); - }); + setButton(index, configItem(CompatibleMaterial.WRITABLE_BOOK, ChatColor.YELLOW + settingKey, node, settingKey, String.format("(%d values)", ((List) val).size()), "Click to edit this setting"), + (event) -> + event.manager.showGUI(event.player, (new ConfigEditorListEditorGui(this, settingKey, (List) val)).setOnClose((gui) -> { + if (((ConfigEditorListEditorGui) gui.gui).saveChanges) { + setList(event.slot, settingKey, ((ConfigEditorListEditorGui) gui.gui).values); + } + }))); } /* else { // idk. should we display uneditable values? } */ @@ -186,7 +185,7 @@ public class ConfigEditorGui extends SimplePagedGui { if (meta != null && val != null) { String valStr; if (val instanceof List) { - valStr = String.format("(%d values)", ((List) val).size()); + valStr = String.format("(%d values)", ((List) val).size()); } else { valStr = val.toString(); } @@ -280,7 +279,7 @@ public class ConfigEditorGui extends SimplePagedGui { } private boolean isNumber(Object value) { - return value != null && (value instanceof Long + return (value instanceof Long || value instanceof Integer || value instanceof Float || value instanceof Double); @@ -321,7 +320,7 @@ public class ConfigEditorGui extends SimplePagedGui { try { Object comment = configSection_getCommentString.invoke(node, path); if (comment != null) { - info = (value + "\n" + comment.toString()).split("\n"); + info = (value + "\n" + comment).split("\n"); } } catch (Exception ignore) { } diff --git a/Core/src/main/java/com/songoda/core/configuration/editor/ConfigEditorListEditorGui.java b/Core/src/main/java/com/songoda/core/configuration/editor/ConfigEditorListEditorGui.java index 94583de3..7433931c 100644 --- a/Core/src/main/java/com/songoda/core/configuration/editor/ConfigEditorListEditorGui.java +++ b/Core/src/main/java/com/songoda/core/configuration/editor/ConfigEditorListEditorGui.java @@ -29,7 +29,7 @@ public class ConfigEditorListEditorGui extends SimplePagedGui { this.setUseHeader(true); this.setItem(4, current.configItem(CompatibleMaterial.FILLED_MAP, key, current.getCurrentNode(), key, null)); this.setButton(8, GuiUtils.createButtonItem(CompatibleMaterial.OAK_DOOR, "Exit"), (event) -> event.player.closeInventory()); - this.values = new ArrayList(val); + this.values = new ArrayList<>(val); this.setButton(8, GuiUtils.createButtonItem(CompatibleMaterial.LAVA_BUCKET, ChatColor.RED + "Discard Changes"), (event) -> event.player.closeInventory()); this.setButton(0, GuiUtils.createButtonItem(CompatibleMaterial.REDSTONE, ChatColor.GREEN + "Save"), (event) -> { @@ -42,9 +42,8 @@ public class ConfigEditorListEditorGui extends SimplePagedGui { ChatPrompt.showPrompt(event.manager.getPlugin(), event.player, "Enter a new value to add:", response -> { values.add(response.getMessage().trim()); redraw(); - }).setOnClose(() -> { - event.manager.showGUI(event.player, this); }) + .setOnClose(() -> event.manager.showGUI(event.player, this)) .setOnCancel(() -> { event.player.sendMessage(ChatColor.RED + "Edit canceled"); event.manager.showGUI(event.player, this); diff --git a/Core/src/main/java/com/songoda/core/configuration/editor/PluginConfigGui.java b/Core/src/main/java/com/songoda/core/configuration/editor/PluginConfigGui.java index 9e5eafe7..5036bc10 100644 --- a/Core/src/main/java/com/songoda/core/configuration/editor/PluginConfigGui.java +++ b/Core/src/main/java/com/songoda/core/configuration/editor/PluginConfigGui.java @@ -22,7 +22,7 @@ import java.util.Map; */ public class PluginConfigGui extends SimplePagedGui { final JavaPlugin plugin; - LinkedHashMap configs = new LinkedHashMap(); + LinkedHashMap configs = new LinkedHashMap<>(); public PluginConfigGui(SongodaPlugin plugin) { this(plugin, null); @@ -59,16 +59,16 @@ public class PluginConfigGui extends SimplePagedGui { try { // can we also grab extra config from this mysterious plugin? Object more = plugin.getClass().getDeclaredMethod("getExtraConfig").invoke(plugin); - if (more != null && more instanceof List && !((List) more).isEmpty()) { + if (more instanceof List && !((List) more).isEmpty()) { try { // if we have the getExtraConfig function, we should also be able to get the file - Method method_Config_getFile = ((List) more).get(0).getClass().getDeclaredMethod("getFile"); - for (Object cfg : ((List) more)) { + Method method_Config_getFile = ((List) more).get(0).getClass().getDeclaredMethod("getFile"); + for (Object cfg : ((List) more)) { configs.put(((File) method_Config_getFile.invoke(cfg)).getName(), (MemoryConfiguration) cfg); } } catch (Exception ex) { // include a failsafe, I guess - ((List) more).forEach(cfg -> configs.put("(File " + configs.size() + ")", (MemoryConfiguration) cfg)); + ((List) more).forEach(cfg -> configs.put("(File " + configs.size() + ")", (MemoryConfiguration) cfg)); } } } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { diff --git a/Core/src/main/java/com/songoda/core/core/LocaleModule.java b/Core/src/main/java/com/songoda/core/core/LocaleModule.java index 3619434e..fce8f336 100644 --- a/Core/src/main/java/com/songoda/core/core/LocaleModule.java +++ b/Core/src/main/java/com/songoda/core/core/LocaleModule.java @@ -6,7 +6,6 @@ import org.json.simple.JSONObject; import java.io.IOException; import java.net.HttpURLConnection; -import java.net.MalformedURLException; import java.net.URL; import java.util.logging.Level; import java.util.logging.Logger; @@ -29,12 +28,12 @@ public class LocaleModule implements PluginInfoModule { downloadLocale(plugin, (String) file.get("link"), (String) file.get("name")); } } - } catch (IOException e) { - Logger.getLogger(LocaleModule.class.getName()).log(Level.INFO, "Failed to check for locale files: " + e.getMessage()); + } catch (IOException ex) { + Logger.getLogger(LocaleModule.class.getName()).log(Level.INFO, "Failed to check for locale files: " + ex.getMessage()); } } - void downloadLocale(PluginInfo plugin, String link, String fileName) throws MalformedURLException, IOException { + void downloadLocale(PluginInfo plugin, String link, String fileName) throws IOException { URL url = new URL(link); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); diff --git a/Core/src/main/java/com/songoda/core/database/DataManagerAbstract.java b/Core/src/main/java/com/songoda/core/database/DataManagerAbstract.java index d8264150..fd6a1b6f 100644 --- a/Core/src/main/java/com/songoda/core/database/DataManagerAbstract.java +++ b/Core/src/main/java/com/songoda/core/database/DataManagerAbstract.java @@ -144,7 +144,7 @@ public class DataManagerAbstract { } /** - * Queue tasks to be ran asynchronously. + * Queue tasks to be run asynchronously. * * @param runnable task to put into queue. * @param queueKey the queue key to add the runnable to. diff --git a/Core/src/main/java/com/songoda/core/gui/AnvilGui.java b/Core/src/main/java/com/songoda/core/gui/AnvilGui.java index 49996176..640c3377 100644 --- a/Core/src/main/java/com/songoda/core/gui/AnvilGui.java +++ b/Core/src/main/java/com/songoda/core/gui/AnvilGui.java @@ -75,9 +75,12 @@ public class AnvilGui extends Gui { } void updateOutputPrompt() { - final ItemStack in; - if (endPrompt != null && (in = cellItems.get(0)) != null) { - setItem(2, GuiUtils.createButtonItem(in, endPrompt)); + if (endPrompt != null) { + ItemStack in = cellItems.get(0); + + if (in != null) { + setItem(2, GuiUtils.createButtonItem(in, endPrompt)); + } } } @@ -96,15 +99,24 @@ public class AnvilGui extends Gui { createInventory(); ItemStack item; - if ((item = cellItems.get(0)) != null) { + if (cellItems.containsKey(0)) { + item = cellItems.get(0); + inventory.setItem(0, item); - } else if ((item = cellItems.get(1)) != null) { + } else if (cellItems.containsKey(1)) { + item = cellItems.get(1); + inventory.setItem(1, item); } else if (!acceptsItems) { - cellItems.put(0, item = GuiUtils.createButtonItem(CompatibleMaterial.PAPER, " ", " ")); + item = GuiUtils.createButtonItem(CompatibleMaterial.PAPER, " ", " "); + + cellItems.put(0, item); inventory.setItem(0, item); } - if ((item = cellItems.get(2)) != null) { + + if (cellItems.containsKey(2)) { + item = cellItems.get(2); + inventory.setItem(2, item); } diff --git a/Core/src/main/java/com/songoda/core/gui/BackgroundType.java b/Core/src/main/java/com/songoda/core/gui/BackgroundType.java index 5d071041..577bc4af 100644 --- a/Core/src/main/java/com/songoda/core/gui/BackgroundType.java +++ b/Core/src/main/java/com/songoda/core/gui/BackgroundType.java @@ -7,7 +7,7 @@ public enum BackgroundType { ADVENTURE, END, HUSBANDRY, NETHER, STONE; final String key; - private BackgroundType() { + BackgroundType() { this.key = "minecraft:textures/gui/advancements/backgrounds/" + name().toLowerCase() + ".png"; } } diff --git a/Core/src/main/java/com/songoda/core/gui/CustomizableGui.java b/Core/src/main/java/com/songoda/core/gui/CustomizableGui.java index b68e757b..cc2fb1ac 100644 --- a/Core/src/main/java/com/songoda/core/gui/CustomizableGui.java +++ b/Core/src/main/java/com/songoda/core/gui/CustomizableGui.java @@ -898,11 +898,11 @@ public class CustomizableGui extends Gui { } public int applyPositionRow(int row) { - return row == -1 ? row : row; + return row; } public int applyPositionCol(int col) { - return col == -1 ? col : col; + return col; } } diff --git a/Core/src/main/java/com/songoda/core/gui/DoubleGui.java b/Core/src/main/java/com/songoda/core/gui/DoubleGui.java index 197ccbc6..1d2dc0e9 100644 --- a/Core/src/main/java/com/songoda/core/gui/DoubleGui.java +++ b/Core/src/main/java/com/songoda/core/gui/DoubleGui.java @@ -28,7 +28,7 @@ import java.util.Map; public class DoubleGui extends Gui { protected boolean startStashed = true; protected int playerRows = 4; - protected Map stash = new HashMap(); + protected Map stash = new HashMap<>(); public DoubleGui() { super(GuiType.STANDARD); @@ -244,7 +244,7 @@ public class DoubleGui extends Gui { } public DoubleGui clearPlayerActions(int cell) { - conditionalButtons.remove(cell = invOffset(cell)); + conditionalButtons.remove(invOffset(cell)); return this; } @@ -301,7 +301,7 @@ public class DoubleGui extends Gui { return false; } - event.setCancelled(!unlockedCells.entrySet().stream().anyMatch(e -> offsetCell == e.getKey() && e.getValue())); + event.setCancelled(unlockedCells.entrySet().stream().noneMatch(e -> offsetCell == e.getKey() && e.getValue())); return true; } diff --git a/Core/src/main/java/com/songoda/core/gui/Gui.java b/Core/src/main/java/com/songoda/core/gui/Gui.java index bd3b5f0a..0625dbab 100644 --- a/Core/src/main/java/com/songoda/core/gui/Gui.java +++ b/Core/src/main/java/com/songoda/core/gui/Gui.java @@ -96,12 +96,12 @@ public class Gui { @NotNull public List getPlayers() { if (inventory == null) { - return Collections.EMPTY_LIST; + return Collections.emptyList(); } return inventory.getViewers().stream() - .filter(e -> e instanceof Player) - .map(e -> (Player) e) + .filter(Player.class::isInstance) + .map(Player.class::cast) .collect(Collectors.toList()); } @@ -158,8 +158,8 @@ public class Gui { open = false; inventory.getViewers().stream() - .filter(e -> e instanceof Player) - .map(e -> (Player) e) + .filter(Player.class::isInstance) + .map(Player.class::cast) .collect(Collectors.toList()) .forEach(Player::closeInventory); } @@ -171,8 +171,8 @@ public class Gui { allowClose = true; inventory.getViewers().stream() - .filter(e -> e instanceof Player) - .map(e -> (Player) e) + .filter(Player.class::isInstance) + .map(Player.class::cast) .collect(Collectors.toList()) .forEach(Player::closeInventory); } @@ -660,7 +660,7 @@ public class Gui { } protected void setConditional(int cell, @Nullable ClickType type, @Nullable Clickable action) { - Map conditionals = conditionalButtons.computeIfAbsent(cell, k -> new HashMap()); + Map conditionals = conditionalButtons.computeIfAbsent(cell, k -> new HashMap<>()); conditionals.put(type, action); } diff --git a/Core/src/main/java/com/songoda/core/gui/GuiManager.java b/Core/src/main/java/com/songoda/core/gui/GuiManager.java index 48a3dae5..66256a50 100644 --- a/Core/src/main/java/com/songoda/core/gui/GuiManager.java +++ b/Core/src/main/java/com/songoda/core/gui/GuiManager.java @@ -33,7 +33,7 @@ public class GuiManager { final Plugin plugin; final UUID uuid = UUID.randomUUID(); // manager tracking to fix weird bugs from lazy programming final GuiListener listener = new GuiListener(this); - final Map openInventories = new HashMap(); + final Map openInventories = new HashMap<>(); private final Object lock = new Object(); private boolean initialized = false; private boolean shutdown = false; diff --git a/Core/src/main/java/com/songoda/core/gui/GuiType.java b/Core/src/main/java/com/songoda/core/gui/GuiType.java index 3c4bd634..f8310025 100644 --- a/Core/src/main/java/com/songoda/core/gui/GuiType.java +++ b/Core/src/main/java/com/songoda/core/gui/GuiType.java @@ -11,7 +11,7 @@ public enum GuiType { protected final int rows; protected final int columns; - private GuiType(InventoryType type, int rows, int columns) { + GuiType(InventoryType type, int rows, int columns) { this.type = type; this.rows = rows; this.columns = columns; diff --git a/Core/src/main/java/com/songoda/core/gui/GuiUtils.java b/Core/src/main/java/com/songoda/core/gui/GuiUtils.java index 55c46e6f..8a38f89b 100644 --- a/Core/src/main/java/com/songoda/core/gui/GuiUtils.java +++ b/Core/src/main/java/com/songoda/core/gui/GuiUtils.java @@ -53,7 +53,7 @@ public class GuiUtils { */ public static List getSafeLore(List lines) { // fix newlines - ArrayList newLore = new ArrayList(); + ArrayList newLore = new ArrayList<>(); for (String l : lines) { for (String l2 : l.split("\n")) { @@ -108,7 +108,7 @@ public class GuiUtils { if (lore != null) { meta.setLore(getSafeLore(lore)); } else { - meta.setLore(Collections.EMPTY_LIST); + meta.setLore(Collections.emptyList()); } item.setItemMeta(meta); @@ -129,7 +129,7 @@ public class GuiUtils { if (lore != null) { meta.setLore(getSafeLore(lore)); } else { - meta.setLore(Collections.EMPTY_LIST); + meta.setLore(Collections.emptyList()); } item.setItemMeta(meta); @@ -148,7 +148,7 @@ public class GuiUtils { if (lore != null) { meta.setLore(getSafeLore(lore)); } else { - meta.setLore(Collections.EMPTY_LIST); + meta.setLore(Collections.emptyList()); } item.setItemMeta(meta); @@ -167,7 +167,7 @@ public class GuiUtils { if (lore != null) { meta.setLore(getSafeLore(lore)); } else { - meta.setLore(Collections.EMPTY_LIST); + meta.setLore(Collections.emptyList()); } item.setItemMeta(meta); @@ -188,7 +188,7 @@ public class GuiUtils { if (lore != null) { meta.setLore(getSafeLore(lore)); } else { - meta.setLore(Collections.EMPTY_LIST); + meta.setLore(Collections.emptyList()); } item.setItemMeta(meta); @@ -207,7 +207,7 @@ public class GuiUtils { if (lore != null) { meta.setLore(getSafeLore(lore)); } else { - meta.setLore(Collections.EMPTY_LIST); + meta.setLore(Collections.emptyList()); } item.setItemMeta(meta); @@ -227,7 +227,7 @@ public class GuiUtils { meta.setDisplayName(safe.get(0)); meta.setLore(safe.subList(1, safe.size())); } else { - meta.setLore(Collections.EMPTY_LIST); + meta.setLore(Collections.emptyList()); } item.setItemMeta(meta); @@ -249,7 +249,7 @@ public class GuiUtils { meta.setDisplayName(safe.get(0)); meta.setLore(safe.subList(1, safe.size())); } else { - meta.setLore(Collections.EMPTY_LIST); + meta.setLore(Collections.emptyList()); } item.setItemMeta(meta); @@ -269,7 +269,7 @@ public class GuiUtils { meta.setDisplayName(safe.get(0)); meta.setLore(safe.subList(1, safe.size())); } else { - meta.setLore(Collections.EMPTY_LIST); + meta.setLore(Collections.emptyList()); } item.setItemMeta(meta); @@ -289,7 +289,7 @@ public class GuiUtils { meta.setDisplayName(safe.get(0)); meta.setLore(safe.subList(1, safe.size())); } else { - meta.setLore(Collections.EMPTY_LIST); + meta.setLore(Collections.emptyList()); } item.setItemMeta(meta); @@ -310,7 +310,7 @@ public class GuiUtils { meta.setDisplayName(safe.get(0)); meta.setLore(safe.subList(1, safe.size())); } else { - meta.setLore(Collections.EMPTY_LIST); + meta.setLore(Collections.emptyList()); } item.setItemMeta(meta); @@ -330,7 +330,7 @@ public class GuiUtils { meta.setDisplayName(safe.get(0)); meta.setLore(safe.subList(1, safe.size())); } else { - meta.setLore(Collections.EMPTY_LIST); + meta.setLore(Collections.emptyList()); } item.setItemMeta(meta); @@ -348,7 +348,7 @@ public class GuiUtils { if (lore != null) { meta.setLore(getSafeLore(lore)); } else { - meta.setLore(Collections.EMPTY_LIST); + meta.setLore(Collections.emptyList()); } item.setItemMeta(meta); @@ -375,7 +375,7 @@ public class GuiUtils { if (lore != null && lore.length != 0) { meta.setLore(getSafeLore(lore)); } else { - meta.setLore(Collections.EMPTY_LIST); + meta.setLore(Collections.emptyList()); } item.setItemMeta(meta); @@ -391,7 +391,7 @@ public class GuiUtils { if (lore != null) { meta.setLore(getSafeLore(lore)); } else { - meta.setLore(Collections.EMPTY_LIST); + meta.setLore(Collections.emptyList()); } item.setItemMeta(meta); @@ -413,7 +413,7 @@ public class GuiUtils { if (lore != null) { meta.setLore(getSafeLore(lore)); } else { - meta.setLore(Collections.EMPTY_LIST); + meta.setLore(Collections.emptyList()); } item.setItemMeta(meta); @@ -435,7 +435,7 @@ public class GuiUtils { if (lore != null) { meta.setLore(getSafeLore(lore)); } else { - meta.setLore(Collections.EMPTY_LIST); + meta.setLore(Collections.emptyList()); } item.setItemMeta(meta); @@ -453,7 +453,7 @@ public class GuiUtils { if (lore != null) { meta.setLore(getSafeLore(lore)); } else { - meta.setLore(Collections.EMPTY_LIST); + meta.setLore(Collections.emptyList()); } item.setItemMeta(meta); @@ -475,7 +475,7 @@ public class GuiUtils { if (lore != null) { meta.setLore(getSafeLore(lore)); } else { - meta.setLore(Collections.EMPTY_LIST); + meta.setLore(Collections.emptyList()); } item.setItemMeta(meta); @@ -497,7 +497,7 @@ public class GuiUtils { if (lore != null) { meta.setLore(getSafeLore(lore)); } else { - meta.setLore(Collections.EMPTY_LIST); + meta.setLore(Collections.emptyList()); } item.setItemMeta(meta); diff --git a/Core/src/main/java/com/songoda/core/gui/PopupMessage.java b/Core/src/main/java/com/songoda/core/gui/PopupMessage.java index 28d329ad..47e193b4 100644 --- a/Core/src/main/java/com/songoda/core/gui/PopupMessage.java +++ b/Core/src/main/java/com/songoda/core/gui/PopupMessage.java @@ -25,7 +25,7 @@ import java.util.UUID; */ class PopupMessage { private static final Gson gson = new GsonBuilder().setPrettyPrinting().create(); - private static final HashSet registeredMessages = new HashSet(); + private static final HashSet registeredMessages = new HashSet<>(); final UUID id = UUID.randomUUID(); private final NamespacedKey key; @@ -92,7 +92,9 @@ class PopupMessage { final AdvancementProgress progress = pl.getAdvancementProgress(adv); if (!progress.isDone()) { - progress.getRemainingCriteria().forEach((crit) -> progress.awardCriteria(crit)); + for (String s : progress.getRemainingCriteria()) { + progress.awardCriteria(s); + } } } @@ -101,7 +103,9 @@ class PopupMessage { final AdvancementProgress prog = pl.getAdvancementProgress(adv); if (prog.isDone()) { - prog.getAwardedCriteria().forEach((crit) -> prog.revokeCriteria(crit)); + for (String s : prog.getAwardedCriteria()) { + prog.revokeCriteria(s); + } } } @@ -128,19 +132,19 @@ class PopupMessage { return Bukkit.getAdvancement(key); } - public static enum FrameType { + public enum FrameType { TASK, CHALLENGE, GOAL; final String id; - private FrameType() { + FrameType() { id = name().toLowerCase(); } } - public static enum TriggerType { + public enum TriggerType { ARBITRARY_PLAYER_TICK(ServerVersion.V1_13, "TICK"), BRED_ANIMALS, BREWED_POTION, @@ -175,13 +179,13 @@ class PopupMessage { final String compatible; final String key; - private TriggerType() { + TriggerType() { this.minVersion = ServerVersion.UNKNOWN; this.compatible = ""; this.key = "minecraft:" + name().toLowerCase(); } - private TriggerType(ServerVersion minVersion, String compatible) { + TriggerType(ServerVersion minVersion, String compatible) { this.minVersion = minVersion; this.compatible = compatible; this.key = "minecraft:" + (ServerVersion.isServerVersionAtLeast(minVersion) ? name() : compatible).toLowerCase(); diff --git a/Core/src/main/java/com/songoda/core/gui/SimplePagedGui.java b/Core/src/main/java/com/songoda/core/gui/SimplePagedGui.java index d1612962..3f3f9854 100644 --- a/Core/src/main/java/com/songoda/core/gui/SimplePagedGui.java +++ b/Core/src/main/java/com/songoda/core/gui/SimplePagedGui.java @@ -135,7 +135,7 @@ public class SimplePagedGui extends Gui { // calculate pages here rowsPerPage = useHeader ? 4 : 5; - maxCellSlot = (this.cellItems.isEmpty() ? 0 : this.cellItems.keySet().stream().max(Integer::compare).get()) + 1; + maxCellSlot = this.cellItems.keySet().stream().max(Integer::compare).orElse(0) + 1; int maxRows = (int) Math.ceil(maxCellSlot / 9.); pages = (int) Math.max(1, Math.ceil(maxRows / (double) rowsPerPage)); this.setRows(maxRows + (useHeader ? 1 : 0)); @@ -217,7 +217,7 @@ public class SimplePagedGui extends Gui { // footer row conditionals = conditionalButtons.get(cell - (rows * 9)); } else { - int cellIndex = page == 1 || (useHeader && cell < 9) ? cell : (cell + (page - 1) * (rowsPerPage * 9)); + int cellIndex = page == 1 ? cell : cell + (page - 1) * rowsPerPage * 9; conditionals = conditionalButtons.get(cellIndex); } diff --git a/Core/src/main/java/com/songoda/core/hooks/Hook.java b/Core/src/main/java/com/songoda/core/hooks/Hook.java index 647eadeb..533d434d 100644 --- a/Core/src/main/java/com/songoda/core/hooks/Hook.java +++ b/Core/src/main/java/com/songoda/core/hooks/Hook.java @@ -4,12 +4,12 @@ public interface Hook { /** * Get the name of the plugin being used */ - abstract String getName(); + String getName(); /** * Check to see if the economy plugin being used is active * * @return true if the plugin is loaded and active */ - abstract boolean isEnabled(); + boolean isEnabled(); } diff --git a/Core/src/main/java/com/songoda/core/hooks/HookManager.java b/Core/src/main/java/com/songoda/core/hooks/HookManager.java index 425cc706..4bdbf462 100644 --- a/Core/src/main/java/com/songoda/core/hooks/HookManager.java +++ b/Core/src/main/java/com/songoda/core/hooks/HookManager.java @@ -37,7 +37,7 @@ public class HookManager { .collect(Collectors.toMap(Map.Entry::getKey, e -> (T) e.getValue()))); if (!registeredHooks.isEmpty()) { - defaultHook = (T) registeredHooks.values().iterator().next(); + defaultHook = registeredHooks.values().iterator().next(); } loaded = true; @@ -107,7 +107,7 @@ public class HookManager { } final String plugin = name.trim(); - return (T) registeredHooks.get(registeredHooks.keySet().stream() + return registeredHooks.get(registeredHooks.keySet().stream() .filter(type -> type.plugin.equalsIgnoreCase(plugin)) .findFirst().orElse(null)); } diff --git a/Core/src/main/java/com/songoda/core/hooks/JobsHook.java b/Core/src/main/java/com/songoda/core/hooks/JobsHook.java index 2c6145fc..2a09412d 100644 --- a/Core/src/main/java/com/songoda/core/hooks/JobsHook.java +++ b/Core/src/main/java/com/songoda/core/hooks/JobsHook.java @@ -40,7 +40,7 @@ public class JobsHook { return JobsHandler.getJobs(); } - return Collections.EMPTY_LIST; + return Collections.emptyList(); } public static double getBoostExp(Player player, String job) { @@ -166,7 +166,7 @@ public class JobsHook { return jPlayer.getJobs(); } - return Collections.EMPTY_LIST; + return Collections.emptyList(); } public static void eatItem(Player player, ItemStack item) { diff --git a/Core/src/main/java/com/songoda/core/hooks/McMMOHook.java b/Core/src/main/java/com/songoda/core/hooks/McMMOHook.java index c8a6f371..27ee31f8 100644 --- a/Core/src/main/java/com/songoda/core/hooks/McMMOHook.java +++ b/Core/src/main/java/com/songoda/core/hooks/McMMOHook.java @@ -184,46 +184,46 @@ public class McMMOHook { } public static boolean hasHerbalismDoubleDrops(Player player) { - return canHook ? McMMOHandler.hasHerbalismDoubleDrops(player) : false; + return canHook && McMMOHandler.hasHerbalismDoubleDrops(player); } public static boolean hasMiningDoubleDrops(Player player) { - return canHook ? McMMOHandler.hasMiningDoubleDrops(player) : false; + return canHook && McMMOHandler.hasMiningDoubleDrops(player); } public static boolean hasWoodcuttingDoubleDrops(Player player) { - return canHook ? McMMOHandler.hasWoodcuttingDoubleDrops(player) : false; + return canHook && McMMOHandler.hasWoodcuttingDoubleDrops(player); } public static boolean isUsingBerserk(Player player) { - return canHook ? McMMOHandler.isUsingBerserk(player) : false; + return canHook && McMMOHandler.isUsingBerserk(player); } public static boolean isUsingGigaDrill(Player player) { - return canHook ? McMMOHandler.isUsingGigaDrill(player) : false; + return canHook && McMMOHandler.isUsingGigaDrill(player); } public static boolean isUsingGreenTerra(Player player) { - return canHook ? McMMOHandler.isUsingGreenTerra(player) : false; + return canHook && McMMOHandler.isUsingGreenTerra(player); } public static boolean isUsingSerratedStrikes(Player player) { - return canHook ? McMMOHandler.isUsingSerratedStrikes(player) : false; + return canHook && McMMOHandler.isUsingSerratedStrikes(player); } public static boolean isUsingSkullSplitter(Player player) { - return canHook ? McMMOHandler.isUsingSkullSplitter(player) : false; + return canHook && McMMOHandler.isUsingSkullSplitter(player); } public static boolean isUsingSuperBreaker(Player player) { - return canHook ? McMMOHandler.isUsingSuperBreaker(player) : false; + return canHook && McMMOHandler.isUsingSuperBreaker(player); } public static boolean isUsingTreeFeller(Player player) { - return canHook ? McMMOHandler.isUsingTreeFeller(player) : false; + return canHook && McMMOHandler.isUsingTreeFeller(player); } public static boolean isBleeding(LivingEntity victim) { - return canHook ? McMMOHandler.isBleeding(victim) : false; + return canHook && McMMOHandler.isBleeding(victim); } } diff --git a/Core/src/main/java/com/songoda/core/hooks/PluginHook.java b/Core/src/main/java/com/songoda/core/hooks/PluginHook.java index 4be5c554..ab7be28c 100644 --- a/Core/src/main/java/com/songoda/core/hooks/PluginHook.java +++ b/Core/src/main/java/com/songoda/core/hooks/PluginHook.java @@ -70,7 +70,7 @@ public final class PluginHook { this.managerClass = handler; if (hooks == null) { - hooks = new LinkedHashMap(); + hooks = new LinkedHashMap<>(); } hooks.put(handler, this); diff --git a/Core/src/main/java/com/songoda/core/hooks/WorldGuardHook.java b/Core/src/main/java/com/songoda/core/hooks/WorldGuardHook.java index 01a2b910..5e86fb09 100644 --- a/Core/src/main/java/com/songoda/core/hooks/WorldGuardHook.java +++ b/Core/src/main/java/com/songoda/core/hooks/WorldGuardHook.java @@ -146,7 +146,7 @@ public class WorldGuardHook { */ @NotNull public static List getRegionNames(@NotNull Location loc) { - return canHook ? WorldGuardRegionHandler.getRegionNames(loc) : Collections.EMPTY_LIST; + return canHook ? WorldGuardRegionHandler.getRegionNames(loc) : Collections.emptyList(); } /** @@ -156,6 +156,6 @@ public class WorldGuardHook { */ @NotNull public static List getRegionNames(@NotNull Chunk c) { - return canHook ? WorldGuardRegionHandler.getRegionNames(c) : Collections.EMPTY_LIST; + return canHook ? WorldGuardRegionHandler.getRegionNames(c) : Collections.emptyList(); } } diff --git a/Core/src/main/java/com/songoda/core/hooks/economies/ReserveEconomy.java b/Core/src/main/java/com/songoda/core/hooks/economies/ReserveEconomy.java index f46a9035..e433fd48 100644 --- a/Core/src/main/java/com/songoda/core/hooks/economies/ReserveEconomy.java +++ b/Core/src/main/java/com/songoda/core/hooks/economies/ReserveEconomy.java @@ -32,16 +32,16 @@ public class ReserveEconomy extends Economy { @Override public boolean hasBalance(OfflinePlayer player, double cost) { - return economyAPI.hasHoldings(player.getUniqueId(), new BigDecimal(cost)); + return economyAPI.hasHoldings(player.getUniqueId(), BigDecimal.valueOf(cost)); } @Override public boolean withdrawBalance(OfflinePlayer player, double cost) { - return economyAPI.removeHoldings(player.getUniqueId(), new BigDecimal(cost)); + return economyAPI.removeHoldings(player.getUniqueId(), BigDecimal.valueOf(cost)); } @Override public boolean deposit(OfflinePlayer player, double amount) { - return economyAPI.addHoldings(player.getUniqueId(), new BigDecimal(amount)); + return economyAPI.addHoldings(player.getUniqueId(), BigDecimal.valueOf(amount)); } } diff --git a/Core/src/main/java/com/songoda/core/hooks/holograms/HologramsHolograms.java b/Core/src/main/java/com/songoda/core/hooks/holograms/HologramsHolograms.java index 76ec8fc4..9472e16d 100644 --- a/Core/src/main/java/com/songoda/core/hooks/holograms/HologramsHolograms.java +++ b/Core/src/main/java/com/songoda/core/hooks/holograms/HologramsHolograms.java @@ -126,8 +126,6 @@ public class HologramsHolograms extends Holograms { hologramPlugin.getHologramManager().addActiveHologram(hologram); - if (!ourHolograms.contains(id)) { - ourHolograms.add(id); - } + ourHolograms.add(id); } } diff --git a/Core/src/main/java/com/songoda/core/hooks/jobs/JobsHandler.java b/Core/src/main/java/com/songoda/core/hooks/jobs/JobsHandler.java index fd9802dc..2ea68e0a 100644 --- a/Core/src/main/java/com/songoda/core/hooks/jobs/JobsHandler.java +++ b/Core/src/main/java/com/songoda/core/hooks/jobs/JobsHandler.java @@ -1,12 +1,13 @@ package com.songoda.core.hooks.jobs; import com.gamingmesh.jobs.Jobs; +import com.gamingmesh.jobs.container.Job; import java.util.List; import java.util.stream.Collectors; public class JobsHandler { public static List getJobs() { - return Jobs.getJobs().stream().map(j -> j.getName()).collect(Collectors.toList()); + return Jobs.getJobs().stream().map(Job::getName).collect(Collectors.toList()); } } diff --git a/Core/src/main/java/com/songoda/core/hooks/jobs/JobsPlayerHandler.java b/Core/src/main/java/com/songoda/core/hooks/jobs/JobsPlayerHandler.java index 5e928045..2ba41585 100644 --- a/Core/src/main/java/com/songoda/core/hooks/jobs/JobsPlayerHandler.java +++ b/Core/src/main/java/com/songoda/core/hooks/jobs/JobsPlayerHandler.java @@ -149,7 +149,7 @@ public class JobsPlayerHandler { } public void tameEntity(LivingEntity entity) { - Jobs.action(jPlayer, new EntityActionInfo((Entity) entity, ActionType.TAME)); + Jobs.action(jPlayer, new EntityActionInfo(entity, ActionType.TAME)); } public void catchFish(ItemStack items) { diff --git a/Core/src/main/java/com/songoda/core/hooks/mcmmo/McMMOHandler.java b/Core/src/main/java/com/songoda/core/hooks/mcmmo/McMMOHandler.java index 51b716c4..b14102dd 100644 --- a/Core/src/main/java/com/songoda/core/hooks/mcmmo/McMMOHandler.java +++ b/Core/src/main/java/com/songoda/core/hooks/mcmmo/McMMOHandler.java @@ -88,7 +88,7 @@ public class McMMOHandler { return; } - ArrayList blockStates = blocks.stream().map(b -> b.getState()).collect(Collectors.toCollection(ArrayList::new)); + ArrayList blockStates = blocks.stream().map(Block::getState).collect(Collectors.toCollection(ArrayList::new)); ExperienceAPI.addXpFromBlocksBySkill(blockStates, UserManager.getPlayer(player), PrimarySkillType.MINING); } @@ -102,7 +102,7 @@ public class McMMOHandler { return; } - ArrayList blockStates = blocks.stream().map(b -> b.getState()).collect(Collectors.toCollection(ArrayList::new)); + ArrayList blockStates = blocks.stream().map(Block::getState).collect(Collectors.toCollection(ArrayList::new)); ExperienceAPI.addXpFromBlocksBySkill(blockStates, UserManager.getPlayer(player), PrimarySkillType.EXCAVATION); } @@ -116,7 +116,7 @@ public class McMMOHandler { return; } - ArrayList blockStates = blocks.stream().map(b -> b.getState()).collect(Collectors.toCollection(ArrayList::new)); + ArrayList blockStates = blocks.stream().map(Block::getState).collect(Collectors.toCollection(ArrayList::new)); ExperienceAPI.addXpFromBlocksBySkill(blockStates, UserManager.getPlayer(player), PrimarySkillType.HERBALISM); } @@ -130,7 +130,7 @@ public class McMMOHandler { return; } - ArrayList blockStates = blocks.stream().map(b -> b.getState()).collect(Collectors.toCollection(ArrayList::new)); + ArrayList blockStates = blocks.stream().map(Block::getState).collect(Collectors.toCollection(ArrayList::new)); ExperienceAPI.addXpFromBlocksBySkill(blockStates, UserManager.getPlayer(player), PrimarySkillType.WOODCUTTING); } diff --git a/Core/src/main/java/com/songoda/core/hooks/worldguard/WorldGuardFlagHandler.java b/Core/src/main/java/com/songoda/core/hooks/worldguard/WorldGuardFlagHandler.java index 34f60dcd..7bd008b4 100644 --- a/Core/src/main/java/com/songoda/core/hooks/worldguard/WorldGuardFlagHandler.java +++ b/Core/src/main/java/com/songoda/core/hooks/worldguard/WorldGuardFlagHandler.java @@ -6,7 +6,6 @@ import com.sk89q.worldguard.LocalPlayer; import com.sk89q.worldguard.WorldGuard; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; import com.sk89q.worldguard.protection.ApplicableRegionSet; -import com.sk89q.worldguard.protection.association.RegionAssociable; import com.sk89q.worldguard.protection.flags.Flag; import com.sk89q.worldguard.protection.flags.StateFlag; import com.sk89q.worldguard.protection.flags.StateFlag.State; @@ -40,7 +39,7 @@ public class WorldGuardFlagHandler { static boolean legacy_v62 = false; static boolean legacy_v5 = false; static boolean hooksInstalled = false; - static Map flags = new HashMap(); + static Map flags = new HashMap<>(); static { if (wgPlugin = (worldGuardPlugin = Bukkit.getPluginManager().getPlugin("WorldGuard")) != null) { @@ -99,7 +98,7 @@ public class WorldGuardFlagHandler { Bukkit.getServer().getLogger().log(Level.WARNING, "Could not add flag {0} to WorldGuard", addFlag.getName()); Object wgFlag = WorldGuard.getInstance().getFlagRegistry().get(addFlag.getName()); - if (wgFlag == null || !(wgFlag instanceof StateFlag)) { + if (!(wgFlag instanceof StateFlag)) { wgPlugin = false; Bukkit.getServer().getLogger().log(Level.WARNING, "Could not hook WorldGuard"); } else { @@ -118,7 +117,7 @@ public class WorldGuardFlagHandler { Field flagField = defaultFlagClazz.getField("flagsList"); Flag[] flagsOld = (Flag[]) flagField.get(null); Flag wgFlag = Stream.of(flagsOld) - .filter(f -> ((Flag) f).getName().equalsIgnoreCase(flag)) + .filter(f -> f.getName().equalsIgnoreCase(flag)) .findFirst().orElse(null); if (wgFlag != null) { @@ -288,7 +287,7 @@ public class WorldGuardFlagHandler { BlockVector3.at((c.getX() << 4) + 15, 0, (c.getZ() << 4) + 15)); ApplicableRegionSet set = worldManager.getApplicableRegions(chunkRegion); - State result = set.queryState((RegionAssociable) null, (StateFlag) flagObj); + State result = set.queryState(null, (StateFlag) flagObj); if (result == null && set.size() == 0) { return null; @@ -335,7 +334,7 @@ public class WorldGuardFlagHandler { } // grab the applicable manager for this world - Object worldManager = (RegionManager) legacy_getRegionManager.invoke(worldGuardPlugin, l.getWorld()); + Object worldManager = legacy_getRegionManager.invoke(worldGuardPlugin, l.getWorld()); if (worldManager == null) { return null; } @@ -348,7 +347,7 @@ public class WorldGuardFlagHandler { // so what's the verdict? State result; if (legacy_v62 || legacy_v60) { - result = (State) ((ApplicableRegionSet) set).queryState((RegionAssociable) null, (StateFlag) flag); + result = ((ApplicableRegionSet) set).queryState(null, (StateFlag) flag); } else { // v5 has a different class signature for ApplicableRegionSet // also doesn't have a "queryState" function @@ -394,7 +393,7 @@ public class WorldGuardFlagHandler { } // grab the applicable manager for this world - Object worldManager = (RegionManager) legacy_getRegionManager.invoke(worldGuardPlugin, c.getWorld()); + Object worldManager = legacy_getRegionManager.invoke(worldGuardPlugin, c.getWorld()); if (worldManager == null) { return null; } @@ -410,7 +409,7 @@ public class WorldGuardFlagHandler { // so what's the verdict? State result; if (legacy_v62 || legacy_v60) { - result = (State) ((ApplicableRegionSet) set).queryState((RegionAssociable) null, (StateFlag) flag); + result = ((ApplicableRegionSet) set).queryState(null, (StateFlag) flag); } else { // v5 has a different class signature for ApplicableRegionSet // also doesn't have a "queryState" function @@ -422,7 +421,7 @@ public class WorldGuardFlagHandler { result = (State) legacy5_applicableRegionSet_getFlag.invoke(set, flag); } - if (result == null && set != null && ((Iterable) set).iterator().hasNext()) { + if (result == null && set != null && ((Iterable) set).iterator().hasNext()) { return null; } diff --git a/Core/src/main/java/com/songoda/core/hooks/worldguard/WorldGuardRegionHandler.java b/Core/src/main/java/com/songoda/core/hooks/worldguard/WorldGuardRegionHandler.java index 963a8d99..aea3a2e5 100644 --- a/Core/src/main/java/com/songoda/core/hooks/worldguard/WorldGuardRegionHandler.java +++ b/Core/src/main/java/com/songoda/core/hooks/worldguard/WorldGuardRegionHandler.java @@ -97,7 +97,7 @@ public class WorldGuardRegionHandler { } if (!wgPlugin || c == null) { - return Collections.EMPTY_LIST; + return Collections.emptyList(); } if (legacy_v62 || legacy_v60 || legacy_v5) { @@ -107,7 +107,7 @@ public class WorldGuardRegionHandler { RegionManager worldManager = WorldGuard.getInstance().getPlatform().getRegionContainer().get(BukkitAdapter.adapt(c.getWorld())); if (worldManager == null) { - return Collections.EMPTY_LIST; + return Collections.emptyList(); } ProtectedCuboidRegion chunkRegion = new ProtectedCuboidRegion("__TEST__", @@ -139,7 +139,7 @@ public class WorldGuardRegionHandler { private static List getRegionNamesLegacy(Chunk c) { try { // grab the applicable manager for this world - Object worldManager = (RegionManager) legacy_getRegionManager.invoke(worldGuardPlugin, c.getWorld()); + Object worldManager = legacy_getRegionManager.invoke(worldGuardPlugin, c.getWorld()); if (worldManager == null) { return null; @@ -177,7 +177,7 @@ public class WorldGuardRegionHandler { Bukkit.getServer().getLogger().log(Level.WARNING, "Could not grab regions from WorldGuard", ex); } - return Collections.EMPTY_LIST; + return Collections.emptyList(); } public static List getRegionNames(Location loc) { @@ -186,7 +186,7 @@ public class WorldGuardRegionHandler { } if (!wgPlugin || loc == null) { - return Collections.EMPTY_LIST; + return Collections.emptyList(); } if (legacy_v62 || legacy_v60 || legacy_v5) { @@ -196,7 +196,7 @@ public class WorldGuardRegionHandler { RegionManager regionManager = WorldGuard.getInstance().getPlatform().getRegionContainer().get(BukkitAdapter.adapt(loc.getWorld())); if (regionManager == null) { - return Collections.EMPTY_LIST; + return Collections.emptyList(); } List regions = new ArrayList<>(); @@ -224,9 +224,9 @@ public class WorldGuardRegionHandler { private static List getRegionNamesLegacy(Location loc) { try { // grab the applicable manager for this world - Object worldManager = (RegionManager) legacy_getRegionManager.invoke(worldGuardPlugin, loc.getWorld()); + Object worldManager = legacy_getRegionManager.invoke(worldGuardPlugin, loc.getWorld()); if (worldManager == null) { - return Collections.EMPTY_LIST; + return Collections.emptyList(); } // create a vector object @@ -258,6 +258,6 @@ public class WorldGuardRegionHandler { Bukkit.getServer().getLogger().log(Level.WARNING, "Could not grab regions from WorldGuard", ex); } - return Collections.EMPTY_LIST; + return Collections.emptyList(); } } diff --git a/Core/src/main/java/com/songoda/core/input/ChatPrompt.java b/Core/src/main/java/com/songoda/core/input/ChatPrompt.java index ce3e3c32..ca9add4b 100644 --- a/Core/src/main/java/com/songoda/core/input/ChatPrompt.java +++ b/Core/src/main/java/com/songoda/core/input/ChatPrompt.java @@ -82,7 +82,7 @@ public class ChatPrompt implements Listener { private void startListener(Plugin plugin) { this.listener = new Listener() { - @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = false) + @EventHandler(priority = EventPriority.LOWEST) public void onChat(AsyncPlayerChatEvent event) { Player player = event.getPlayer(); @@ -111,7 +111,7 @@ public class ChatPrompt implements Listener { Bukkit.getScheduler().cancelTask(taskId); } - @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = false) + @EventHandler(priority = EventPriority.LOWEST) public void onCancel(PlayerCommandPreprocessEvent event) { Player player = event.getPlayer(); @@ -139,15 +139,15 @@ public class ChatPrompt implements Listener { Bukkit.getPluginManager().registerEvents(listener, plugin); } - public static interface ChatConfirmHandler { + public interface ChatConfirmHandler { void onChat(ChatConfirmEvent event); } - public static interface OnClose { + public interface OnClose { void onClose(); } - public static interface OnCancel { + public interface OnCancel { void onCancel(); } diff --git a/Core/src/main/java/com/songoda/core/locale/Locale.java b/Core/src/main/java/com/songoda/core/locale/Locale.java index 0dbf2519..2a07dcd3 100644 --- a/Core/src/main/java/com/songoda/core/locale/Locale.java +++ b/Core/src/main/java/com/songoda/core/locale/Locale.java @@ -139,7 +139,7 @@ public class Locale { */ public static List getLocales(Plugin plugin) { File localeFolder = new File(plugin.getDataFolder(), "locales/"); - List all = new ArrayList(); + List all = new ArrayList<>(); for (File localeFile : localeFolder.listFiles()) { String fileName = localeFile.getName(); @@ -315,7 +315,7 @@ public class Locale { // load lists as strings with newlines lang.getValues(true).forEach((k, v) -> nodes.put(k, v instanceof List - ? (((List) v).stream().map(Object::toString).collect(Collectors.joining("\n")).toString()) + ? (((List) v).stream().map(Object::toString).collect(Collectors.joining("\n"))) : v.toString())); return true; @@ -338,7 +338,7 @@ public class Locale { line1 = line; line = line.replaceAll("[\uFEFF\uFFFE\u200B]", ""); if (line1.length() != line.length()) { - output.append(line1.substring(0, line1.length() - line.length())); + output.append(line1, 0, line1.length() - line.length()); } } @@ -372,7 +372,7 @@ public class Locale { if (!msgs.isEmpty()) { try (FileInputStream stream = new FileInputStream(file); - BufferedReader source = new BufferedReader(new InputStreamReader((InputStream) stream, charset))) { + BufferedReader source = new BufferedReader(new InputStreamReader(stream, charset))) { String line; for (int lineNumber = 0; (line = source.readLine()) != null; ++lineNumber) { if (lineNumber == 0) { diff --git a/Core/src/main/java/com/songoda/core/locale/Message.java b/Core/src/main/java/com/songoda/core/locale/Message.java index 26057ecd..91aec5b3 100644 --- a/Core/src/main/java/com/songoda/core/locale/Message.java +++ b/Core/src/main/java/com/songoda/core/locale/Message.java @@ -26,7 +26,7 @@ public class Message { Player.Spigot.class.getDeclaredMethod("sendMessage", net.md_5.bungee.api.ChatMessageType.class, net.md_5.bungee.api.chat.TextComponent.class); canActionBar = true; - } catch (Exception ex) { + } catch (Exception ignore) { } } @@ -147,7 +147,7 @@ public class Message { * @return the message */ public List getMessageLines() { - return Arrays.asList(ChatColor.translateAlternateColorCodes('&', this.message.toText()).split("\n|\\|")); + return Arrays.asList(ChatColor.translateAlternateColorCodes('&', this.message.toText()).split("[\n|]")); } /** diff --git a/Core/src/main/java/com/songoda/core/lootables/gui/AbstractGuiListEditor.java b/Core/src/main/java/com/songoda/core/lootables/gui/AbstractGuiListEditor.java index 262308ac..9748d532 100644 --- a/Core/src/main/java/com/songoda/core/lootables/gui/AbstractGuiListEditor.java +++ b/Core/src/main/java/com/songoda/core/lootables/gui/AbstractGuiListEditor.java @@ -48,7 +48,7 @@ public abstract class AbstractGuiListEditor extends Gui { String validated = validate(gui.getInputText()); if (validated != null) { lore.add(validated); - updateData(lore.isEmpty() ? null : lore); + updateData(lore); e.player.closeInventory(); paint(); } diff --git a/Core/src/main/java/com/songoda/core/lootables/gui/GuiEnchantEditor.java b/Core/src/main/java/com/songoda/core/lootables/gui/GuiEnchantEditor.java index bf5fdf41..9447c3f6 100644 --- a/Core/src/main/java/com/songoda/core/lootables/gui/GuiEnchantEditor.java +++ b/Core/src/main/java/com/songoda/core/lootables/gui/GuiEnchantEditor.java @@ -59,7 +59,7 @@ public class GuiEnchantEditor extends Gui { AnvilGui gui1 = new AnvilGui(event.player, this); gui1.setAction((ee -> { lore.put(gui.getInputText().toUpperCase().trim(), Integer.parseInt(gui1.getInputText().trim())); - loot.setEnchants(lore.isEmpty() ? null : lore); + loot.setEnchants(lore); ee.player.closeInventory(); paint(); })); diff --git a/Core/src/main/java/com/songoda/core/lootables/loot/LootManager.java b/Core/src/main/java/com/songoda/core/lootables/loot/LootManager.java index 3db354b9..28abe081 100644 --- a/Core/src/main/java/com/songoda/core/lootables/loot/LootManager.java +++ b/Core/src/main/java/com/songoda/core/lootables/loot/LootManager.java @@ -39,7 +39,7 @@ public class LootManager { public void removeLootable(String key) { registeredLootables.remove(key); - File file = new File(lootables.getLootablesDir() + "/" + key.toLowerCase() + ".json"); + File file = new File(lootables.getLootablesDir(), key.toLowerCase() + ".json"); file.delete(); } @@ -189,8 +189,7 @@ public class LootManager { // Save to file for (Lootable lootable : registeredLootables.values()) { try { - File file = new File(lootables.getLootablesDir() - + "/" + lootable.getKey().toLowerCase() + ".json"); + File file = new File(lootables.getLootablesDir(), lootable.getKey().toLowerCase() + ".json"); if (file.exists() && defaults) { continue; diff --git a/Core/src/main/java/com/songoda/core/math/Eval.java b/Core/src/main/java/com/songoda/core/math/Eval.java index 6931dff7..8e15689e 100644 --- a/Core/src/main/java/com/songoda/core/math/Eval.java +++ b/Core/src/main/java/com/songoda/core/math/Eval.java @@ -99,16 +99,21 @@ public class Eval { String func = toParse.substring(startPos, this.pos); x = parseFactor(); - if (func.equals("sqrt")) { - x = Math.sqrt(x); - } else if (func.equals("sin")) { - x = Math.sin(Math.toRadians(x)); - } else if (func.equals("cos")) { - x = Math.cos(Math.toRadians(x)); - } else if (func.equals("tan")) { - x = Math.tan(Math.toRadians(x)); - } else { - throw new RuntimeException(warningMessage + "Unknown function: " + func); + switch (func) { + case "sqrt": + x = Math.sqrt(x); + break; + case "sin": + x = Math.sin(Math.toRadians(x)); + break; + case "cos": + x = Math.cos(Math.toRadians(x)); + break; + case "tan": + x = Math.tan(Math.toRadians(x)); + break; + default: + throw new RuntimeException(warningMessage + "Unknown function: " + func); } } else { throw new RuntimeException(warningMessage + "Unexpected: " + (char) ch); diff --git a/Core/src/main/java/com/songoda/core/nms/NmsManager.java b/Core/src/main/java/com/songoda/core/nms/NmsManager.java index 32d87954..680a01da 100644 --- a/Core/src/main/java/com/songoda/core/nms/NmsManager.java +++ b/Core/src/main/java/com/songoda/core/nms/NmsManager.java @@ -9,11 +9,11 @@ import java.util.logging.Level; import java.util.logging.Logger; public class NmsManager { - private final static String serverPackagePath = Bukkit.getServer().getClass().getPackage().getName(); - private final static String serverPackageVersion = serverPackagePath.substring(serverPackagePath.lastIndexOf('.') + 1); - private final static AnvilCore anvil; - private final static NBTCore nbt; - private final static WorldCore world; + private static final String serverPackagePath = Bukkit.getServer().getClass().getPackage().getName(); + private static final String serverPackageVersion = serverPackagePath.substring(serverPackagePath.lastIndexOf('.') + 1); + private static final AnvilCore anvil; + private static final NBTCore nbt; + private static final WorldCore world; static { switch (serverPackageVersion) { diff --git a/Core/src/main/java/com/songoda/core/utils/BlockUtils.java b/Core/src/main/java/com/songoda/core/utils/BlockUtils.java index cd2d69e8..a767e397 100644 --- a/Core/src/main/java/com/songoda/core/utils/BlockUtils.java +++ b/Core/src/main/java/com/songoda/core/utils/BlockUtils.java @@ -173,7 +173,7 @@ public class BlockUtils { legacySetBlockData.invoke(lever, (byte) (lever.getData() ^ 0x8)); lever.getState().update(); //lever.getWorld().playEffect(lever.getLocation(), Effect.CLICK1, 0); - // now we need to update the redstone around it.. + // now we need to update the redstone around it... // int data = lever.getData() & ~0x8; // Block attached; // switch(data) { @@ -752,9 +752,9 @@ public class BlockUtils { case "WALL_BANNER": case "BEETROOT_BLOCK": return true; + default: + return false; } - - return false; } /** @@ -763,7 +763,7 @@ public class BlockUtils { * * @param m material to check * - * @return true if this is a block that can be walked though or up + * @return true if this is a block that can be walked through or up */ public static boolean canWalkTo(Material m) { switch (m.name()) { @@ -1086,8 +1086,8 @@ public class BlockUtils { case "STONE_SLAB2": case "BEETROOT_BLOCK": return true; + default: + return false; } - - return false; } } diff --git a/Core/src/main/java/com/songoda/core/utils/ColorUtils.java b/Core/src/main/java/com/songoda/core/utils/ColorUtils.java index dafebb9f..c119f67a 100644 --- a/Core/src/main/java/com/songoda/core/utils/ColorUtils.java +++ b/Core/src/main/java/com/songoda/core/utils/ColorUtils.java @@ -29,9 +29,9 @@ public class ColorUtils { } private static class ColorSet { - R red = null; - G green = null; - B blue = null; + R red; + G green; + B blue; ColorSet(R red, G green, B blue) { this.red = red; @@ -58,6 +58,7 @@ public class ColorUtils { int red = Math.abs(r - set.getRed()); int green = Math.abs(g - set.getGreen()); int blue = Math.abs(b - set.getBlue()); + closest.put(red + green + blue, color); }); diff --git a/Core/src/main/java/com/songoda/core/utils/ItemUtils.java b/Core/src/main/java/com/songoda/core/utils/ItemUtils.java index 19507cd3..ec036ef6 100644 --- a/Core/src/main/java/com/songoda/core/utils/ItemUtils.java +++ b/Core/src/main/java/com/songoda/core/utils/ItemUtils.java @@ -1,6 +1,3 @@ -/** - * This class uses some Minecraft code and also Paper API - */ package com.songoda.core.utils; import com.mojang.authlib.GameProfile; @@ -31,6 +28,7 @@ import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.util.Arrays; import java.util.Base64; import java.util.Iterator; import java.util.List; @@ -40,6 +38,9 @@ import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Stream; +/** + * This class uses some Minecraft code and also Paper API + */ public class ItemUtils { static boolean can_getI18NDisplayName = true; @@ -367,7 +368,7 @@ public class ItemUtils { } public static void setHeadOwner(ItemStack head, OfflinePlayer player) { - if (ServerVersion.isServerVersionBelow(ServerVersion.V1_8) || head == null || !CompatibleMaterial.PLAYER_HEAD.matches(head)) { + if (ServerVersion.isServerVersionBelow(ServerVersion.V1_8) || !CompatibleMaterial.PLAYER_HEAD.matches(head)) { return; } @@ -456,9 +457,6 @@ public class ItemUtils { try { SkullMeta localSkullMeta = (SkullMeta) item.getItemMeta(); Field cb_SkullMeta_profile = localSkullMeta.getClass().getDeclaredField("profile"); - if (cb_SkullMeta_profile == null) { - return null; - } cb_SkullMeta_profile.setAccessible(true); GameProfile profile = (GameProfile) cb_SkullMeta_profile.get(localSkullMeta); @@ -559,8 +557,7 @@ public class ItemUtils { public static boolean canMove(ItemStack[] contents, ItemStack item) { final ItemMeta itemMeta = item.getItemMeta(); - for (int i = 0; i < contents.length; ++i) { - final ItemStack stack = contents[i]; + for (final ItemStack stack : contents) { if (stack == null || stack.getAmount() == 0) { return true; } @@ -788,7 +785,7 @@ public class ItemUtils { boolean[] check = null; - if (inventorySource != null && inventorySource != Material.AIR) { + if (inventorySource != Material.AIR) { // Don't transfer shulker boxes into other shulker boxes, that's a bad idea. if (inventorySource.name().contains("SHULKER_BOX") && item.getType().name().contains("SHULKER_BOX")) { return false; @@ -997,7 +994,7 @@ public class ItemUtils { boolean[] check = null; - if (inventorySource != null && inventorySource != Material.AIR) { + if (inventorySource != Material.AIR) { // Don't transfer shulker boxes into other shulker boxes, that's a bad idea. if (inventorySource.name().contains("SHULKER_BOX") && item.getType().name().contains("SHULKER_BOX")) { return false; @@ -1159,15 +1156,10 @@ public class ItemUtils { // grab the amount to move and the max item stack size int toAdd = amount; final int maxStack = item.getMaxStackSize(); - boolean[] check = null; // we can reduce calls to ItemStack.isSimilar() by caching what cells to look at - if (check == null) { - check = new boolean[containerSize]; - for (int i = 0; toAdd > 0 && i < check.length; i++) { - check[i] = true; - } - } + boolean[] check = new boolean[containerSize]; + Arrays.fill(check, true); // first verify that we can add this item for (int i = 0; toAdd > 0 && i < containerSize; i++) { diff --git a/Core/src/main/java/com/songoda/core/utils/Metrics.java b/Core/src/main/java/com/songoda/core/utils/Metrics.java index f28cc90d..36aa7dca 100644 --- a/Core/src/main/java/com/songoda/core/utils/Metrics.java +++ b/Core/src/main/java/com/songoda/core/utils/Metrics.java @@ -239,7 +239,7 @@ public class Metrics { playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class) ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; - } catch (Exception e) { + } catch (Exception ex) { playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed } int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; @@ -294,17 +294,14 @@ public class Metrics { data.put("plugins", pluginData); // Create a new thread for the connection to the bStats server - new Thread(new Runnable() { - @Override - public void run() { - try { - // Send the data - sendData(plugin, data); - } catch (Exception e) { - // Something went wrong! :( - if (logFailedRequests) { - plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); - } + new Thread(() -> { + try { + // Send the data + sendData(plugin, data); + } catch (Exception ex) { + // Something went wrong! :( + if (logFailedRequests) { + plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), ex); } } }).start(); @@ -326,7 +323,7 @@ public class Metrics { throw new IllegalAccessException("This method must not be called from the main thread!"); } if (logSentData) { - plugin.getLogger().info("Sending data to bStats: " + data.toString()); + plugin.getLogger().info("Sending data to bStats: " + data); } HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); @@ -359,7 +356,7 @@ public class Metrics { } bufferedReader.close(); if (logResponseStatusText) { - plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString()); + plugin.getLogger().info("Sent data to bStats and received response: " + builder); } } @@ -386,8 +383,7 @@ public class Metrics { /** * Represents a custom chart. */ - public static abstract class CustomChart { - + public abstract static class CustomChart { // The id of the chart final String chartId; @@ -429,7 +425,6 @@ public class Metrics { * Represents a custom simple pie. */ public static class SimplePie extends CustomChart { - private final Callable callable; /** @@ -460,7 +455,6 @@ public class Metrics { * Represents a custom advanced pie. */ public static class AdvancedPie extends CustomChart { - private final Callable> callable; /** @@ -504,7 +498,6 @@ public class Metrics { * Represents a custom drilldown pie. */ public static class DrilldownPie extends CustomChart { - private final Callable>> callable; /** @@ -553,7 +546,6 @@ public class Metrics { * Represents a custom single line chart. */ public static class SingleLineChart extends CustomChart { - private final Callable callable; /** @@ -584,7 +576,6 @@ public class Metrics { * Represents a custom multi line chart. */ public static class MultiLineChart extends CustomChart { - private final Callable> callable; /** @@ -628,7 +619,6 @@ public class Metrics { * Represents a custom simple bar chart. */ public static class SimpleBarChart extends CustomChart { - private final Callable> callable; /** @@ -639,6 +629,7 @@ public class Metrics { */ public SimpleBarChart(String chartId, Callable> callable) { super(chartId); + this.callable = callable; } @@ -665,7 +656,6 @@ public class Metrics { * Represents a custom advanced bar chart. */ public static class AdvancedBarChart extends CustomChart { - private final Callable> callable; /** diff --git a/Core/src/main/java/com/songoda/core/utils/PlayerUtils.java b/Core/src/main/java/com/songoda/core/utils/PlayerUtils.java index 17b20fbd..a0f1b665 100644 --- a/Core/src/main/java/com/songoda/core/utils/PlayerUtils.java +++ b/Core/src/main/java/com/songoda/core/utils/PlayerUtils.java @@ -53,7 +53,7 @@ public class PlayerUtils { } /** - * Get a list of all of the players that this player can "see" + * Get a list of all the players that this player can "see" * * @param sender user to check against, or null for all players * @param startingWith optional query to test: only players whose game names @@ -90,7 +90,7 @@ public class PlayerUtils { .filter(p -> p != player) .filter(p -> startsWith == null || p.getName().toLowerCase().startsWith(startsWith)) .filter(p -> player == null || (player.canSee(p) && p.getMetadata("vanished").isEmpty())) - .map(p -> (Player) p) + .map(Player.class::cast) .collect(Collectors.toList()); } @@ -120,6 +120,8 @@ public class PlayerUtils { * @return List of matching player display names */ public static List getAllPlayersDisplay(CommandSender us, String startsWith) { + // FIXME: Why do we need that regex? It just breaks the startsWith check + // + the DisplayName comparison is not made lower case final String arg = startsWith.replaceAll("[^a-zA-Z]", "").toLowerCase(); return Bukkit.getOnlinePlayers().stream() @@ -196,7 +198,7 @@ public class PlayerUtils { Map leftover = player.getInventory().addItem(item); if (!leftover.isEmpty()) { - leftover.values().stream().forEach(it -> player.getWorld().dropItemNaturally(player.getLocation(), it)); + leftover.values().forEach(it -> player.getWorld().dropItemNaturally(player.getLocation(), it)); } } @@ -210,7 +212,7 @@ public class PlayerUtils { final World world = player.getWorld(); final Location location = player.getLocation(); - leftover.values().stream().forEach(it -> world.dropItemNaturally(location, it)); + leftover.values().forEach(it -> world.dropItemNaturally(location, it)); } } @@ -219,12 +221,12 @@ public class PlayerUtils { return; } - Map leftover = player.getInventory().addItem(items.toArray(new ItemStack[items.size()])); + Map leftover = player.getInventory().addItem(items.toArray(new ItemStack[0])); if (!leftover.isEmpty()) { final World world = player.getWorld(); final Location location = player.getLocation(); - leftover.values().stream().forEach(it -> world.dropItemNaturally(location, it)); + leftover.values().forEach(it -> world.dropItemNaturally(location, it)); } } diff --git a/Core/src/main/java/com/songoda/core/utils/ReflectionUtils.java b/Core/src/main/java/com/songoda/core/utils/ReflectionUtils.java index 61542a3c..6c3972f4 100644 --- a/Core/src/main/java/com/songoda/core/utils/ReflectionUtils.java +++ b/Core/src/main/java/com/songoda/core/utils/ReflectionUtils.java @@ -211,7 +211,7 @@ public class ReflectionUtils { return packageClasses; } - public static enum ITERATION { + public enum ITERATION { NONE, CLASS, PACKAGE, FULL } @@ -234,7 +234,7 @@ public class ReflectionUtils { // http://stackoverflow.com/questions/1456930/how-do-i-read-all-classes-from-a-java-package-in-the-classpath ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); URL packageURL; - ArrayList names = new ArrayList(); + ArrayList names = new ArrayList<>(); if (packageName.contains("/")) { // load as a file @@ -284,7 +284,7 @@ public class ReflectionUtils { jarEntries = jf.entries(); // in case of multiple sub-classes, keep track of what classes have been searched - ArrayList loaded = new ArrayList(); + ArrayList loaded = new ArrayList<>(); while (jarEntries.hasMoreElements()) { entryName = jarEntries.nextElement().getName(); @@ -331,7 +331,7 @@ public class ReflectionUtils { File[] contenuti = folder.listFiles(); // in case of multiple sub-classes, keep track of what classes have been searched - ArrayList loaded = new ArrayList(); + ArrayList loaded = new ArrayList<>(); String entryName; for (File actual : contenuti) { diff --git a/Core/src/main/java/com/songoda/core/utils/RotationUtils.java b/Core/src/main/java/com/songoda/core/utils/RotationUtils.java index ec06c932..d5c8f193 100644 --- a/Core/src/main/java/com/songoda/core/utils/RotationUtils.java +++ b/Core/src/main/java/com/songoda/core/utils/RotationUtils.java @@ -7,15 +7,15 @@ public class RotationUtils { switch (face) { case NORTH: return 180F; - case SOUTH: - return 0F; case EAST: return -90F; + case SOUTH: + return 0F; case WEST: return 90F; + default: + return 0F; } - - return 0F; } public static BlockFace yawToFace(float face) { @@ -32,9 +32,9 @@ public class RotationUtils { case 90: case 450: return BlockFace.WEST; + default: + // idk + return BlockFace.SOUTH; } - - // idk - return BlockFace.SOUTH; } } diff --git a/Core/src/main/java/com/songoda/core/utils/TextUtils.java b/Core/src/main/java/com/songoda/core/utils/TextUtils.java index f604e4d8..12737b66 100644 --- a/Core/src/main/java/com/songoda/core/utils/TextUtils.java +++ b/Core/src/main/java/com/songoda/core/utils/TextUtils.java @@ -26,6 +26,7 @@ public class TextUtils { // supportedCharsets.add(StandardCharsets.UTF_16BE); // FE FF // supportedCharsets.add(StandardCharsets.UTF_16); + // FIXME: One unsupported charset causes other ones not to be tried try { supportedCharsets.add(Charset.forName("windows-1253")); supportedCharsets.add(Charset.forName("ISO-8859-7")); @@ -67,6 +68,8 @@ public class TextUtils { return wrap(null, line); } + // TODO: We might want to remove white spaces at the beginning after wrapping a substring into a new line + // TODO: Why do we accept a String as a color when we need it in a very specific format?! public static List wrap(String color, String line) { if (color != null) { color = "&" + color; @@ -97,7 +100,7 @@ public class TextUtils { /** * Convert a string to an invisible colored string that's lore-safe
* (Safe to use as lore)
- * Note: Do not use semi-colons in this string, or they will be lost when decoding! + * Note: Do not use semi-colons or § in this string, or they will be lost when decoding! * * @param s string to convert * @@ -111,7 +114,10 @@ public class TextUtils { StringBuilder hidden = new StringBuilder(); for (char c : s.toCharArray()) { - hidden.append(ChatColor.COLOR_CHAR).append(';').append(ChatColor.COLOR_CHAR).append(c); + hidden.append(ChatColor.COLOR_CHAR) + .append(';') + .append(ChatColor.COLOR_CHAR) + .append(c); } return hidden.toString(); @@ -120,7 +126,7 @@ public class TextUtils { /** * Convert a string to an invisible colored string
* (Not safe to use as lore)
- * Note: Do not use semi-colons in this string, or they will be lost when decoding! + * Note: Do not use semi-colons or § in this string, or they will be lost when decoding! * * @param s string to convert * @@ -133,12 +139,14 @@ public class TextUtils { StringBuilder hidden = new StringBuilder(); for (char c : s.toCharArray()) { - hidden.append(ChatColor.COLOR_CHAR).append(c); + hidden.append(ChatColor.COLOR_CHAR) + .append(c); } return hidden.toString(); } + // TODO: Is there a more reliable way? /** * Removes color markers used to encode strings as invisible text * @@ -158,7 +166,7 @@ public class TextUtils { byte[] buffer = new byte[2048]; int len; - // Read the first 2KiB of the file and test the file's encoding + // Read the first 2 KiB of the file and test the file's encoding try (FileInputStream input = new FileInputStream(f)) { len = input.read(buffer); } catch (Exception ex) { @@ -172,7 +180,7 @@ public class TextUtils { byte[] buffer = new byte[2048]; int len; - // Read the first 2KiB of the file and test the file's encoding + // Read the first 2 KiB of the file and test the file's encoding try { reader.mark(2048); len = reader.read(buffer); @@ -188,11 +196,11 @@ public class TextUtils { public static Charset detectCharset(byte[] data, int len, Charset def) { // check the file header if (len > 4) { - if (data[0] == (byte) 0xFF && data[1] == (byte) 0xFE) { // FF FE 00 00 is UTF-32LE + if (data[0] == (byte) 0xFF && data[1] == (byte) 0xFE) { // FF FE is UTF-16LE return StandardCharsets.UTF_16LE; - } else if (data[0] == (byte) 0xFE && data[1] == (byte) 0xFF) { // 00 00 FE FF is UTF-32BE + } else if (data[0] == (byte) 0xFE && data[1] == (byte) 0xFF) { // FE FF is UTF-16BE return StandardCharsets.UTF_16BE; - } else if (data[0] == (byte) 0xEF && data[1] == (byte) 0xBB && data[2] == (byte) 0xBF) { // UTF-8 with BOM, same sig as ISO-8859-1 + } else if (data[0] == (byte) 0xEF && data[1] == (byte) 0xBB && data[2] == (byte) 0xBF) { // UTF-8 with BOM return StandardCharsets.UTF_8; } } diff --git a/Core/src/main/java/com/songoda/core/utils/TimeUtils.java b/Core/src/main/java/com/songoda/core/utils/TimeUtils.java index 369ad9c8..2de6248c 100644 --- a/Core/src/main/java/com/songoda/core/utils/TimeUtils.java +++ b/Core/src/main/java/com/songoda/core/utils/TimeUtils.java @@ -3,6 +3,9 @@ package com.songoda.core.utils; import java.util.concurrent.TimeUnit; public class TimeUtils { + /** + * @param time In milliseconds + */ public static String makeReadable(Long time) { if (time == null) { return ""; diff --git a/Core/src/main/java/com/songoda/core/world/SItemStack.java b/Core/src/main/java/com/songoda/core/world/SItemStack.java index e90ccf80..d16d8b55 100644 --- a/Core/src/main/java/com/songoda/core/world/SItemStack.java +++ b/Core/src/main/java/com/songoda/core/world/SItemStack.java @@ -33,7 +33,7 @@ public class SItemStack { /** * Damage the selected item * - * @param player the player who's item you want to damage + * @param player the player whose item you want to damage * @param damage the amount of damage to apply to the item */ public ItemStack addDamage(Player player, int damage, boolean respectVanillaUnbreakingEnchantments) { diff --git a/NMS/NMS-API/src/main/java/com/songoda/core/nms/ReflectionUtils.java b/NMS/NMS-API/src/main/java/com/songoda/core/nms/ReflectionUtils.java index 311c60bd..5d6154e3 100644 --- a/NMS/NMS-API/src/main/java/com/songoda/core/nms/ReflectionUtils.java +++ b/NMS/NMS-API/src/main/java/com/songoda/core/nms/ReflectionUtils.java @@ -7,6 +7,7 @@ public class ReflectionUtils { throw new IllegalStateException("Utility class"); } + @SuppressWarnings("deprecation") public static Object getFieldValue(Object instance, String fieldName) throws NoSuchFieldException, IllegalAccessException { Field f = getField(instance, fieldName); boolean accessible = f.isAccessible(); @@ -20,6 +21,7 @@ public class ReflectionUtils { return result; } + @SuppressWarnings("deprecation") public static void setFieldValue(Object instance, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException { Field f = getField(instance, fieldName); boolean accessible = f.isAccessible(); diff --git a/NMS/NMS-API/src/main/java/com/songoda/core/nms/anvil/AnvilCore.java b/NMS/NMS-API/src/main/java/com/songoda/core/nms/anvil/AnvilCore.java index 04880a4f..9690e411 100644 --- a/NMS/NMS-API/src/main/java/com/songoda/core/nms/anvil/AnvilCore.java +++ b/NMS/NMS-API/src/main/java/com/songoda/core/nms/anvil/AnvilCore.java @@ -4,7 +4,7 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; public interface AnvilCore { - public CustomAnvil createAnvil(Player player); + CustomAnvil createAnvil(Player player); - public CustomAnvil createAnvil(Player player, InventoryHolder holder); + CustomAnvil createAnvil(Player player, InventoryHolder holder); } diff --git a/NMS/NMS-API/src/main/java/com/songoda/core/nms/anvil/CustomAnvil.java b/NMS/NMS-API/src/main/java/com/songoda/core/nms/anvil/CustomAnvil.java index a81fe891..4462c03e 100644 --- a/NMS/NMS-API/src/main/java/com/songoda/core/nms/anvil/CustomAnvil.java +++ b/NMS/NMS-API/src/main/java/com/songoda/core/nms/anvil/CustomAnvil.java @@ -8,43 +8,43 @@ import org.bukkit.inventory.ItemStack; * NMS interface for creating an anvil view for a single player */ public interface CustomAnvil { - public void setLevelCost(int cost); + void setLevelCost(int cost); - public int getLevelCost(); + int getLevelCost(); - public void setCanUse(boolean bool); + void setCanUse(boolean bool); - public String getCustomTitle(); + String getCustomTitle(); - public void setCustomTitle(String title); + void setCustomTitle(String title); - public String getRenameText(); + String getRenameText(); - public void setRenameText(String text); + void setRenameText(String text); - public void setOnChange(AnvilTextChange handler); + void setOnChange(AnvilTextChange handler); - public ItemStack getLeftInput(); + ItemStack getLeftInput(); - public ItemStack getRightInput(); + ItemStack getRightInput(); - public ItemStack getOutput(); + ItemStack getOutput(); - public void setLeftInput(ItemStack item); + void setLeftInput(ItemStack item); - public void setRightInput(ItemStack item); + void setRightInput(ItemStack item); - public void setOutput(ItemStack item); + void setOutput(ItemStack item); - public Inventory getInventory(); + Inventory getInventory(); /** * Open this anvil for the provided player */ - public void open(); + void open(); /** - * Force a redraw of the output + * Forces a re-draw of the output */ - public void update(); + void update(); } diff --git a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/anvil/AnvilView.java b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/anvil/AnvilView.java index ddb0db74..fd22b6a1 100644 --- a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/anvil/AnvilView.java +++ b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/anvil/AnvilView.java @@ -25,7 +25,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { private String title = "Repairing"; private int cost = -1; private boolean canUse = true; - private AnvilTextChange textChange = null; + private AnvilTextChange textChange; // used for setting custom inventory static Field mc_ContainerAnvil_repairInventory; // subcontainer with only the result diff --git a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/nbt/NBTCompoundImpl.java b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/nbt/NBTCompoundImpl.java index cca17d07..bf304905 100644 --- a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/nbt/NBTCompoundImpl.java +++ b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/nbt/NBTCompoundImpl.java @@ -7,7 +7,6 @@ import net.minecraft.server.v1_10_R1.NBTTagCompound; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; @@ -192,7 +191,7 @@ public class NBTCompoundImpl implements NBTCompound { public void deSerialize(byte[] serialized) { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(serialized); ObjectInputStream dataInput = new ObjectInputStream(inputStream)) { - compound = NBTCompressedStreamTools.a((InputStream) dataInput); + compound = NBTCompressedStreamTools.a(dataInput); } catch (Exception ex) { ex.printStackTrace(); } diff --git a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/nbt/NBTItemImpl.java b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/nbt/NBTItemImpl.java index 3312766d..f96f5f95 100644 --- a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/nbt/NBTItemImpl.java @@ -21,8 +21,4 @@ public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { return CraftItemStack.asBukkitCopy(nmsItem); } - - @Override - public void addExtras() { - } } diff --git a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/world/SItemStackImpl.java b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/world/SItemStackImpl.java index 13942c7b..627f237c 100644 --- a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/world/SItemStackImpl.java +++ b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/world/SItemStackImpl.java @@ -31,7 +31,8 @@ public class SItemStackImpl implements SItemStack { vec3d1 = vec3d1.a(-entityPlayer.pitch * 0.017453292F); vec3d1 = vec3d1.b(-entityPlayer.yaw * 0.017453292F); vec3d1 = vec3d1.add(entityPlayer.locX, entityPlayer.locY + (double) entityPlayer.getHeadHeight(), entityPlayer.locZ); - entityPlayer.world.addParticle(EnumParticle.ITEM_CRACK, vec3d1.x, vec3d1.y, vec3d1.z, vec3d.x, vec3d.y + 0.05D, vec3d.z, new int[] {Item.getId(CraftItemStack.asNMSCopy(item).getItem())}); + + entityPlayer.world.addParticle(EnumParticle.ITEM_CRACK, vec3d1.x, vec3d1.y, vec3d1.z, vec3d.x, vec3d.y + 0.05D, vec3d.z, Item.getId(CraftItemStack.asNMSCopy(item).getItem())); } } } diff --git a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/world/SSpawnerImpl.java b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/world/SSpawnerImpl.java index af1726cd..cf98d5ef 100644 --- a/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/world/SSpawnerImpl.java +++ b/NMS/NMS-v1_10_R1/src/main/java/com/songoda/core/nms/v1_10_R1/world/SSpawnerImpl.java @@ -53,6 +53,7 @@ public class SSpawnerImpl implements SSpawner { Entity entity = ChunkRegionLoader.a(compound, world, x, y, z, false); + assert entity != null; BlockPosition position = entity.getChunkCoordinates(); DifficultyDamageScaler damageScaler = world.D(position); diff --git a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/anvil/AnvilView.java b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/anvil/AnvilView.java index 711bd6fa..8a7fcc58 100644 --- a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/anvil/AnvilView.java +++ b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/anvil/AnvilView.java @@ -25,7 +25,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { private String title = "Repairing"; private int cost = -1; private boolean canUse = true; - private AnvilTextChange textChange = null; + private AnvilTextChange textChange; // used for setting custom inventory static Field mc_ContainerAnvil_repairInventory; // subcontainer with only the result diff --git a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/nbt/NBTCompoundImpl.java b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/nbt/NBTCompoundImpl.java index 78dbb5f2..bb454757 100644 --- a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/nbt/NBTCompoundImpl.java +++ b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/nbt/NBTCompoundImpl.java @@ -7,7 +7,6 @@ import net.minecraft.server.v1_11_R1.NBTTagCompound; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; @@ -193,7 +192,7 @@ public class NBTCompoundImpl implements NBTCompound { public void deSerialize(byte[] serialized) { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(serialized); ObjectInputStream dataInput = new ObjectInputStream(inputStream)) { - compound = NBTCompressedStreamTools.a((InputStream) dataInput); + compound = NBTCompressedStreamTools.a(dataInput); } catch (Exception ex) { ex.printStackTrace(); } diff --git a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/nbt/NBTItemImpl.java b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/nbt/NBTItemImpl.java index 02d82b3b..e23f8213 100644 --- a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/nbt/NBTItemImpl.java @@ -33,8 +33,4 @@ public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { public byte[] getByteArray(String tag) { return new byte[0]; } - - @Override - public void addExtras() { - } } diff --git a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/world/SItemStackImpl.java b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/world/SItemStackImpl.java index 4112b12b..3efbd1d9 100644 --- a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/world/SItemStackImpl.java +++ b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/world/SItemStackImpl.java @@ -32,7 +32,8 @@ public class SItemStackImpl implements SItemStack { vec3d1 = vec3d1.a(-entityPlayer.pitch * 0.017453292F); vec3d1 = vec3d1.b(-entityPlayer.yaw * 0.017453292F); vec3d1 = vec3d1.add(entityPlayer.locX, entityPlayer.locY + (double) entityPlayer.getHeadHeight(), entityPlayer.locZ); - entityPlayer.world.addParticle(EnumParticle.ITEM_CRACK, vec3d1.x, vec3d1.y, vec3d1.z, vec3d.x, vec3d.y + 0.05D, vec3d.z, new int[] {Item.getId(CraftItemStack.asNMSCopy(item).getItem())}); + + entityPlayer.world.addParticle(EnumParticle.ITEM_CRACK, vec3d1.x, vec3d1.y, vec3d1.z, vec3d.x, vec3d.y + 0.05D, vec3d.z, Item.getId(CraftItemStack.asNMSCopy(item).getItem())); } } } diff --git a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/world/SSpawnerImpl.java b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/world/SSpawnerImpl.java index b8fc4bf8..cbd5b03b 100644 --- a/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/world/SSpawnerImpl.java +++ b/NMS/NMS-v1_11_R1/src/main/java/com/songoda/core/nms/v1_11_R1/world/SSpawnerImpl.java @@ -55,6 +55,7 @@ public class SSpawnerImpl implements SSpawner { Entity entity = ChunkRegionLoader.a(compound, world, x, y, z, false); + assert entity != null; BlockPosition position = entity.getChunkCoordinates(); DifficultyDamageScaler damageScaler = world.D(position); diff --git a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/anvil/AnvilView.java b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/anvil/AnvilView.java index fe79bcb4..379e6e29 100644 --- a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/anvil/AnvilView.java +++ b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/anvil/AnvilView.java @@ -25,7 +25,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { private String title = "Repairing"; private int cost = -1; private boolean canUse = true; - private AnvilTextChange textChange = null; + private AnvilTextChange textChange; // used for setting custom inventory static Field mc_ContainerAnvil_repairInventory; // subcontainer with only the result diff --git a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/nbt/NBTCompoundImpl.java b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/nbt/NBTCompoundImpl.java index 20a878a0..53548522 100644 --- a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/nbt/NBTCompoundImpl.java +++ b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/nbt/NBTCompoundImpl.java @@ -7,7 +7,6 @@ import net.minecraft.server.v1_12_R1.NBTTagCompound; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; @@ -192,7 +191,7 @@ public class NBTCompoundImpl implements NBTCompound { public void deSerialize(byte[] serialized) { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(serialized); ObjectInputStream dataInput = new ObjectInputStream(inputStream)) { - compound = NBTCompressedStreamTools.a((InputStream) dataInput); + compound = NBTCompressedStreamTools.a(dataInput); } catch (Exception ex) { ex.printStackTrace(); } diff --git a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/nbt/NBTItemImpl.java b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/nbt/NBTItemImpl.java index e7c993dd..0f310067 100644 --- a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/nbt/NBTItemImpl.java @@ -21,8 +21,4 @@ public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { return CraftItemStack.asBukkitCopy(nmsItem); } - - @Override - public void addExtras() { - } } diff --git a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/world/SItemStackImpl.java b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/world/SItemStackImpl.java index 09487374..cd13d66b 100644 --- a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/world/SItemStackImpl.java +++ b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/world/SItemStackImpl.java @@ -31,7 +31,8 @@ public class SItemStackImpl implements SItemStack { vec3d1 = vec3d1.a(-entityPlayer.pitch * 0.017453292F); vec3d1 = vec3d1.b(-entityPlayer.yaw * 0.017453292F); vec3d1 = vec3d1.add(entityPlayer.locX, entityPlayer.locY + (double) entityPlayer.getHeadHeight(), entityPlayer.locZ); - entityPlayer.world.addParticle(EnumParticle.ITEM_CRACK, vec3d1.x, vec3d1.y, vec3d1.z, vec3d.x, vec3d.y + 0.05D, vec3d.z, new int[] {Item.getId(CraftItemStack.asNMSCopy(item).getItem())}); + + entityPlayer.world.addParticle(EnumParticle.ITEM_CRACK, vec3d1.x, vec3d1.y, vec3d1.z, vec3d.x, vec3d.y + 0.05D, vec3d.z, Item.getId(CraftItemStack.asNMSCopy(item).getItem())); } } } diff --git a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/world/SSpawnerImpl.java b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/world/SSpawnerImpl.java index f2daa465..22c43036 100644 --- a/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/world/SSpawnerImpl.java +++ b/NMS/NMS-v1_12_R1/src/main/java/com/songoda/core/nms/v1_12_R1/world/SSpawnerImpl.java @@ -55,6 +55,7 @@ public class SSpawnerImpl implements SSpawner { Entity entity = ChunkRegionLoader.a(compound, world, x, y, z, false); + assert entity != null; BlockPosition position = entity.getChunkCoordinates(); DifficultyDamageScaler damageScaler = world.D(position); diff --git a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/anvil/AnvilView.java b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/anvil/AnvilView.java index 67429038..1b59bd7f 100644 --- a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/anvil/AnvilView.java +++ b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/anvil/AnvilView.java @@ -25,7 +25,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { private String title = "Repairing"; private int cost = -1; private boolean canUse = true; - private AnvilTextChange textChange = null; + private AnvilTextChange textChange; // used for setting custom inventory static Field mc_ContainerAnvil_repairInventory; // subcontainer with only the result diff --git a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/nbt/NBTCompoundImpl.java b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/nbt/NBTCompoundImpl.java index 92bf5f5f..82b3c179 100644 --- a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/nbt/NBTCompoundImpl.java +++ b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/nbt/NBTCompoundImpl.java @@ -7,7 +7,6 @@ import net.minecraft.server.v1_13_R1.NBTTagCompound; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; @@ -192,7 +191,7 @@ public class NBTCompoundImpl implements NBTCompound { public void deSerialize(byte[] serialized) { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(serialized); ObjectInputStream dataInput = new ObjectInputStream(inputStream)) { - compound = NBTCompressedStreamTools.a((InputStream) dataInput); + compound = NBTCompressedStreamTools.a(dataInput); } catch (Exception ex) { ex.printStackTrace(); } diff --git a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/nbt/NBTItemImpl.java b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/nbt/NBTItemImpl.java index d9bcb839..204f0b0f 100644 --- a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/nbt/NBTItemImpl.java @@ -21,8 +21,4 @@ public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { return CraftItemStack.asBukkitCopy(nmsItem); } - - @Override - public void addExtras() { - } } diff --git a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/world/SSpawnerImpl.java b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/world/SSpawnerImpl.java index 6ebf5519..737c70ca 100644 --- a/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/world/SSpawnerImpl.java +++ b/NMS/NMS-v1_13_R1/src/main/java/com/songoda/core/nms/v1_13_R1/world/SSpawnerImpl.java @@ -55,6 +55,7 @@ public class SSpawnerImpl implements SSpawner { Entity entity = ChunkRegionLoader.a(compound, world, x, y, z, false); + assert entity != null; BlockPosition position = entity.getChunkCoordinates(); DifficultyDamageScaler damageScaler = world.getDamageScaler(position); diff --git a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/anvil/AnvilView.java b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/anvil/AnvilView.java index 6f357a06..6318bd85 100644 --- a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/anvil/AnvilView.java +++ b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/anvil/AnvilView.java @@ -25,7 +25,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { private String title = "Repairing"; private int cost = -1; private boolean canUse = true; - private AnvilTextChange textChange = null; + private AnvilTextChange textChange; // used for setting custom inventory static Field mc_ContainerAnvil_repairInventory; // subcontainer with only the result diff --git a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/nbt/NBTCompoundImpl.java b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/nbt/NBTCompoundImpl.java index 6fd969b9..b0ffede5 100644 --- a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/nbt/NBTCompoundImpl.java +++ b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/nbt/NBTCompoundImpl.java @@ -7,7 +7,6 @@ import net.minecraft.server.v1_13_R2.NBTTagCompound; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; @@ -191,7 +190,7 @@ public class NBTCompoundImpl implements NBTCompound { public void deSerialize(byte[] serialized) { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(serialized); ObjectInputStream dataInput = new ObjectInputStream(inputStream)) { - compound = NBTCompressedStreamTools.a((InputStream) dataInput); + compound = NBTCompressedStreamTools.a(dataInput); } catch (Exception ex) { ex.printStackTrace(); } diff --git a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/nbt/NBTItemImpl.java b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/nbt/NBTItemImpl.java index 5356f086..c30b69ca 100644 --- a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/nbt/NBTItemImpl.java @@ -32,8 +32,4 @@ public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { public byte[] getByteArray(String tag) { return new byte[0]; } - - @Override - public void addExtras() { - } } diff --git a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/world/SSpawnerImpl.java b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/world/SSpawnerImpl.java index 81696f56..892ab1de 100644 --- a/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/world/SSpawnerImpl.java +++ b/NMS/NMS-v1_13_R2/src/main/java/com/songoda/core/nms/v1_13_R2/world/SSpawnerImpl.java @@ -55,6 +55,7 @@ public class SSpawnerImpl implements SSpawner { Entity entity = ChunkRegionLoader.a(compound, world, x, y, z, false); + assert entity != null; BlockPosition position = entity.getChunkCoordinates(); DifficultyDamageScaler damageScaler = world.getDamageScaler(position); diff --git a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/anvil/AnvilView.java b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/anvil/AnvilView.java index 919c668b..e54bdf8b 100644 --- a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/anvil/AnvilView.java +++ b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/anvil/AnvilView.java @@ -30,7 +30,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { private String customTitle = "Repairing"; private int cost = -1; private boolean canUse = true; - private AnvilTextChange textChange = null; + private AnvilTextChange textChange; // used for setting custom inventory static Field mc_ContainerAnvil_repairInventory; // subcontainer with only the result @@ -97,9 +97,10 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { if (holder != null) { this.inventory = getBukkitView(entity, holder).getTopInventory(); - } else { - this.inventory = getBukkitView().getTopInventory(); + return; } + + this.inventory = getBukkitView().getTopInventory(); } public CraftInventoryView getBukkitView(EntityHuman player, InventoryHolder holder) { diff --git a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTCompoundImpl.java b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTCompoundImpl.java index 3ef2c3f7..fe2303a6 100644 --- a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTCompoundImpl.java +++ b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTCompoundImpl.java @@ -7,7 +7,6 @@ import net.minecraft.server.v1_14_R1.NBTTagCompound; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; @@ -192,7 +191,7 @@ public class NBTCompoundImpl implements NBTCompound { public void deSerialize(byte[] serialized) { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(serialized); ObjectInputStream dataInput = new ObjectInputStream(inputStream)) { - compound = NBTCompressedStreamTools.a((InputStream) dataInput); + compound = NBTCompressedStreamTools.a(dataInput); } catch (Exception ex) { ex.printStackTrace(); } diff --git a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTEntityImpl.java b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTEntityImpl.java index 821140c6..8a272a67 100644 --- a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTEntityImpl.java +++ b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTEntityImpl.java @@ -27,6 +27,8 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { Optional> optionalEntity = EntityTypes.a(entityType); if (optionalEntity.isPresent()) { + assert location.getWorld() != null; + Entity spawned = optionalEntity.get().spawnCreature( ((CraftWorld) location.getWorld()).getHandle(), compound, diff --git a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTItemImpl.java b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTItemImpl.java index c62059a7..0fc7a9c7 100644 --- a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/nbt/NBTItemImpl.java @@ -33,8 +33,4 @@ public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { public byte[] getByteArray(String tag) { return new byte[0]; } - - @Override - public void addExtras() { - } } diff --git a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/world/SSpawnerImpl.java b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/world/SSpawnerImpl.java index 620a715f..364211f8 100644 --- a/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/world/SSpawnerImpl.java +++ b/NMS/NMS-v1_14_R1/src/main/java/com/songoda/core/nms/v1_14_R1/world/SSpawnerImpl.java @@ -48,6 +48,7 @@ public class SSpawnerImpl implements SSpawner { short spawnRange = 4; for (int i = 0; i < 50; i++) { + @SuppressWarnings("ConstantConditions") WorldServer world = ((CraftWorld) spawnerLocation.getWorld()).getHandle(); Random random = world.getRandom(); diff --git a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/anvil/AnvilView.java b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/anvil/AnvilView.java index afbf23c4..b368c441 100644 --- a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/anvil/AnvilView.java +++ b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/anvil/AnvilView.java @@ -30,7 +30,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { private String customTitle = "Repairing"; private int cost = -1; private boolean canUse = true; - private AnvilTextChange textChange = null; + private AnvilTextChange textChange; // used for setting custom inventory static Field mc_ContainerAnvil_repairInventory; // subcontainer with only the result diff --git a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTCompoundImpl.java b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTCompoundImpl.java index 46f76740..fb7d33e1 100644 --- a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTCompoundImpl.java +++ b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTCompoundImpl.java @@ -7,7 +7,6 @@ import net.minecraft.server.v1_15_R1.NBTTagCompound; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; @@ -192,7 +191,7 @@ public class NBTCompoundImpl implements NBTCompound { public void deSerialize(byte[] serialized) { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(serialized); ObjectInputStream dataInput = new ObjectInputStream(inputStream)) { - compound = NBTCompressedStreamTools.a((InputStream) dataInput); + compound = NBTCompressedStreamTools.a(dataInput); } catch (Exception ex) { ex.printStackTrace(); } diff --git a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTEntityImpl.java b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTEntityImpl.java index ce6c1151..9b3c82a3 100644 --- a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTEntityImpl.java +++ b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTEntityImpl.java @@ -28,6 +28,8 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { Optional> optionalEntity = EntityTypes.a(entityType); if (optionalEntity.isPresent()) { + assert location.getWorld() != null; + Entity spawned = optionalEntity.get().spawnCreature( ((CraftWorld) location.getWorld()).getHandle(), compound, diff --git a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTItemImpl.java b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTItemImpl.java index 086c8bfc..ccb61abd 100644 --- a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/nbt/NBTItemImpl.java @@ -21,8 +21,4 @@ public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { return CraftItemStack.asBukkitCopy(nmsItem); } - - @Override - public void addExtras() { - } } diff --git a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/world/SSpawnerImpl.java b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/world/SSpawnerImpl.java index a347fba9..68735f16 100644 --- a/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/world/SSpawnerImpl.java +++ b/NMS/NMS-v1_15_R1/src/main/java/com/songoda/core/nms/v1_15_R1/world/SSpawnerImpl.java @@ -48,6 +48,7 @@ public class SSpawnerImpl implements SSpawner { short spawnRange = 4; for (int i = 0; i < 50; i++) { + @SuppressWarnings("ConstantConditions") WorldServer world = ((CraftWorld) spawnerLocation.getWorld()).getHandle(); Random random = world.getRandom(); diff --git a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/anvil/AnvilView.java b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/anvil/AnvilView.java index 89ce4bb2..e3e8d1ce 100644 --- a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/anvil/AnvilView.java +++ b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/anvil/AnvilView.java @@ -31,7 +31,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { private String customTitle = "Repairing"; private int cost = -1; private boolean canUse = true; - private AnvilTextChange textChange = null; + private AnvilTextChange textChange; // used for setting custom inventory static Field mc_ContainerAnvil_repairInventory; // subcontainer with only the result @@ -85,9 +85,10 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { if (holder != null) { this.inventory = getBukkitView(entity, holder).getTopInventory(); - } else { - this.inventory = getBukkitView().getTopInventory(); + return; } + + this.inventory = getBukkitView().getTopInventory(); } public CraftInventoryView getBukkitView(EntityHuman player, InventoryHolder holder) { diff --git a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTCompoundImpl.java b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTCompoundImpl.java index 56945be4..4836c25c 100644 --- a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTCompoundImpl.java +++ b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTCompoundImpl.java @@ -7,7 +7,6 @@ import net.minecraft.server.v1_16_R1.NBTTagCompound; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; @@ -192,7 +191,7 @@ public class NBTCompoundImpl implements NBTCompound { public void deSerialize(byte[] serialized) { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(serialized); ObjectInputStream dataInput = new ObjectInputStream(inputStream)) { - compound = NBTCompressedStreamTools.a((InputStream) dataInput); + compound = NBTCompressedStreamTools.a(dataInput); } catch (Exception ex) { ex.printStackTrace(); } diff --git a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTEntityImpl.java b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTEntityImpl.java index 54340361..2c29f250 100644 --- a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTEntityImpl.java +++ b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTEntityImpl.java @@ -27,6 +27,8 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { Optional> optionalEntity = EntityTypes.a(entityType); if (optionalEntity.isPresent()) { + assert location.getWorld() != null; + Entity spawned = optionalEntity.get().spawnCreature( ((CraftWorld) location.getWorld()).getHandle(), compound, diff --git a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTItemImpl.java b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTItemImpl.java index c576efa4..13a2e280 100644 --- a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/nbt/NBTItemImpl.java @@ -33,8 +33,4 @@ public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { public byte[] getByteArray(String tag) { return new byte[0]; } - - @Override - public void addExtras() { - } } diff --git a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/world/SSpawnerImpl.java b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/world/SSpawnerImpl.java index ad305fa8..19967ddf 100644 --- a/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/world/SSpawnerImpl.java +++ b/NMS/NMS-v1_16_R1/src/main/java/com/songoda/core/nms/v1_16_R1/world/SSpawnerImpl.java @@ -48,6 +48,7 @@ public class SSpawnerImpl implements SSpawner { short spawnRange = 4; for (int i = 0; i < 50; i++) { + @SuppressWarnings("ConstantConditions") WorldServer world = ((CraftWorld) spawnerLocation.getWorld()).getHandle(); Random random = world.getRandom(); diff --git a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/anvil/AnvilView.java b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/anvil/AnvilView.java index 87cd83a5..c0d0c00c 100644 --- a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/anvil/AnvilView.java +++ b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/anvil/AnvilView.java @@ -31,7 +31,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { private String customTitle = "Repairing"; private int cost = -1; private boolean canUse = true; - private AnvilTextChange textChange = null; + private AnvilTextChange textChange; // used for setting custom inventory static Field mc_ContainerAnvil_repairInventory; // subcontainer with only the result diff --git a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/nbt/NBTEntityImpl.java b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/nbt/NBTEntityImpl.java index 0761dea5..504b3ec5 100644 --- a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/nbt/NBTEntityImpl.java +++ b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/nbt/NBTEntityImpl.java @@ -27,6 +27,8 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { Optional> optionalEntity = EntityTypes.a(entityType); if (optionalEntity.isPresent()) { + assert location.getWorld() != null; + Entity spawned = optionalEntity.get().spawnCreature( ((CraftWorld) location.getWorld()).getHandle(), compound, diff --git a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/nbt/NBTItemImpl.java b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/nbt/NBTItemImpl.java index d350ea94..24473fb0 100644 --- a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/nbt/NBTItemImpl.java @@ -21,8 +21,4 @@ public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { return CraftItemStack.asBukkitCopy(nmsItem); } - - @Override - public void addExtras() { - } } diff --git a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/world/SSpawnerImpl.java b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/world/SSpawnerImpl.java index 7c769ec2..798d93ac 100644 --- a/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/world/SSpawnerImpl.java +++ b/NMS/NMS-v1_16_R2/src/main/java/com/songoda/core/nms/v1_16_R2/world/SSpawnerImpl.java @@ -48,6 +48,7 @@ public class SSpawnerImpl implements SSpawner { short spawnRange = 4; for (int i = 0; i < 50; i++) { + @SuppressWarnings("ConstantConditions") WorldServer world = ((CraftWorld) spawnerLocation.getWorld()).getHandle(); Random random = world.getRandom(); diff --git a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/anvil/AnvilView.java b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/anvil/AnvilView.java index 1d1cf233..8dfb6489 100644 --- a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/anvil/AnvilView.java +++ b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/anvil/AnvilView.java @@ -31,7 +31,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { private String customTitle = "Repairing"; private int cost = -1; private boolean canUse = true; - private AnvilTextChange textChange = null; + private AnvilTextChange textChange; // used for setting custom inventory static Field mc_ContainerAnvil_repairInventory; // subcontainer with only the result diff --git a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/nbt/NBTEntityImpl.java b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/nbt/NBTEntityImpl.java index 8d605471..de9202e4 100644 --- a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/nbt/NBTEntityImpl.java +++ b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/nbt/NBTEntityImpl.java @@ -27,6 +27,8 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { Optional> optionalEntity = EntityTypes.a(entityType); if (optionalEntity.isPresent()) { + assert location.getWorld() != null; + Entity spawned = optionalEntity.get().spawnCreature( ((CraftWorld) location.getWorld()).getHandle(), compound, diff --git a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/nbt/NBTItemImpl.java b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/nbt/NBTItemImpl.java index 7f3474e5..a1fe602d 100644 --- a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/nbt/NBTItemImpl.java @@ -21,8 +21,4 @@ public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { return CraftItemStack.asBukkitCopy(nmsItem); } - - @Override - public void addExtras() { - } } diff --git a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/world/SSpawnerImpl.java b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/world/SSpawnerImpl.java index e7fb6262..c84aa443 100644 --- a/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/world/SSpawnerImpl.java +++ b/NMS/NMS-v1_16_R3/src/main/java/com/songoda/core/nms/v1_16_R3/world/SSpawnerImpl.java @@ -48,6 +48,7 @@ public class SSpawnerImpl implements SSpawner { short spawnRange = 4; for (int i = 0; i < 50; i++) { + @SuppressWarnings("ConstantConditions") WorldServer world = ((CraftWorld) spawnerLocation.getWorld()).getHandle(); Random random = world.getRandom(); diff --git a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/anvil/AnvilView.java b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/anvil/AnvilView.java index dc84cd93..ee5b2059 100644 --- a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/anvil/AnvilView.java +++ b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/anvil/AnvilView.java @@ -29,7 +29,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { private String customTitle = "Repairing"; private int cost = -1; private boolean canUse = true; - private AnvilTextChange textChange = null; + private AnvilTextChange textChange; // used for setting custom inventory static Field mc_ContainerAnvil_repairInventory; // subcontainer with only the result diff --git a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/nbt/NBTEntityImpl.java b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/nbt/NBTEntityImpl.java index 05a22b79..1ec46246 100644 --- a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/nbt/NBTEntityImpl.java +++ b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/nbt/NBTEntityImpl.java @@ -27,6 +27,8 @@ public class NBTEntityImpl extends NBTCompoundImpl implements NBTEntity { Optional> optionalEntity = EntityTypes.a(entityType); if (optionalEntity.isPresent()) { + assert location.getWorld() != null; + Entity spawned = optionalEntity.get().spawnCreature( ((CraftWorld) location.getWorld()).getHandle(), compound, diff --git a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/nbt/NBTItemImpl.java b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/nbt/NBTItemImpl.java index 31cd554a..896a8cf3 100644 --- a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/nbt/NBTItemImpl.java @@ -21,8 +21,4 @@ public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { return CraftItemStack.asBukkitCopy(nmsItem); } - - @Override - public void addExtras() { - } } diff --git a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/SSpawnerImpl.java b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/SSpawnerImpl.java index 3d1b5795..da78339f 100644 --- a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/SSpawnerImpl.java +++ b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/SSpawnerImpl.java @@ -48,6 +48,7 @@ public class SSpawnerImpl implements SSpawner { short spawnRange = 4; for (int i = 0; i < 50; i++) { + assert spawnerLocation.getWorld() != null; WorldServer world = ((CraftWorld) spawnerLocation.getWorld()).getHandle(); Random random = world.getRandom(); @@ -56,7 +57,7 @@ public class SSpawnerImpl implements SSpawner { double z = spawnerLocation.getZ() + (random.nextDouble() - random.nextDouble()) * (double) spawnRange + 0.5D; Optional optionalEntity = EntityTypes.a(compound, world); - if (!optionalEntity.isPresent()) continue; + if (optionalEntity.isEmpty()) continue; Entity entity = optionalEntity.get(); entity.setPosition(x, y, z); diff --git a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/SWorldImpl.java b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/SWorldImpl.java index 673be2ed..b7c5bd51 100644 --- a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/SWorldImpl.java +++ b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/SWorldImpl.java @@ -34,7 +34,7 @@ public class SWorldImpl implements SWorld { @Override public List getLivingEntities() { - List list = new ArrayList(); + List list = new ArrayList<>(); try { WorldServer worldServer = ((CraftWorld) world).getHandle(); diff --git a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/spawner/BBaseSpawnerImpl.java b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/spawner/BBaseSpawnerImpl.java index 809972b2..85f0dff8 100644 --- a/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/spawner/BBaseSpawnerImpl.java +++ b/NMS/NMS-v1_17_R1/src/main/java/com/songoda/core/nms/v1_17_R1/world/spawner/BBaseSpawnerImpl.java @@ -160,7 +160,7 @@ public class BBaseSpawnerImpl implements BBaseSpawner { } this.spawner.e.b(spawnerFieldP) - .ifPresent((mobspawnerdata) -> this.spawner.setSpawnData(world, bPos, mobspawnerdata)); + .ifPresent((mobSpawnerData) -> this.spawner.setSpawnData(world, bPos, mobSpawnerData)); this.spawner.a(world, getBlockPosition(), 1); } diff --git a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/anvil/AnvilView.java b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/anvil/AnvilView.java index de14f8fa..58ffb635 100644 --- a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/anvil/AnvilView.java +++ b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/anvil/AnvilView.java @@ -24,7 +24,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { private String title = "Repairing"; private int cost = -1; private boolean canUse = true; - private AnvilTextChange textChange = null; + private AnvilTextChange textChange; // used for setting custom inventory static Field mc_ContainerAnvil_repairInventory; // subcontainer with only the result diff --git a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/nbt/NBTCompoundImpl.java b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/nbt/NBTCompoundImpl.java index 21fdcf63..02f8c70a 100644 --- a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/nbt/NBTCompoundImpl.java +++ b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/nbt/NBTCompoundImpl.java @@ -7,7 +7,6 @@ import net.minecraft.server.v1_8_R1.NBTTagCompound; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; @@ -194,7 +193,7 @@ public class NBTCompoundImpl implements NBTCompound { public void deSerialize(byte[] serialized) { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(serialized); ObjectInputStream dataInput = new ObjectInputStream(inputStream)) { - compound = NBTCompressedStreamTools.a((InputStream) dataInput); + compound = NBTCompressedStreamTools.a(dataInput); } catch (Exception ex) { ex.printStackTrace(); } diff --git a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/nbt/NBTItemImpl.java b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/nbt/NBTItemImpl.java index 6cba3c6d..cddbfc99 100644 --- a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/nbt/NBTItemImpl.java @@ -21,8 +21,4 @@ public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { return CraftItemStack.asBukkitCopy(nmsItem); } - - @Override - public void addExtras() { - } } diff --git a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/world/SItemStackImpl.java b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/world/SItemStackImpl.java index 0e460077..88526560 100644 --- a/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/world/SItemStackImpl.java +++ b/NMS/NMS-v1_8_R1/src/main/java/com/songoda/core/nms/v1_8_R1/world/SItemStackImpl.java @@ -32,7 +32,8 @@ public class SItemStackImpl implements SItemStack { vec3d1 = vec3d1.a(-entityPlayer.pitch * 0.017453292F); vec3d1 = vec3d1.b(-entityPlayer.yaw * 0.017453292F); vec3d1 = vec3d1.add(entityPlayer.locX, entityPlayer.locY + (double) entityPlayer.getHeadHeight(), entityPlayer.locZ); - entityPlayer.world.addParticle(EnumParticle.ITEM_CRACK, vec3d1.a, vec3d1.b, vec3d1.c, vec3d.a, vec3d.b + 0.05D, vec3d.c, new int[] {Item.getId(CraftItemStack.asNMSCopy(item).getItem())}); + + entityPlayer.world.addParticle(EnumParticle.ITEM_CRACK, vec3d1.a, vec3d1.b, vec3d1.c, vec3d.a, vec3d.b + 0.05D, vec3d.c, Item.getId(CraftItemStack.asNMSCopy(item).getItem())); } } } diff --git a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/anvil/AnvilView.java b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/anvil/AnvilView.java index 9b769bf5..d9235fb0 100644 --- a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/anvil/AnvilView.java +++ b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/anvil/AnvilView.java @@ -24,7 +24,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { private String title = "Repairing"; private int cost = -1; private boolean canUse = true; - private AnvilTextChange textChange = null; + private AnvilTextChange textChange; // used for setting custom inventory static Field mc_ContainerAnvil_repairInventory; // subcontainer with only the result diff --git a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/nbt/NBTCompoundImpl.java b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/nbt/NBTCompoundImpl.java index 97966c83..c1fb2fc7 100644 --- a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/nbt/NBTCompoundImpl.java +++ b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/nbt/NBTCompoundImpl.java @@ -7,7 +7,6 @@ import net.minecraft.server.v1_8_R2.NBTTagCompound; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; @@ -194,7 +193,7 @@ public class NBTCompoundImpl implements NBTCompound { public void deSerialize(byte[] serialized) { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(serialized); ObjectInputStream dataInput = new ObjectInputStream(inputStream)) { - compound = NBTCompressedStreamTools.a((InputStream) dataInput); + compound = NBTCompressedStreamTools.a(dataInput); } catch (Exception ex) { ex.printStackTrace(); } diff --git a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/nbt/NBTItemImpl.java b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/nbt/NBTItemImpl.java index d07730c2..53d2f7f1 100644 --- a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/nbt/NBTItemImpl.java @@ -21,8 +21,4 @@ public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { return CraftItemStack.asBukkitCopy(nmsItem); } - - @Override - public void addExtras() { - } } diff --git a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/world/SItemStackImpl.java b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/world/SItemStackImpl.java index 7a324712..784f1c60 100644 --- a/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/world/SItemStackImpl.java +++ b/NMS/NMS-v1_8_R2/src/main/java/com/songoda/core/nms/v1_8_R2/world/SItemStackImpl.java @@ -32,7 +32,8 @@ public class SItemStackImpl implements SItemStack { vec3d1 = vec3d1.a(-entityPlayer.pitch * 0.017453292F); vec3d1 = vec3d1.b(-entityPlayer.yaw * 0.017453292F); vec3d1 = vec3d1.add(entityPlayer.locX, entityPlayer.locY + (double) entityPlayer.getHeadHeight(), entityPlayer.locZ); - entityPlayer.world.addParticle(EnumParticle.ITEM_CRACK, vec3d1.a, vec3d1.b, vec3d1.c, vec3d.a, vec3d.b + 0.05D, vec3d.c, new int[] {Item.getId(CraftItemStack.asNMSCopy(item).getItem())}); + + entityPlayer.world.addParticle(EnumParticle.ITEM_CRACK, vec3d1.a, vec3d1.b, vec3d1.c, vec3d.a, vec3d.b + 0.05D, vec3d.c, Item.getId(CraftItemStack.asNMSCopy(item).getItem())); } } } diff --git a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/anvil/AnvilView.java b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/anvil/AnvilView.java index 8c065247..46614995 100644 --- a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/anvil/AnvilView.java +++ b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/anvil/AnvilView.java @@ -24,7 +24,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { private String title = "Repairing"; private int cost = -1; private boolean canUse = true; - private AnvilTextChange textChange = null; + private AnvilTextChange textChange; // used for setting custom inventory static Field mc_ContainerAnvil_repairInventory; // subcontainer with only the result diff --git a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/nbt/NBTCompoundImpl.java b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/nbt/NBTCompoundImpl.java index a39aca33..a73b86a2 100644 --- a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/nbt/NBTCompoundImpl.java +++ b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/nbt/NBTCompoundImpl.java @@ -7,7 +7,6 @@ import net.minecraft.server.v1_8_R3.NBTTagCompound; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; @@ -193,7 +192,7 @@ public class NBTCompoundImpl implements NBTCompound { public void deSerialize(byte[] serialized) { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(serialized); ObjectInputStream dataInput = new ObjectInputStream(inputStream)) { - compound = NBTCompressedStreamTools.a((InputStream) dataInput); + compound = NBTCompressedStreamTools.a(dataInput); } catch (Exception ex) { ex.printStackTrace(); } diff --git a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/nbt/NBTItemImpl.java b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/nbt/NBTItemImpl.java index cd7ec969..55128777 100644 --- a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/nbt/NBTItemImpl.java @@ -20,8 +20,4 @@ public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { return CraftItemStack.asBukkitCopy(nmsItem); } } - - @Override - public void addExtras() { - } } diff --git a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/world/SItemStackImpl.java b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/world/SItemStackImpl.java index 42948e8d..011932bd 100644 --- a/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/world/SItemStackImpl.java +++ b/NMS/NMS-v1_8_R3/src/main/java/com/songoda/core/nms/v1_8_R3/world/SItemStackImpl.java @@ -32,7 +32,8 @@ public class SItemStackImpl implements SItemStack { vec3d1 = vec3d1.a(-entityPlayer.pitch * 0.017453292F); vec3d1 = vec3d1.b(-entityPlayer.yaw * 0.017453292F); vec3d1 = vec3d1.add(entityPlayer.locX, entityPlayer.locY + (double) entityPlayer.getHeadHeight(), entityPlayer.locZ); - entityPlayer.world.addParticle(EnumParticle.ITEM_CRACK, vec3d1.a, vec3d1.b, vec3d1.c, vec3d.a, vec3d.b + 0.05D, vec3d.c, new int[] {Item.getId(CraftItemStack.asNMSCopy(item).getItem())}); + + entityPlayer.world.addParticle(EnumParticle.ITEM_CRACK, vec3d1.a, vec3d1.b, vec3d1.c, vec3d.a, vec3d.b + 0.05D, vec3d.c, Item.getId(CraftItemStack.asNMSCopy(item).getItem())); } } } diff --git a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/anvil/AnvilView.java b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/anvil/AnvilView.java index f2f575c0..f3408f13 100644 --- a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/anvil/AnvilView.java +++ b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/anvil/AnvilView.java @@ -25,7 +25,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { private String title = "Repairing"; private int cost = -1; private boolean canUse = true; - private AnvilTextChange textChange = null; + private AnvilTextChange textChange; // used for setting custom inventory static Field mc_ContainerAnvil_repairInventory; // subcontainer with only the result diff --git a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/nbt/NBTCompoundImpl.java b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/nbt/NBTCompoundImpl.java index 659dc034..2473fcd3 100644 --- a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/nbt/NBTCompoundImpl.java +++ b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/nbt/NBTCompoundImpl.java @@ -7,7 +7,6 @@ import net.minecraft.server.v1_9_R1.NBTTagCompound; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; @@ -191,7 +190,7 @@ public class NBTCompoundImpl implements NBTCompound { public void deSerialize(byte[] serialized) { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(serialized); ObjectInputStream dataInput = new ObjectInputStream(inputStream)) { - compound = NBTCompressedStreamTools.a((InputStream) dataInput); + compound = NBTCompressedStreamTools.a(dataInput); } catch (Exception ex) { ex.printStackTrace(); } diff --git a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/nbt/NBTItemImpl.java b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/nbt/NBTItemImpl.java index 181f423a..de3234d9 100644 --- a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/nbt/NBTItemImpl.java @@ -21,8 +21,4 @@ public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { return CraftItemStack.asBukkitCopy(nmsItem); } - - @Override - public void addExtras() { - } } diff --git a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/world/SItemStackImpl.java b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/world/SItemStackImpl.java index 7fe84c62..dbc95314 100644 --- a/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/world/SItemStackImpl.java +++ b/NMS/NMS-v1_9_R1/src/main/java/com/songoda/core/nms/v1_9_R1/world/SItemStackImpl.java @@ -32,7 +32,8 @@ public class SItemStackImpl implements SItemStack { vec3d1 = vec3d1.a(-entityPlayer.pitch * 0.017453292F); vec3d1 = vec3d1.b(-entityPlayer.yaw * 0.017453292F); vec3d1 = vec3d1.add(entityPlayer.locX, entityPlayer.locY + (double) entityPlayer.getHeadHeight(), entityPlayer.locZ); - entityPlayer.world.addParticle(EnumParticle.ITEM_CRACK, vec3d1.x, vec3d1.y, vec3d1.z, vec3d.x, vec3d.y + 0.05D, vec3d.z, new int[] {Item.getId(CraftItemStack.asNMSCopy(item).getItem())}); + + entityPlayer.world.addParticle(EnumParticle.ITEM_CRACK, vec3d1.x, vec3d1.y, vec3d1.z, vec3d.x, vec3d.y + 0.05D, vec3d.z, Item.getId(CraftItemStack.asNMSCopy(item).getItem())); } } } diff --git a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/anvil/AnvilView.java b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/anvil/AnvilView.java index 3602392a..bd7fe7e7 100644 --- a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/anvil/AnvilView.java +++ b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/anvil/AnvilView.java @@ -25,7 +25,7 @@ public class AnvilView extends ContainerAnvil implements CustomAnvil { private String title = "Repairing"; private int cost = -1; private boolean canUse = true; - private AnvilTextChange textChange = null; + private AnvilTextChange textChange; // used for setting custom inventory static Field mc_ContainerAnvil_repairInventory; // subcontainer with only the result diff --git a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/nbt/NBTCompoundImpl.java b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/nbt/NBTCompoundImpl.java index 784cdc64..d3e095c3 100644 --- a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/nbt/NBTCompoundImpl.java +++ b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/nbt/NBTCompoundImpl.java @@ -7,7 +7,6 @@ import net.minecraft.server.v1_9_R2.NBTTagCompound; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; @@ -192,7 +191,7 @@ public class NBTCompoundImpl implements NBTCompound { public void deSerialize(byte[] serialized) { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(serialized); ObjectInputStream dataInput = new ObjectInputStream(inputStream)) { - compound = NBTCompressedStreamTools.a((InputStream) dataInput); + compound = NBTCompressedStreamTools.a(dataInput); } catch (Exception ex) { ex.printStackTrace(); } diff --git a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/nbt/NBTItemImpl.java b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/nbt/NBTItemImpl.java index d4309ca7..e08460f5 100644 --- a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/nbt/NBTItemImpl.java +++ b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/nbt/NBTItemImpl.java @@ -21,8 +21,4 @@ public class NBTItemImpl extends NBTCompoundImpl implements NBTItem { return CraftItemStack.asBukkitCopy(nmsItem); } - - @Override - public void addExtras() { - } } diff --git a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/world/SItemStackImpl.java b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/world/SItemStackImpl.java index 859238b6..a4b2b83d 100644 --- a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/world/SItemStackImpl.java +++ b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/world/SItemStackImpl.java @@ -32,7 +32,8 @@ public class SItemStackImpl implements SItemStack { vec3d1 = vec3d1.a(-entityPlayer.pitch * 0.017453292F); vec3d1 = vec3d1.b(-entityPlayer.yaw * 0.017453292F); vec3d1 = vec3d1.add(entityPlayer.locX, entityPlayer.locY + (double) entityPlayer.getHeadHeight(), entityPlayer.locZ); - entityPlayer.world.addParticle(EnumParticle.ITEM_CRACK, vec3d1.x, vec3d1.y, vec3d1.z, vec3d.x, vec3d.y + 0.05D, vec3d.z, new int[] {Item.getId(CraftItemStack.asNMSCopy(item).getItem())}); + + entityPlayer.world.addParticle(EnumParticle.ITEM_CRACK, vec3d1.x, vec3d1.y, vec3d1.z, vec3d.x, vec3d.y + 0.05D, vec3d.z, Item.getId(CraftItemStack.asNMSCopy(item).getItem())); } } } diff --git a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/world/SSpawnerImpl.java b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/world/SSpawnerImpl.java index c4c78fc3..f55d3184 100644 --- a/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/world/SSpawnerImpl.java +++ b/NMS/NMS-v1_9_R2/src/main/java/com/songoda/core/nms/v1_9_R2/world/SSpawnerImpl.java @@ -53,6 +53,7 @@ public class SSpawnerImpl implements SSpawner { Entity entity = ChunkRegionLoader.a(compound, world, x, y, z, false); + assert entity != null; BlockPosition position = entity.getChunkCoordinates(); DifficultyDamageScaler damageScaler = world.D(position); From 0712730ca61a77a1422dad44f9383ecea2bbca73 Mon Sep 17 00:00:00 2001 From: Christian Koop Date: Sat, 30 Oct 2021 14:27:51 +0200 Subject: [PATCH 07/18] Updates dependency `org.jetbrains:annotations` from 13.0 to 22.0.0 --- pom.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 9f655c3b..47b32991 100644 --- a/pom.xml +++ b/pom.xml @@ -113,7 +113,8 @@ org.jetbrains annotations - 13.0 + 22.0.0 + provided From afb53ba3a012c06a087a58b87a0995877ca4f54f Mon Sep 17 00:00:00 2001 From: Christian Koop Date: Sat, 30 Oct 2021 14:53:09 +0200 Subject: [PATCH 08/18] Add dependencies for unit tests --- .gitignore | 1 + pom.xml | 31 +++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/.gitignore b/.gitignore index f8c66c55..751da154 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,7 @@ /NMS/*/target/ dependency-reduced-pom.xml +/**/logs/*.log ## # Misc. diff --git a/pom.xml b/pom.xml index 47b32991..ce9bca02 100644 --- a/pom.xml +++ b/pom.xml @@ -67,6 +67,16 @@ ${java.release} + + + maven-surefire-plugin + 2.22.2 + + + + maven-failsafe-plugin + 3.0.0-M5 + @@ -116,5 +126,26 @@ 22.0.0 provided + + + org.junit.jupiter + junit-jupiter + 5.8.1 + test + + + + + + + + + + + com.github.seeseemelk + MockBukkit-v1.17 + 1.10.3 + test + From b4d1f4fc60a3660022c10f335ddb7a1900f72cdd Mon Sep 17 00:00:00 2001 From: Christian Koop Date: Sat, 30 Oct 2021 14:53:05 +0200 Subject: [PATCH 09/18] Implement first unit tests --- .../com/songoda/core/utils/LocationUtils.java | 7 +- .../songoda/core/input/ChatPromptTest.java | 127 ++++++++++ .../com/songoda/core/math/MathUtilsTest.java | 60 +++++ .../songoda/core/utils/LocationUtilsTest.java | 29 +++ .../songoda/core/utils/NumberUtilsTest.java | 64 +++++ .../songoda/core/utils/PlayerUtilsTest.java | 230 ++++++++++++++++++ .../songoda/core/utils/RotationUtilsTest.java | 40 +++ .../com/songoda/core/utils/TextUtilsTest.java | 129 ++++++++++ .../com/songoda/core/utils/TimeUtilsTest.java | 48 ++++ 9 files changed, 733 insertions(+), 1 deletion(-) create mode 100644 Core/src/test/java/com/songoda/core/input/ChatPromptTest.java create mode 100644 Core/src/test/java/com/songoda/core/math/MathUtilsTest.java create mode 100644 Core/src/test/java/com/songoda/core/utils/LocationUtilsTest.java create mode 100644 Core/src/test/java/com/songoda/core/utils/NumberUtilsTest.java create mode 100644 Core/src/test/java/com/songoda/core/utils/PlayerUtilsTest.java create mode 100644 Core/src/test/java/com/songoda/core/utils/RotationUtilsTest.java create mode 100644 Core/src/test/java/com/songoda/core/utils/TextUtilsTest.java create mode 100644 Core/src/test/java/com/songoda/core/utils/TimeUtilsTest.java diff --git a/Core/src/main/java/com/songoda/core/utils/LocationUtils.java b/Core/src/main/java/com/songoda/core/utils/LocationUtils.java index 23e3ad3f..1e2d8ad7 100644 --- a/Core/src/main/java/com/songoda/core/utils/LocationUtils.java +++ b/Core/src/main/java/com/songoda/core/utils/LocationUtils.java @@ -3,8 +3,13 @@ package com.songoda.core.utils; import org.bukkit.Location; public class LocationUtils { + /** + * Compares the block coordinates of two locations ignoring the world + */ public static boolean isLocationMatching(Location location1, Location location2) { - return location1.getBlockX() == location2.getBlockX() && location1.getBlockY() == location2.getBlockY() && location1.getBlockZ() == location2.getBlockZ(); + return location1.getBlockX() == location2.getBlockX() && + location1.getBlockY() == location2.getBlockY() && + location1.getBlockZ() == location2.getBlockZ(); } public static boolean isInArea(Location l, Location pos1, Location pos2) { diff --git a/Core/src/test/java/com/songoda/core/input/ChatPromptTest.java b/Core/src/test/java/com/songoda/core/input/ChatPromptTest.java new file mode 100644 index 00000000..06d8e22f --- /dev/null +++ b/Core/src/test/java/com/songoda/core/input/ChatPromptTest.java @@ -0,0 +1,127 @@ +package com.songoda.core.input; + +import be.seeseemelk.mockbukkit.MockBukkit; +import be.seeseemelk.mockbukkit.MockPlugin; +import be.seeseemelk.mockbukkit.ServerMock; +import be.seeseemelk.mockbukkit.entity.PlayerMock; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Disabled("BukkitMock seems to cause some troubles here, skipping for now") +class ChatPromptTest { + private final String inputMsg = "&eInput-Message"; + + private ServerMock server; + private MockPlugin plugin; + private PlayerMock player; + + @BeforeEach + void setUp() { + this.server = MockBukkit.mock(); + this.plugin = MockBukkit.createMockPlugin(); + this.player = this.server.addPlayer(); + } + + @AfterEach + void tearDown() { + MockBukkit.unmock(); + } + + @Test + void showPrompt() throws InterruptedException { + List chatInputs = new ArrayList<>(1); + + ChatPrompt.showPrompt(this.plugin, this.player, event -> { + assertEquals(this.player, event.getPlayer()); + + chatInputs.add(event.getMessage()); + }); + + this.player.chat(this.inputMsg); + Thread.sleep(1000); + // this.server.getScheduler().waitAsyncTasksFinished() // does not wait for async events + + String playerReceivedMsg = this.player.nextMessage(); + + assertNotNull(playerReceivedMsg); + assertTrue(playerReceivedMsg.endsWith(this.inputMsg)); + + assertEquals(1, chatInputs.size()); + assertEquals(this.inputMsg, chatInputs.get(0)); + } + + /* FIXME: Something is still running in the background and prevents the test from finishing */ + @Disabled("Scheduling mock seems bugged, skipping for now") + @Test + void showPromptWithTimeout() { + AtomicBoolean calledOnClose = new AtomicBoolean(false); + + ChatPrompt.showPrompt(this.plugin, this.player, event -> { + }) + .setOnClose(() -> calledOnClose.set(true)) + .setTimeOut(this.player, 40); + + this.server.getScheduler().performTicks(40); + + String playerReceivedMsg = this.player.nextMessage(); + + assertNotNull(playerReceivedMsg); + assertTrue(playerReceivedMsg.contains("timed out")); + + this.server.getScheduler().performOneTick(); + assertTrue(calledOnClose.get()); + } + + @Test + void cancelPrompt() { + AtomicBoolean calledOnCancel = new AtomicBoolean(false); + AtomicBoolean calledHandler = new AtomicBoolean(false); + + ChatPrompt prompt = ChatPrompt.showPrompt(plugin, player, (event) -> calledHandler.set(true)); + prompt.setOnCancel(() -> calledOnCancel.set(true)); + + this.server.dispatchCommand(player, "cancel"); + // this.player.chat("/cancel"); +// Thread.sleep(1000); + // this.server.getScheduler().waitAsyncTasksFinished() // does not wait for async events + + System.out.println(this.player.nextMessage()); + +// assertTrue(player.nextMessage().endsWith("/cancel")); + + assertTrue(calledOnCancel.get()); + assertFalse(calledHandler.get()); + } + + @Test + void isRegistered() { + assertFalse(ChatPrompt.isRegistered(this.player)); + + ChatPrompt.showPrompt(this.plugin, this.player, (event) -> { + }); + + assertTrue(ChatPrompt.isRegistered(this.player)); + } + + @Test + void unregister() { + assertFalse(ChatPrompt.unregister(this.player)); + + ChatPrompt.showPrompt(this.plugin, this.player, (event) -> { + }); + + assertTrue(ChatPrompt.unregister(this.player)); + assertFalse(ChatPrompt.unregister(this.player)); + } +} diff --git a/Core/src/test/java/com/songoda/core/math/MathUtilsTest.java b/Core/src/test/java/com/songoda/core/math/MathUtilsTest.java new file mode 100644 index 00000000..fea0b3d6 --- /dev/null +++ b/Core/src/test/java/com/songoda/core/math/MathUtilsTest.java @@ -0,0 +1,60 @@ +package com.songoda.core.math; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrowsExactly; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class MathUtilsTest { + private final String warningMessage = "MathTest"; + private final String warningMessageExpectedStart = "[" + warningMessage + "] "; + + @Test + void eval() { + assertEquals(10.5 + 4, MathUtils.eval("10.5 + 4")); + assertEquals(10.5 - 5, MathUtils.eval("10.5 - 5")); + assertEquals(10 * 4, MathUtils.eval("10 * 4")); + assertEquals(10.5 / .5, MathUtils.eval("10.5 / .5")); + + assertEquals(20 - +4, MathUtils.eval("20 - +4")); + assertEquals(Math.pow(10, 2), MathUtils.eval("10^2")); + assertEquals(Math.pow(-10, 2), MathUtils.eval("(-10)^2")); + assertEquals(-Math.pow(10, 2), MathUtils.eval("-10^2")); + + assertEquals(Math.sqrt(49), MathUtils.eval("sqrt(49)")); + assertEquals(Math.sin(Math.toRadians(90)), MathUtils.eval("sin(90)")); + assertEquals(Math.cos(Math.toRadians(90)), MathUtils.eval("cos(90)")); + assertEquals(Math.tan(Math.toRadians(89650)), MathUtils.eval("tan(89650)")); + + assertEquals(Integer.MAX_VALUE + (long) Integer.MAX_VALUE, + MathUtils.eval(Integer.MAX_VALUE + "+" + Integer.MAX_VALUE)); + } + + @Test + void evalWithCommaAsDecimalSeparator() { + Exception ex = assertThrowsExactly(RuntimeException.class, () -> MathUtils.eval("1,0", warningMessage)); + + assertTrue(ex.getMessage().startsWith(warningMessageExpectedStart), + () -> "'" + ex.getMessage() + "' does not start with '" + warningMessageExpectedStart + "'"); + assertTrue(ex.getMessage().contains("Unexpected: ")); + } + + @Test + void evalWithUnsupportedSyntax() { + Exception ex = assertThrowsExactly(RuntimeException.class, () -> MathUtils.eval("!2", warningMessage)); + + assertTrue(ex.getMessage().startsWith(warningMessageExpectedStart), + () -> "'" + ex.getMessage() + "' does not start with '" + warningMessageExpectedStart + "'"); + assertTrue(ex.getMessage().contains("Unexpected: ")); + } + + @Test + void evalWithUnsupportedFunction() { + Exception ex = assertThrowsExactly(RuntimeException.class, () -> MathUtils.eval("acos(90)", warningMessage)); + + assertTrue(ex.getMessage().startsWith(warningMessageExpectedStart), + () -> "'" + ex.getMessage() + "' does not start with '" + warningMessageExpectedStart + "'"); + assertTrue(ex.getMessage().contains("Unknown function: ")); + } +} diff --git a/Core/src/test/java/com/songoda/core/utils/LocationUtilsTest.java b/Core/src/test/java/com/songoda/core/utils/LocationUtilsTest.java new file mode 100644 index 00000000..9fc10215 --- /dev/null +++ b/Core/src/test/java/com/songoda/core/utils/LocationUtilsTest.java @@ -0,0 +1,29 @@ +package com.songoda.core.utils; + +import be.seeseemelk.mockbukkit.WorldMock; +import org.bukkit.Location; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class LocationUtilsTest { + @Test + void isLocationMatching() { + assertTrue(LocationUtils.isLocationMatching( + new Location(null, 10, 20, 30), + new Location(new WorldMock(), 10.25, 20.5, 30.75) + )); + + assertFalse(LocationUtils.isLocationMatching( + new Location(null, 10, 20, 30), + new Location(new WorldMock(), -10.25, 20.5, 30.75) + )); + } + + @Disabled("Test not yet implemented") + @Test + void isInArea() { + } +} diff --git a/Core/src/test/java/com/songoda/core/utils/NumberUtilsTest.java b/Core/src/test/java/com/songoda/core/utils/NumberUtilsTest.java new file mode 100644 index 00000000..10fe462c --- /dev/null +++ b/Core/src/test/java/com/songoda/core/utils/NumberUtilsTest.java @@ -0,0 +1,64 @@ +package com.songoda.core.utils; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class NumberUtilsTest { + @Test + void formatEconomy() { + assertEquals("$1,999.99", NumberUtils.formatEconomy('$', 1999.99)); + } + + @Test + void formatNumber() { + assertEquals("1,999.99", NumberUtils.formatNumber(1999.99)); + assertEquals("1,999,999.99", NumberUtils.formatNumber(1999999.99)); + } + + @Test + void formatWithSuffix() { + assertEquals("100", NumberUtils.formatWithSuffix(100)); + + assertEquals("150,5M", NumberUtils.formatWithSuffix(150_500_000)); + assertEquals("150,5M", NumberUtils.formatWithSuffix(150_500_999)); + assertEquals("151,0M", NumberUtils.formatWithSuffix(150_999_999)); + + assertEquals("150,5G", NumberUtils.formatWithSuffix(150_500_000_000L)); + assertEquals("150,5T", NumberUtils.formatWithSuffix(150_500_000_000_000L)); + assertEquals("150,5P", NumberUtils.formatWithSuffix(150_500_000_000_000_000L)); + assertEquals("1,5E", NumberUtils.formatWithSuffix(150_500_000_000_000_000_0L)); + + assertEquals("9,2E", NumberUtils.formatWithSuffix(Long.MAX_VALUE)); + + assertEquals(String.valueOf(Long.MIN_VALUE), NumberUtils.formatWithSuffix(Long.MIN_VALUE)); + } + + @Test + void isInt() { + assertFalse(NumberUtils.isInt(null)); + assertFalse(NumberUtils.isInt("")); + + assertTrue(NumberUtils.isInt("100")); + assertTrue(NumberUtils.isInt("-100")); + assertTrue(NumberUtils.isInt("+100")); + + assertFalse(NumberUtils.isInt("100.0")); + assertFalse(NumberUtils.isInt("Int")); + } + + @Test + void isNumeric() { + assertFalse(NumberUtils.isNumeric(null)); + assertFalse(NumberUtils.isNumeric("")); + + assertTrue(NumberUtils.isNumeric("100")); + assertTrue(NumberUtils.isNumeric("100.0")); + assertTrue(NumberUtils.isNumeric("-100.0")); + assertTrue(NumberUtils.isNumeric("+100.0")); + + assertFalse(NumberUtils.isNumeric("Numeric")); + } +} diff --git a/Core/src/test/java/com/songoda/core/utils/PlayerUtilsTest.java b/Core/src/test/java/com/songoda/core/utils/PlayerUtilsTest.java new file mode 100644 index 00000000..f1d112b5 --- /dev/null +++ b/Core/src/test/java/com/songoda/core/utils/PlayerUtilsTest.java @@ -0,0 +1,230 @@ +package com.songoda.core.utils; + +import be.seeseemelk.mockbukkit.MockBukkit; +import be.seeseemelk.mockbukkit.ServerMock; +import be.seeseemelk.mockbukkit.entity.PlayerMock; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class PlayerUtilsTest { + private ServerMock server; + + @BeforeEach + void setUp() { + this.server = MockBukkit.mock(); + } + + @AfterEach + void tearDown() { + MockBukkit.unmock(); + this.server = null; + } + + @Test + void sendMessages() { + String[] messages = new String[] {"First message", "Second message"}; + + PlayerMock player = this.server.addPlayer(); + + PlayerUtils.sendMessages(player, messages); + PlayerUtils.sendMessages(player, Arrays.asList(messages)); + + for (int i = 0; i < 2; ++i) { + assertEquals(messages[0], player.nextMessage()); + assertEquals(messages[1], player.nextMessage()); + } + + assertNull(player.nextMessage()); + } + + @Disabled("Player#hidePlayer can currently not be mocked") + @Test + void getVisiblePlayerNames() { + PlayerMock player = this.server.addPlayer("BasePlayer"); + PlayerMock visiblePlayer = this.server.addPlayer("VisiblePlayer"); + PlayerMock hiddenPlayer = this.server.addPlayer("HiddenPlayer"); + + player.hidePlayer(MockBukkit.createMockPlugin(), hiddenPlayer); + + List result = PlayerUtils.getVisiblePlayerNames(player, null); + assertTrue(result.contains(visiblePlayer.getName())); + assertFalse(result.contains(hiddenPlayer.getName())); + assertFalse(result.contains(player.getName())); + + assertEquals(0, PlayerUtils.getVisiblePlayerNames(player, "_").size()); + } + + @Disabled("Player#hidePlayer can currently not be mocked") + @Test + void getVisiblePlayerDisplayNames() { + PlayerMock player = this.server.addPlayer("BasePlayer"); + PlayerMock visiblePlayer = this.server.addPlayer("VisiblePlayer"); + PlayerMock hiddenPlayer = this.server.addPlayer("HiddenPlayer"); + + player.setDisplayName("Base"); + visiblePlayer.setDisplayName("Visible"); + hiddenPlayer.setDisplayName("Hidden"); + + player.hidePlayer(MockBukkit.createMockPlugin(), hiddenPlayer); + + List result = PlayerUtils.getVisiblePlayerDisplayNames(player, null); + assertTrue(result.contains(visiblePlayer.getDisplayName())); + assertFalse(result.contains(hiddenPlayer.getDisplayName())); + assertFalse(result.contains(player.getDisplayName())); + + assertEquals(0, PlayerUtils.getVisiblePlayerDisplayNames(player, "_").size()); + } + + @Disabled("Player#hidePlayer can currently not be mocked") + @Test + void getVisiblePlayers() { + PlayerMock player = this.server.addPlayer("BasePlayer"); + PlayerMock visiblePlayer = this.server.addPlayer("VisiblePlayer"); + PlayerMock hiddenPlayer = this.server.addPlayer("HiddenPlayer"); + + player.hidePlayer(MockBukkit.createMockPlugin(), hiddenPlayer); + + List result = PlayerUtils.getVisiblePlayers(player, null); + assertTrue(result.contains(visiblePlayer)); + assertFalse(result.contains(hiddenPlayer)); + assertFalse(result.contains(player)); + + assertEquals(0, PlayerUtils.getVisiblePlayers(player, "_").size()); + } + + @Test + void getAllPlayers() { + PlayerMock basePlayer = this.server.addPlayer("BasePlayer"); + this.server.addPlayer("Player_1"); + this.server.addPlayer("Player_2"); + this.server.addPlayer("Player3"); + + List result = PlayerUtils.getAllPlayers(basePlayer, ""); + assertEquals(3, result.size()); + assertFalse(result.contains(basePlayer.getName())); + + assertTrue(PlayerUtils.getAllPlayers(basePlayer, "_").isEmpty()); + assertEquals(0, PlayerUtils.getAllPlayers(basePlayer, "Player_").size()); + } + + @Test + void getAllPlayersDisplay() { + PlayerMock basePlayer = this.server.addPlayer("BasePlayer"); + this.server.addPlayer("Player_1"); + this.server.addPlayer("Player_2"); + this.server.addPlayer("Player3"); + + List result = PlayerUtils.getAllPlayersDisplay(basePlayer, ""); + assertEquals(3, result.size()); + assertFalse(result.contains(basePlayer.getDisplayName())); + + assertEquals(2, PlayerUtils.getAllPlayersDisplay(basePlayer, "Player_").size()); + assertEquals(0, PlayerUtils.getAllPlayersDisplay(basePlayer, "_").size()); + } + + @Test + void findPlayer() { + Player p3 = this.server.addPlayer("Player"); + Player p1 = this.server.addPlayer("Player_1"); + Player p2 = this.server.addPlayer("_Player_2"); + + p1.setDisplayName("p1"); + p2.setDisplayName("p2"); + p3.setDisplayName("p3"); + + assertEquals(p1, PlayerUtils.findPlayer("Player_")); + assertEquals(p2, PlayerUtils.findPlayer("_Play")); + assertEquals(p3, PlayerUtils.findPlayer("Player")); + + assertEquals(p3, PlayerUtils.findPlayer("p")); + assertEquals(p1, PlayerUtils.findPlayer("p1")); + assertEquals(p2, PlayerUtils.findPlayer("p2")); + assertEquals(p3, PlayerUtils.findPlayer("p3")); + } + + @Test + void getRandomPlayer() { + assertNull(PlayerUtils.getRandomPlayer()); + + for (int i = 0; i < 10; ++i) { + this.server.addPlayer(String.valueOf(i)); + } + + Set returnedPlayers = new HashSet<>(); + for (int i = 0; i < 50; ++i) { + if (returnedPlayers.size() >= 5) { + break; + } + + returnedPlayers.add(PlayerUtils.getRandomPlayer()); + } + + assertTrue(returnedPlayers.size() >= 5); + } + + @Test + void giveItem() { + Player player = this.server.addPlayer(); + + PlayerUtils.giveItem(player, new ItemStack(Material.STONE)); + assertTrue(player.getInventory().contains(Material.STONE, 1)); + + PlayerUtils.giveItem(player, new ItemStack(Material.GRASS_BLOCK), new ItemStack(Material.GRASS_BLOCK)); + assertTrue(player.getInventory().contains(Material.GRASS_BLOCK, 2)); + + PlayerUtils.giveItem(player, Arrays.asList(new ItemStack(Material.WHEAT_SEEDS), new ItemStack(Material.WHEAT_SEEDS))); + assertTrue(player.getInventory().contains(Material.WHEAT_SEEDS, 2)); + } + + @Test + void giveItemOnFullInventory() { + PlayerMock player = this.server.addPlayer(); + + fillInventory(player); + + int entityCount = this.server.getEntities().size(); + PlayerUtils.giveItem(player, new ItemStack(Material.STONE)); + assertEquals(entityCount + 1, this.server.getEntities().size()); + + entityCount = this.server.getEntities().size(); + PlayerUtils.giveItem(player, new ItemStack(Material.GRASS_BLOCK), new ItemStack(Material.GRASS_BLOCK)); + assertEquals(entityCount + 2, this.server.getEntities().size()); + + entityCount = this.server.getEntities().size(); + PlayerUtils.giveItem(player, Arrays.asList(new ItemStack(Material.WHEAT_SEEDS), new ItemStack(Material.WHEAT_SEEDS), new ItemStack(Material.WHEAT_SEEDS))); + assertEquals(entityCount + 3, this.server.getEntities().size()); + } + + @Disabled("Test is incomplete") + @Test + void getNumberFromPermission() { + Player player = this.server.addPlayer(); + + assertEquals(-1, PlayerUtils.getNumberFromPermission(player, "example.plugin.feature", -1)); + } + + private void fillInventory(Player player) { + ItemStack[] contents = new ItemStack[player.getInventory().getContents().length]; + + for (int i = 0; i < contents.length; ++i) { + contents[i] = new ItemStack(Material.BARRIER); + } + + player.getInventory().setContents(contents); + } +} diff --git a/Core/src/test/java/com/songoda/core/utils/RotationUtilsTest.java b/Core/src/test/java/com/songoda/core/utils/RotationUtilsTest.java new file mode 100644 index 00000000..bb7596f8 --- /dev/null +++ b/Core/src/test/java/com/songoda/core/utils/RotationUtilsTest.java @@ -0,0 +1,40 @@ +package com.songoda.core.utils; + +import org.bukkit.block.BlockFace; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class RotationUtilsTest { + @Test + void faceToYaw() { + assertEquals(180, RotationUtils.faceToYaw(BlockFace.NORTH)); + assertEquals(-90, RotationUtils.faceToYaw(BlockFace.EAST)); + assertEquals(0, RotationUtils.faceToYaw(BlockFace.SOUTH)); + assertEquals(90, RotationUtils.faceToYaw(BlockFace.WEST)); + + assertEquals(0, RotationUtils.faceToYaw(BlockFace.UP)); + assertEquals(0, RotationUtils.faceToYaw(BlockFace.DOWN)); + } + + @Test + void yawToFace() { + assertEquals(BlockFace.NORTH, RotationUtils.yawToFace(180 - 25)); + assertEquals(BlockFace.NORTH, RotationUtils.yawToFace(180)); + assertEquals(BlockFace.NORTH, RotationUtils.yawToFace(180 + 25)); + + assertEquals(BlockFace.EAST, RotationUtils.yawToFace(-90 - 25)); + assertEquals(BlockFace.EAST, RotationUtils.yawToFace(-90)); + assertEquals(BlockFace.EAST, RotationUtils.yawToFace(-90 + 25)); + + assertEquals(BlockFace.SOUTH, RotationUtils.yawToFace(-25)); + assertEquals(BlockFace.SOUTH, RotationUtils.yawToFace(0)); + assertEquals(BlockFace.SOUTH, RotationUtils.yawToFace(25)); + + assertEquals(BlockFace.WEST, RotationUtils.yawToFace(90 - 25)); + assertEquals(BlockFace.WEST, RotationUtils.yawToFace(90)); + assertEquals(BlockFace.WEST, RotationUtils.yawToFace(90 + 25)); + + assertEquals(BlockFace.SOUTH, RotationUtils.yawToFace(Float.MAX_VALUE)); + } +} diff --git a/Core/src/test/java/com/songoda/core/utils/TextUtilsTest.java b/Core/src/test/java/com/songoda/core/utils/TextUtilsTest.java new file mode 100644 index 00000000..505a094a --- /dev/null +++ b/Core/src/test/java/com/songoda/core/utils/TextUtilsTest.java @@ -0,0 +1,129 @@ +package com.songoda.core.utils; + +import org.bukkit.ChatColor; +import org.junit.jupiter.api.Test; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.Collections; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class TextUtilsTest { + @Test + void formatText() { + final String testString = "hello&6 world &r:)"; + final String testStringResult = "hello" + ChatColor.COLOR_CHAR + "6 world " + ChatColor.COLOR_CHAR + "r:)"; + + assertEquals("", TextUtils.formatText((String) null)); + assertEquals("", TextUtils.formatText("")); + + assertEquals(testStringResult, TextUtils.formatText(testString)); + + assertEquals(Arrays.asList(testStringResult.split(" ")), TextUtils.formatText(testString.split(" "))); + assertEquals(Arrays.asList(testStringResult.split(" ")), TextUtils.formatText(Arrays.asList(testString.split(" ")))); + } + + @Test + void formatTextCapitalize() { + assertEquals("Hello§6§l world §r:)", TextUtils.formatText("hello&6&l world &r:)", true)); +// assertEquals("§2Hello§6§l world §r:)", TextUtils.formatText("&2hello&6&l world &r:)", true)); // FIXME: https://github.com/songoda/SongodaCore/issues/26 + } + + @Test + void wrap() { + assertEquals(Arrays.asList("Lorem ipsum dolor sit amet,", " consectetuer adipiscing elit.", + " Aenean commodo ligula eget", " dolor. Aenean massa. Cum", + " sociis natoque penatibus", " et magnis dis parturient", + " montes, nascetur ridiculus", " mus."), + TextUtils.wrap("Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor." + + " Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.")); + + assertEquals(Collections.singletonList("§6Hello world!"), TextUtils.wrap("6", "Hello world!")); + } + + @Test + void convertToInvisibleLoreString() { + assertEquals("", TextUtils.convertToInvisibleLoreString(null)); + assertEquals("", TextUtils.convertToInvisibleLoreString("")); + + assertEquals("§;§§§;§6§;§H§;§e§;§l§;§l§;§o§;§ §;§w§;§o§;§r§;§l§;§d", TextUtils.convertToInvisibleLoreString("§6Hello world")); + assertEquals("§;§&§;§6§;§H§;§e§;§l§;§l§;§o§;§ §;§w§;§o§;§r§;§l§;§d", TextUtils.convertToInvisibleLoreString("&6Hello world")); + } + + @Test + void convertToInvisibleString() { + assertEquals("", TextUtils.convertToInvisibleString(null)); + assertEquals("", TextUtils.convertToInvisibleString("")); + + assertEquals("§§§6§H§e§l§l§o§ §w§o§r§l§d", TextUtils.convertToInvisibleString("§6Hello world")); + assertEquals("§&§6§H§e§l§l§o§;§w§o§r§l§d", TextUtils.convertToInvisibleString("&6Hello;world")); + } + + @Test + void convertFromInvisibleString() { + assertEquals("", TextUtils.convertFromInvisibleString(null)); + assertEquals("", TextUtils.convertFromInvisibleString("")); + + assertEquals("§;§§§;§6§;§H§;§e§;§l§;§l§;§o§;§ §;§w§;§o§;§r§;§l§;§d", TextUtils.convertToInvisibleLoreString("§6Hello world")); + assertEquals("6Helloworld", TextUtils.convertFromInvisibleString("§§§6§H§e§l§l§o§;§w§o§r§l§d")); + assertEquals("&6Hello world", TextUtils.convertFromInvisibleString("§&§6§H§e§l§l§o§ §w§o§r§l§d")); + } + + @Test + void detectCharset() throws IOException { + byte[] asciiString = "Hello world!\n".getBytes(StandardCharsets.US_ASCII); + byte[] utf8String = "\uD83D\uDE43 Hello world!\n".getBytes(StandardCharsets.UTF_8); + byte[] loremIpsum = ("Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.\n" + + "\n" + + "Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu.\n" + + "\n" + + "In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus.\n" + + "\n" + + "Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum.\n" + + "\n" + + "Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum.\n" + + "\n" + + "Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc,").getBytes(StandardCharsets.UTF_8); + byte[] utf16LeBom = new byte[] {(byte) 0xFF, (byte) 0xFE, 'a', 'b', 'c'}; + byte[] utf16BeBom = new byte[] {(byte) 0xFE, (byte) 0xFF, 'a', 'b', 'c'}; + byte[] utf8Bom = new byte[] {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF, 'a', 'b', 'c'}; + + assertEquals(StandardCharsets.UTF_8, TextUtils.detectCharset(asciiString, asciiString.length, null)); + assertEquals(StandardCharsets.UTF_8, TextUtils.detectCharset(utf8String, utf8String.length, null)); + + assertEquals(StandardCharsets.UTF_16LE, TextUtils.detectCharset(utf16LeBom, utf16LeBom.length, null)); + assertEquals(StandardCharsets.UTF_16BE, TextUtils.detectCharset(utf16BeBom, utf16BeBom.length, null)); + assertEquals(StandardCharsets.UTF_8, TextUtils.detectCharset(utf8Bom, utf8Bom.length, null)); + + Path tmpFilePath = Files.createTempFile(null, null); + File tmpFile = tmpFilePath.toFile(); + tmpFile.deleteOnExit(); + + try (OutputStream writer = new FileOutputStream(tmpFile)) { + for (int i = 0; i < 5; ++i) { + writer.write(loremIpsum); + } + + writer.flush(); + } + + assertEquals(StandardCharsets.UTF_8, TextUtils.detectCharset(tmpFile, null)); + Files.deleteIfExists(tmpFilePath); + + assertNull(TextUtils.detectCharset(tmpFile, null)); + + try (BufferedInputStream tmpIn = new BufferedInputStream(new ByteArrayInputStream(loremIpsum))) { + assertEquals(StandardCharsets.UTF_8, TextUtils.detectCharset(tmpIn, null)); + } + } +} diff --git a/Core/src/test/java/com/songoda/core/utils/TimeUtilsTest.java b/Core/src/test/java/com/songoda/core/utils/TimeUtilsTest.java new file mode 100644 index 00000000..447f9d35 --- /dev/null +++ b/Core/src/test/java/com/songoda/core/utils/TimeUtilsTest.java @@ -0,0 +1,48 @@ +package com.songoda.core.utils; + +import org.junit.jupiter.api.Test; + +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class TimeUtilsTest { + @Test + void makeReadable() { + assertEquals("", TimeUtils.makeReadable(null)); + + assertEquals("20m", TimeUtils.makeReadable(TimeUnit.MINUTES.toMillis(20))); + assertEquals("20m 10s", TimeUtils.makeReadable( + TimeUnit.MINUTES.toMillis(20) + TimeUnit.SECONDS.toMillis(10))); + + assertEquals("10d 2h 32m 12s", TimeUtils.makeReadable( + TimeUnit.DAYS.toMillis(10) + + TimeUnit.HOURS.toMillis(2) + + TimeUnit.MINUTES.toMillis(32) + + TimeUnit.SECONDS.toMillis(12) + + 100 + )); + } + + @Test + void parseTime() { + assertEquals(TimeUnit.MINUTES.toMillis(20), TimeUtils.parseTime("20m")); + assertEquals(TimeUnit.MINUTES.toMillis(20) + TimeUnit.SECONDS.toMillis(10), TimeUtils.parseTime("20m 10s")); + + assertEquals(TimeUnit.DAYS.toMillis(10) + + TimeUnit.HOURS.toMillis(2) + + TimeUnit.MINUTES.toMillis(32) + + TimeUnit.SECONDS.toMillis(12), + TimeUtils.parseTime("10d 2h 32m 12s")); + + assertEquals(TimeUnit.MINUTES.toMillis(100) + + TimeUnit.SECONDS.toMillis(100), + TimeUtils.parseTime("100m 100s")); + assertEquals(TimeUnit.MINUTES.toMillis(100) + + TimeUnit.SECONDS.toMillis(100), + TimeUtils.parseTime("100m100s")); + + assertEquals(0, TimeUtils.parseTime("10?")); + assertEquals(0, TimeUtils.parseTime("10xX")); + } +} From ba7054c1e7c8862a9beee85955d95c79481519f4 Mon Sep 17 00:00:00 2001 From: Christian Koop Date: Sat, 30 Oct 2021 15:12:44 +0200 Subject: [PATCH 10/18] Fix failing test cases The disabled test cases have been written without looking at the implementation - But it looks like the implementation is faulty and needs a patch. We'll take a look at a later time and decide about backwards compatibility etc. --- Core/src/test/java/com/songoda/core/utils/NumberUtilsTest.java | 2 ++ Core/src/test/java/com/songoda/core/utils/PlayerUtilsTest.java | 2 ++ 2 files changed, 4 insertions(+) diff --git a/Core/src/test/java/com/songoda/core/utils/NumberUtilsTest.java b/Core/src/test/java/com/songoda/core/utils/NumberUtilsTest.java index 10fe462c..3e921234 100644 --- a/Core/src/test/java/com/songoda/core/utils/NumberUtilsTest.java +++ b/Core/src/test/java/com/songoda/core/utils/NumberUtilsTest.java @@ -1,5 +1,6 @@ package com.songoda.core.utils; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -18,6 +19,7 @@ class NumberUtilsTest { assertEquals("1,999,999.99", NumberUtils.formatNumber(1999999.99)); } + @Disabled("Tested method's output relies on the executing system (Locale)") @Test void formatWithSuffix() { assertEquals("100", NumberUtils.formatWithSuffix(100)); diff --git a/Core/src/test/java/com/songoda/core/utils/PlayerUtilsTest.java b/Core/src/test/java/com/songoda/core/utils/PlayerUtilsTest.java index f1d112b5..d7bcb1c2 100644 --- a/Core/src/test/java/com/songoda/core/utils/PlayerUtilsTest.java +++ b/Core/src/test/java/com/songoda/core/utils/PlayerUtilsTest.java @@ -122,6 +122,7 @@ class PlayerUtilsTest { assertEquals(0, PlayerUtils.getAllPlayers(basePlayer, "Player_").size()); } + @Disabled("Disabled for now as the implementations seems to be faulty") @Test void getAllPlayersDisplay() { PlayerMock basePlayer = this.server.addPlayer("BasePlayer"); @@ -137,6 +138,7 @@ class PlayerUtilsTest { assertEquals(0, PlayerUtils.getAllPlayersDisplay(basePlayer, "_").size()); } + @Disabled("Disabled for now as the implementations seems to be faulty") @Test void findPlayer() { Player p3 = this.server.addPlayer("Player"); From 783400d9a9acc23267a36ea89793c0f51f811889 Mon Sep 17 00:00:00 2001 From: Christian Koop Date: Sat, 30 Oct 2021 15:22:23 +0200 Subject: [PATCH 11/18] Adds SonarCloud (static analysis tool) --- .github/workflows/sonarcloud.yml | 42 ++++++++++++++++++++++++++++++++ pom.xml | 3 +++ 2 files changed, 45 insertions(+) create mode 100644 .github/workflows/sonarcloud.yml diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml new file mode 100644 index 00000000..1da660ba --- /dev/null +++ b/.github/workflows/sonarcloud.yml @@ -0,0 +1,42 @@ +name: SonarCloud + +on: + push: + branches: [ master, development ] + pull_request: + types: [ opened, synchronize, reopened ] + +jobs: + build: + name: Build + runs-on: ubuntu-latest + steps: + # Setup Java + - uses: actions/setup-java@v2 + with: + java-version: 16 + distribution: adopt + + # Checkout project files + - uses: actions/checkout@v2 + with: + fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis + + # Caches + - name: 'Cache: Maven' + uses: actions/cache@v2 + with: + path: ~/.m2/repository + key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} + restore-keys: ${{ runner.os }}-maven- + - name: 'Cache: SonarCloud' + uses: actions/cache@v2 + with: + path: ~/.sonar/cache + key: ${{ runner.os }}-sonar + + - name: Analyze project + run: mvn -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar -Dsonar.projectKey=songoda_SongodaCore + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} diff --git a/pom.xml b/pom.xml index ce9bca02..462af58f 100644 --- a/pom.xml +++ b/pom.xml @@ -17,6 +17,9 @@ 8 UTF-8 + + songoda + https://sonarcloud.io From 779d5a27e5279bc91e3054b5e1db909716e0cf82 Mon Sep 17 00:00:00 2001 From: Christian Koop Date: Sat, 30 Oct 2021 16:17:03 +0200 Subject: [PATCH 12/18] Uses *JaCoCo* to generate coverage reports This can additionally be used by SonarCloud for its coverage report/visualization --- pom.xml | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/pom.xml b/pom.xml index 462af58f..a9db602f 100644 --- a/pom.xml +++ b/pom.xml @@ -20,6 +20,8 @@ songoda https://sonarcloud.io + target/surefire-reports/*.xml + target/site/jacoco/jacoco.xml @@ -71,6 +73,7 @@ + maven-surefire-plugin 2.22.2 @@ -80,6 +83,28 @@ maven-failsafe-plugin 3.0.0-M5 + + + org.jacoco + jacoco-maven-plugin + 0.8.8-SNAPSHOT + + + + default-prepare-agent + + prepare-agent + + + + + default-report + + report + + + + @@ -88,6 +113,11 @@ apache.snapshots https://repository.apache.org/snapshots/ + + + sonatype.snapshots + https://oss.sonatype.org/content/repositories/snapshots + From e379ae601d5a681325f914a16671893ba4a78d37 Mon Sep 17 00:00:00 2001 From: Christian Koop Date: Sat, 30 Oct 2021 23:45:22 +0200 Subject: [PATCH 13/18] Fixed typo --- Core/src/main/java/com/songoda/core/SongodaPlugin.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Core/src/main/java/com/songoda/core/SongodaPlugin.java b/Core/src/main/java/com/songoda/core/SongodaPlugin.java index e703f9c6..384fc9fe 100644 --- a/Core/src/main/java/com/songoda/core/SongodaPlugin.java +++ b/Core/src/main/java/com/songoda/core/SongodaPlugin.java @@ -144,7 +144,7 @@ public abstract class SongodaPlugin extends JavaPlugin { return; } - console.sendMessage(" "); // blank line to speparate chatter + console.sendMessage(" "); // blank line to separate chatter console.sendMessage(ChatColor.GREEN + "============================="); console.sendMessage(String.format("%s%s %s by %sSongoda <3!", ChatColor.GRAY, getDescription().getName(), getDescription().getVersion(), ChatColor.DARK_PURPLE)); @@ -154,7 +154,7 @@ public abstract class SongodaPlugin extends JavaPlugin { onPluginDisable(); console.sendMessage(ChatColor.GREEN + "============================="); - console.sendMessage(" "); // blank line to speparate chatter + console.sendMessage(" "); // blank line to separate chatter } public ConsoleCommandSender getConsole() { From 3aaed3bcdec39858e9e55868f473d1680e1196a2 Mon Sep 17 00:00:00 2001 From: Exortions <75327059+Exortions@users.noreply.github.com> Date: Mon, 1 Nov 2021 11:23:42 -0700 Subject: [PATCH 14/18] Remove duplicate code This commit removes the duplicate error message run when the plugin crashes and turns it into one method 'crash'. This method takes in a throwable, which will be printed once the error message is logged. --- .../java/com/songoda/core/SongodaPlugin.java | 24 ++++++++++--------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/Core/src/main/java/com/songoda/core/SongodaPlugin.java b/Core/src/main/java/com/songoda/core/SongodaPlugin.java index de953492..cbd93046 100644 --- a/Core/src/main/java/com/songoda/core/SongodaPlugin.java +++ b/Core/src/main/java/com/songoda/core/SongodaPlugin.java @@ -73,12 +73,7 @@ public abstract class SongodaPlugin extends JavaPlugin { try { onPluginLoad(); } catch (Throwable t) { - Bukkit.getLogger().log(Level.SEVERE, - "Unexpected error while loading " + getDescription().getName() - + " v" + getDescription().getVersion() - + " c" + SongodaCore.getCoreLibraryVersion() - + ": Disabling plugin!", t); - emergencyStop = true; + crash(t); } } @@ -110,11 +105,7 @@ public abstract class SongodaPlugin extends JavaPlugin { // Start Metrics Metrics.start(this); } catch (Throwable t) { - Bukkit.getLogger().log(Level.SEVERE, - "Unexpected error while loading " + getDescription().getName() - + " v" + getDescription().getVersion() - + " c" + SongodaCore.getCoreLibraryVersion() - + ": Disabling plugin!", t); + crash(t); emergencyStop(); console.sendMessage(ChatColor.RED + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); console.sendMessage(" "); @@ -213,4 +204,15 @@ public abstract class SongodaPlugin extends JavaPlugin { } } } + + /** + Invoke this method if a severe error occurs and the plugin needs to shut down. + + @param t Any exceptions that are thrown when crashed should be put here, and will print once the error message logs. + */ + public void crash(Throwable... t) { + Bukkit.getLogger().log(Level.SEVERE, String.format("Unexpected error while loading %s v%s c%s: Disabling plugin!", getDescription().getName(), getDescription().getVersion(), SongodaCore.getCoreLibraryVersion()), t); + emergencyStop(); + } + } From 7c6817c470ff7c985abbb9206ae809952625efcd Mon Sep 17 00:00:00 2001 From: Christian Koop Date: Mon, 1 Nov 2021 20:29:16 +0100 Subject: [PATCH 15/18] Minor cleanup of #27 * Code style * Method name and access modifier * JavaDoc --- .../java/com/songoda/core/SongodaPlugin.java | 43 +++++++++++-------- 1 file changed, 24 insertions(+), 19 deletions(-) diff --git a/Core/src/main/java/com/songoda/core/SongodaPlugin.java b/Core/src/main/java/com/songoda/core/SongodaPlugin.java index d7c54570..7f163c39 100644 --- a/Core/src/main/java/com/songoda/core/SongodaPlugin.java +++ b/Core/src/main/java/com/songoda/core/SongodaPlugin.java @@ -70,8 +70,8 @@ public abstract class SongodaPlugin extends JavaPlugin { public final void onLoad() { try { onPluginLoad(); - } catch (Throwable t) { - crash(t); + } catch (Throwable th) { + criticalErrorOnPluginStartup(th); } } @@ -107,9 +107,8 @@ public abstract class SongodaPlugin extends JavaPlugin { // Start Metrics Metrics.start(this); - } catch (Throwable t) { - crash(t); - emergencyStop(); + } catch (Throwable th) { + criticalErrorOnPluginStartup(th); console.sendMessage(ChatColor.RED + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); console.sendMessage(" "); @@ -121,12 +120,6 @@ public abstract class SongodaPlugin extends JavaPlugin { console.sendMessage(" "); // blank line to separate chatter } - protected void emergencyStop() { - emergencyStop = true; - - Bukkit.getPluginManager().disablePlugin(this); - } - @Override public final void onDisable() { if (emergencyStop) { @@ -213,15 +206,27 @@ public abstract class SongodaPlugin extends JavaPlugin { } } } - + + protected void emergencyStop() { + emergencyStop = true; + + Bukkit.getPluginManager().disablePlugin(this); + } + /** - Invoke this method if a severe error occurs and the plugin needs to shut down. - - @param t Any exceptions that are thrown when crashed should be put here, and will print once the error message logs. - */ - public void crash(Throwable... t) { - Bukkit.getLogger().log(Level.SEVERE, String.format("Unexpected error while loading %s v%s c%s: Disabling plugin!", getDescription().getName(), getDescription().getVersion(), SongodaCore.getCoreLibraryVersion()), t); + * Logs one or multiple errors that occurred during plugin startup and calls {@link #emergencyStop()} afterwards + * + * @param th The error(s) that occurred + */ + protected void criticalErrorOnPluginStartup(Throwable... th) { + Bukkit.getLogger().log(Level.SEVERE, + String.format( + "Unexpected error while loading %s v%s c%s: Disabling plugin!", + getDescription().getName(), + getDescription().getVersion(), + SongodaCore.getCoreLibraryVersion() + ), th); + emergencyStop(); } - } From bfe329c73b3db6ad2c3c8ab1aa1222a17dbe50a4 Mon Sep 17 00:00:00 2001 From: Christian Koop Date: Mon, 1 Nov 2021 22:24:46 +0100 Subject: [PATCH 16/18] Adds `CraftMagicNumbers` to the class mappings --- .../java/com/songoda/core/compatibility/ClassMapping.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Compatibility/src/main/java/com/songoda/core/compatibility/ClassMapping.java b/Compatibility/src/main/java/com/songoda/core/compatibility/ClassMapping.java index 44451307..16ff59aa 100644 --- a/Compatibility/src/main/java/com/songoda/core/compatibility/ClassMapping.java +++ b/Compatibility/src/main/java/com/songoda/core/compatibility/ClassMapping.java @@ -42,6 +42,7 @@ public enum ClassMapping { CRAFT_CHUNK("CraftChunk"), CRAFT_ENTITY("entity", "CraftEntity"), CRAFT_ITEM_STACK("inventory", "CraftItemStack"), + CRAFT_MAGIC_NUMBERS("util", "CraftMagicNumbers"), CRAFT_PLAYER("entity", "CraftPlayer"), CRAFT_WORLD("CraftWorld"); @@ -62,8 +63,9 @@ public enum ClassMapping { } public Class getClazz(String sub) { + String name = sub == null ? className : className + "$" + sub; + try { - String name = sub == null ? className : className + "$" + sub; if (className.startsWith("Craft")) { return Class.forName("org.bukkit.craftbukkit." + ServerVersion.getServerVersionString() + (packageName == null ? "" : "." + packageName) + "." + name); From 6453c7b6f6219173e3c77b218c0ec90a1aaa65d1 Mon Sep 17 00:00:00 2001 From: Christian Koop Date: Mon, 1 Nov 2021 22:27:12 +0100 Subject: [PATCH 17/18] Recode `BlockUtils#updateAdjacentComparators` to work in older versions The old implementation relied on methods that were only available in newer versions - This should be more future proof --- .../com/songoda/core/utils/BlockUtils.java | 81 ++++++++++++------- 1 file changed, 53 insertions(+), 28 deletions(-) diff --git a/Core/src/main/java/com/songoda/core/utils/BlockUtils.java b/Core/src/main/java/com/songoda/core/utils/BlockUtils.java index a767e397..3f02d7d4 100644 --- a/Core/src/main/java/com/songoda/core/utils/BlockUtils.java +++ b/Core/src/main/java/com/songoda/core/utils/BlockUtils.java @@ -10,6 +10,7 @@ import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; +import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.EnumSet; @@ -326,53 +327,77 @@ public class BlockUtils { return null; } - private static Class clazzCraftWorld, clazzCraftBlock, clazzBlockPosition; - private static Method getHandle, updateAdjacentComparators, craftBlock_getNMS, nmsBlockData_getBlock; + /* Only to be used by #updateAdjacentComparators */ + private static Method chunkToNmsChunk, nmsChunkGetWorld, craftBlockGetPosition, craftBlockBlockDataGetter, blockDataGetBlock, craftMagicNumbersGetBlockByMaterial, nmsWorldUpdateAdjacentComparators; + /* Only to be used by #updateAdjacentComparators */ + private static Constructor blockPositionConstructor; /** * Manually trigger the updateAdjacentComparators method for containers * - * @param location location of the container + * @param loc The Location of the container */ - public static void updateAdjacentComparators(Location location) { - if (location == null || location.getWorld() == null) { + public static void updateAdjacentComparators(Location loc) { + if (loc == null || loc.getWorld() == null) { return; } + Block craftBlock = loc.getBlock(); + try { - // Cache reflection. - if (clazzCraftWorld == null) { - clazzCraftWorld = ClassMapping.CRAFT_WORLD.getClazz(); - clazzCraftBlock = ClassMapping.CRAFT_BLOCK.getClazz(); - clazzBlockPosition = ClassMapping.BLOCK_POSITION.getClazz(); - Class clazzWorld = ClassMapping.WORLD.getClazz(); - Class clazzBlock = ClassMapping.BLOCK.getClazz(); + if (chunkToNmsChunk == null) { + chunkToNmsChunk = loc.getChunk().getClass().getMethod("getHandle"); + nmsChunkGetWorld = chunkToNmsChunk.getReturnType().getMethod("getWorld"); - getHandle = clazzCraftWorld.getMethod("getHandle"); - updateAdjacentComparators = clazzWorld.getMethod("updateAdjacentComparators", clazzBlockPosition, clazzBlock); + Class blockPositionClass; + try { + craftBlockGetPosition = craftBlock.getClass().getMethod("getPosition"); - craftBlock_getNMS = clazzCraftBlock.getDeclaredMethod("getNMS"); - Class clazzBlockData = ClassMapping.BLOCK_BASE.getClazz("BlockData"); - nmsBlockData_getBlock = clazzBlockData.getDeclaredMethod("getBlock"); + blockPositionClass = craftBlockGetPosition.getReturnType(); + } catch (NoSuchMethodException ignore) { + blockPositionClass = ClassMapping.BLOCK_POSITION.getClazz(); + + blockPositionConstructor = blockPositionClass.getConstructor(double.class, double.class, double.class); + } + + nmsWorldUpdateAdjacentComparators = nmsChunkGetWorld.getReturnType().getMethod("updateAdjacentComparators", blockPositionClass, ClassMapping.BLOCK.getClazz()); + + try { + craftBlockBlockDataGetter = craftBlock.getClass().getMethod("getNMS"); + blockDataGetBlock = craftBlockBlockDataGetter.getReturnType().getMethod("getBlock"); + } catch (NoSuchMethodException ignore) { + craftMagicNumbersGetBlockByMaterial = ClassMapping.CRAFT_MAGIC_NUMBERS.getClazz() + .getMethod("getBlock", craftBlock.getType().getClass()); + } } - // invoke and cast objects. - Object craftWorld = clazzCraftWorld.cast(location.getWorld()); - Object world = getHandle.invoke(craftWorld); - Object craftBlock = clazzCraftBlock.cast(location.getBlock()); + Object nmsChunk = chunkToNmsChunk.invoke(loc.getChunk()); + Object nmsWorld = nmsChunkGetWorld.invoke(nmsChunk); - // Invoke final method. - updateAdjacentComparators - .invoke(world, clazzBlockPosition.getConstructor(double.class, double.class, double.class) - .newInstance(location.getX(), location.getY(), location.getZ()), - nmsBlockData_getBlock.invoke(craftBlock_getNMS.invoke(craftBlock))); + Object blockPosition; + if (craftBlockGetPosition != null) { + blockPosition = craftBlockGetPosition.invoke(craftBlock); + } else { + blockPosition = blockPositionConstructor.newInstance(loc.getX(), loc.getY(), loc.getZ()); + } + + Object nmsBlock; + if (craftBlockBlockDataGetter != null) { + nmsBlock = blockDataGetBlock.invoke(craftBlockBlockDataGetter.invoke(craftBlock)); + } else { + nmsBlock = craftMagicNumbersGetBlockByMaterial.invoke(null, craftBlock.getType()); + } + + nmsWorldUpdateAdjacentComparators.invoke(nmsWorld, blockPosition, nmsBlock); } catch (ReflectiveOperationException ex) { ex.printStackTrace(); } } - private static Class clazzIBlockData, clazzBlocks; - private static Method getByCombinedId, setType, getChunkAt, getBlockData; + /* Only to be used by #setBlockFast */ + private static Class clazzIBlockData, clazzBlocks, clazzCraftWorld, clazzBlockPosition; + /* Only to be used by #setBlockFast */ + private static Method getHandle, getByCombinedId, setType, getChunkAt, getBlockData; /** * Set a block to a certain type by updating the block directly in the From fd2809f98285aadfbe74ef0a4ff91618cd425df2 Mon Sep 17 00:00:00 2001 From: Christian Koop Date: Mon, 1 Nov 2021 22:30:51 +0100 Subject: [PATCH 18/18] Version 2.5.14 --- Compatibility/pom.xml | 2 +- Core/pom.xml | 2 +- Core/src/main/java/com/songoda/core/SongodaCore.java | 4 ++-- NMS/NMS-API/pom.xml | 2 +- NMS/NMS-v1_10_R1/pom.xml | 2 +- NMS/NMS-v1_11_R1/pom.xml | 2 +- NMS/NMS-v1_12_R1/pom.xml | 2 +- NMS/NMS-v1_13_R1/pom.xml | 2 +- NMS/NMS-v1_13_R2/pom.xml | 2 +- NMS/NMS-v1_14_R1/pom.xml | 2 +- NMS/NMS-v1_15_R1/pom.xml | 2 +- NMS/NMS-v1_16_R1/pom.xml | 2 +- NMS/NMS-v1_16_R2/pom.xml | 2 +- NMS/NMS-v1_16_R3/pom.xml | 2 +- NMS/NMS-v1_17_R1/pom.xml | 2 +- NMS/NMS-v1_8_R1/pom.xml | 2 +- NMS/NMS-v1_8_R2/pom.xml | 2 +- NMS/NMS-v1_8_R3/pom.xml | 2 +- NMS/NMS-v1_9_R1/pom.xml | 2 +- NMS/NMS-v1_9_R2/pom.xml | 2 +- pom.xml | 2 +- 21 files changed, 22 insertions(+), 22 deletions(-) diff --git a/Compatibility/pom.xml b/Compatibility/pom.xml index ce90de0e..d7a91436 100644 --- a/Compatibility/pom.xml +++ b/Compatibility/pom.xml @@ -7,7 +7,7 @@ com.songoda SongodaCore-Modules - 2.5.13 + 2.5.14 ../pom.xml diff --git a/Core/pom.xml b/Core/pom.xml index ce4bef49..258ef2d3 100644 --- a/Core/pom.xml +++ b/Core/pom.xml @@ -7,7 +7,7 @@ com.songoda SongodaCore-Modules - 2.5.13 + 2.5.14 ../pom.xml diff --git a/Core/src/main/java/com/songoda/core/SongodaCore.java b/Core/src/main/java/com/songoda/core/SongodaCore.java index 81335872..943519be 100644 --- a/Core/src/main/java/com/songoda/core/SongodaCore.java +++ b/Core/src/main/java/com/songoda/core/SongodaCore.java @@ -51,9 +51,9 @@ public class SongodaCore { private final static int coreRevision = 9; /** - * This has been added as of Rev 6 + * @since coreRevision 6 */ - private final static String coreVersion = "2.5.13"; + private final static String coreVersion = "2.5.14"; /** * This is specific to the website api diff --git a/NMS/NMS-API/pom.xml b/NMS/NMS-API/pom.xml index c159a620..845dfe6e 100644 --- a/NMS/NMS-API/pom.xml +++ b/NMS/NMS-API/pom.xml @@ -7,7 +7,7 @@ com.songoda SongodaCore-Modules - 2.5.13 + 2.5.14 ../../pom.xml diff --git a/NMS/NMS-v1_10_R1/pom.xml b/NMS/NMS-v1_10_R1/pom.xml index 729ce0fa..d2817511 100644 --- a/NMS/NMS-v1_10_R1/pom.xml +++ b/NMS/NMS-v1_10_R1/pom.xml @@ -7,7 +7,7 @@ com.songoda SongodaCore-Modules - 2.5.13 + 2.5.14 ../../pom.xml diff --git a/NMS/NMS-v1_11_R1/pom.xml b/NMS/NMS-v1_11_R1/pom.xml index 799ffbdf..2e58b923 100644 --- a/NMS/NMS-v1_11_R1/pom.xml +++ b/NMS/NMS-v1_11_R1/pom.xml @@ -7,7 +7,7 @@ com.songoda SongodaCore-Modules - 2.5.13 + 2.5.14 ../../pom.xml diff --git a/NMS/NMS-v1_12_R1/pom.xml b/NMS/NMS-v1_12_R1/pom.xml index 3ba7822d..1e27b28b 100644 --- a/NMS/NMS-v1_12_R1/pom.xml +++ b/NMS/NMS-v1_12_R1/pom.xml @@ -7,7 +7,7 @@ com.songoda SongodaCore-Modules - 2.5.13 + 2.5.14 ../../pom.xml diff --git a/NMS/NMS-v1_13_R1/pom.xml b/NMS/NMS-v1_13_R1/pom.xml index 243c3307..b9cc249a 100644 --- a/NMS/NMS-v1_13_R1/pom.xml +++ b/NMS/NMS-v1_13_R1/pom.xml @@ -7,7 +7,7 @@ com.songoda SongodaCore-Modules - 2.5.13 + 2.5.14 ../../pom.xml diff --git a/NMS/NMS-v1_13_R2/pom.xml b/NMS/NMS-v1_13_R2/pom.xml index d7650c5e..8b07acba 100644 --- a/NMS/NMS-v1_13_R2/pom.xml +++ b/NMS/NMS-v1_13_R2/pom.xml @@ -7,7 +7,7 @@ com.songoda SongodaCore-Modules - 2.5.13 + 2.5.14 ../../pom.xml diff --git a/NMS/NMS-v1_14_R1/pom.xml b/NMS/NMS-v1_14_R1/pom.xml index af0b87e0..7e9e696c 100644 --- a/NMS/NMS-v1_14_R1/pom.xml +++ b/NMS/NMS-v1_14_R1/pom.xml @@ -7,7 +7,7 @@ com.songoda SongodaCore-Modules - 2.5.13 + 2.5.14 ../../pom.xml diff --git a/NMS/NMS-v1_15_R1/pom.xml b/NMS/NMS-v1_15_R1/pom.xml index f2b6d381..47716f2d 100644 --- a/NMS/NMS-v1_15_R1/pom.xml +++ b/NMS/NMS-v1_15_R1/pom.xml @@ -7,7 +7,7 @@ com.songoda SongodaCore-Modules - 2.5.13 + 2.5.14 ../../pom.xml diff --git a/NMS/NMS-v1_16_R1/pom.xml b/NMS/NMS-v1_16_R1/pom.xml index 0e03e50f..1e3356ae 100644 --- a/NMS/NMS-v1_16_R1/pom.xml +++ b/NMS/NMS-v1_16_R1/pom.xml @@ -7,7 +7,7 @@ com.songoda SongodaCore-Modules - 2.5.13 + 2.5.14 ../../pom.xml diff --git a/NMS/NMS-v1_16_R2/pom.xml b/NMS/NMS-v1_16_R2/pom.xml index f4e8b5c3..f7b80cdd 100644 --- a/NMS/NMS-v1_16_R2/pom.xml +++ b/NMS/NMS-v1_16_R2/pom.xml @@ -7,7 +7,7 @@ com.songoda SongodaCore-Modules - 2.5.13 + 2.5.14 ../../pom.xml diff --git a/NMS/NMS-v1_16_R3/pom.xml b/NMS/NMS-v1_16_R3/pom.xml index d4046593..98c0cc26 100644 --- a/NMS/NMS-v1_16_R3/pom.xml +++ b/NMS/NMS-v1_16_R3/pom.xml @@ -7,7 +7,7 @@ com.songoda SongodaCore-Modules - 2.5.13 + 2.5.14 ../../pom.xml diff --git a/NMS/NMS-v1_17_R1/pom.xml b/NMS/NMS-v1_17_R1/pom.xml index 2e8501d7..17e2c3b6 100644 --- a/NMS/NMS-v1_17_R1/pom.xml +++ b/NMS/NMS-v1_17_R1/pom.xml @@ -7,7 +7,7 @@ com.songoda SongodaCore-Modules - 2.5.13 + 2.5.14 ../../pom.xml diff --git a/NMS/NMS-v1_8_R1/pom.xml b/NMS/NMS-v1_8_R1/pom.xml index d09487b5..c2e90872 100644 --- a/NMS/NMS-v1_8_R1/pom.xml +++ b/NMS/NMS-v1_8_R1/pom.xml @@ -7,7 +7,7 @@ com.songoda SongodaCore-Modules - 2.5.13 + 2.5.14 ../../pom.xml diff --git a/NMS/NMS-v1_8_R2/pom.xml b/NMS/NMS-v1_8_R2/pom.xml index ce2bb517..6a743c91 100644 --- a/NMS/NMS-v1_8_R2/pom.xml +++ b/NMS/NMS-v1_8_R2/pom.xml @@ -7,7 +7,7 @@ com.songoda SongodaCore-Modules - 2.5.13 + 2.5.14 ../../pom.xml diff --git a/NMS/NMS-v1_8_R3/pom.xml b/NMS/NMS-v1_8_R3/pom.xml index 7977f6d7..d939a92e 100644 --- a/NMS/NMS-v1_8_R3/pom.xml +++ b/NMS/NMS-v1_8_R3/pom.xml @@ -7,7 +7,7 @@ com.songoda SongodaCore-Modules - 2.5.13 + 2.5.14 ../../pom.xml diff --git a/NMS/NMS-v1_9_R1/pom.xml b/NMS/NMS-v1_9_R1/pom.xml index f5a50737..625d6414 100644 --- a/NMS/NMS-v1_9_R1/pom.xml +++ b/NMS/NMS-v1_9_R1/pom.xml @@ -7,7 +7,7 @@ com.songoda SongodaCore-Modules - 2.5.13 + 2.5.14 ../../pom.xml diff --git a/NMS/NMS-v1_9_R2/pom.xml b/NMS/NMS-v1_9_R2/pom.xml index 1eee9b36..75c28b83 100644 --- a/NMS/NMS-v1_9_R2/pom.xml +++ b/NMS/NMS-v1_9_R2/pom.xml @@ -7,7 +7,7 @@ com.songoda SongodaCore-Modules - 2.5.13 + 2.5.14 ../../pom.xml diff --git a/pom.xml b/pom.xml index a9db602f..0455148c 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.songoda SongodaCore-Modules - 2.5.13 + 2.5.14 pom