Compare commits

..

No commits in common. "v6" and "v3.2.26" have entirely different histories.
v6 ... v3.2.26

1000 changed files with 75961 additions and 90737 deletions

View File

@ -1,387 +0,0 @@
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
max_line_length = 130
tab_width = 4
ij_continuation_indent_size = 8
ij_formatter_off_tag = @formatter:off
ij_formatter_on_tag = @formatter:on
ij_formatter_tags_enabled = false
ij_smart_tabs = false
ij_wrap_on_typing = true
[*.java]
ij_java_align_consecutive_assignments = false
ij_java_align_consecutive_variable_declarations = false
ij_java_align_group_field_declarations = false
ij_java_align_multiline_annotation_parameters = false
ij_java_align_multiline_array_initializer_expression = false
ij_java_align_multiline_assignment = false
ij_java_align_multiline_binary_operation = false
ij_java_align_multiline_chained_methods = false
ij_java_align_multiline_extends_list = false
ij_java_align_multiline_for = true
ij_java_align_multiline_method_parentheses = false
ij_java_align_multiline_parameters = true
ij_java_align_multiline_parameters_in_calls = false
ij_java_align_multiline_parenthesized_expression = false
ij_java_align_multiline_records = true
ij_java_align_multiline_resources = true
ij_java_align_multiline_ternary_operation = false
ij_java_align_multiline_text_blocks = false
ij_java_align_multiline_throws_list = false
ij_java_align_subsequent_simple_methods = false
ij_java_align_throws_keyword = false
ij_java_annotation_parameter_wrap = off
ij_java_array_initializer_new_line_after_left_brace = false
ij_java_array_initializer_right_brace_on_new_line = false
ij_java_array_initializer_wrap = off
ij_java_assert_statement_colon_on_next_line = false
ij_java_assert_statement_wrap = off
ij_java_assignment_wrap = off
ij_java_binary_operation_sign_on_next_line = false
ij_java_binary_operation_wrap = off
ij_java_blank_lines_after_anonymous_class_header = 0
ij_java_blank_lines_after_class_header = 1
ij_java_blank_lines_after_imports = 1
ij_java_blank_lines_after_package = 1
ij_java_blank_lines_around_class = 1
ij_java_blank_lines_around_field = 0
ij_java_blank_lines_around_field_in_interface = 0
ij_java_blank_lines_around_initializer = 1
ij_java_blank_lines_around_method = 1
ij_java_blank_lines_around_method_in_interface = 1
ij_java_blank_lines_before_class_end = 1
ij_java_blank_lines_before_imports = 1
ij_java_blank_lines_before_method_body = 0
ij_java_blank_lines_before_package = 0
ij_java_block_brace_style = end_of_line
ij_java_block_comment_at_first_column = true
ij_java_call_parameters_new_line_after_left_paren = true
ij_java_call_parameters_right_paren_on_new_line = true
ij_java_call_parameters_wrap = on_every_item
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 = 100000
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
ij_java_do_while_brace_force = always
ij_java_doc_add_blank_line_after_description = true
ij_java_doc_add_blank_line_after_param_comments = false
ij_java_doc_add_blank_line_after_return = false
ij_java_doc_add_p_tag_on_empty_lines = true
ij_java_doc_align_exception_comments = true
ij_java_doc_align_param_comments = 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
ij_java_doc_keep_empty_lines = true
ij_java_doc_keep_empty_parameter_tag = true
ij_java_doc_keep_empty_return_tag = true
ij_java_doc_keep_empty_throws_tag = true
ij_java_doc_keep_invalid_tags = false
ij_java_doc_param_description_on_new_line = false
ij_java_doc_preserve_line_breaks = false
ij_java_doc_use_throws_not_exception_tag = true
ij_java_else_on_new_line = false
ij_java_enum_constants_wrap = split_into_lines
ij_java_extends_keyword_wrap = off
ij_java_extends_list_wrap = normal
ij_java_field_annotation_wrap = split_into_lines
ij_java_finally_on_new_line = false
ij_java_for_brace_force = always
ij_java_for_statement_new_line_after_left_paren = false
ij_java_for_statement_right_paren_on_new_line = false
ij_java_for_statement_wrap = off
ij_java_generate_final_locals = true
ij_java_generate_final_parameters = true
ij_java_if_brace_force = always
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 = 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_control_statement_in_one_line = true
ij_java_keep_first_column_comment = true
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 = 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
ij_java_layout_static_imports_separately = true
ij_java_line_comment_add_space = false
ij_java_line_comment_at_first_column = true
ij_java_method_annotation_wrap = split_into_lines
ij_java_method_brace_style = end_of_line
ij_java_method_call_chain_wrap = on_every_item
ij_java_method_parameters_new_line_after_left_paren = true
ij_java_method_parameters_right_paren_on_new_line = true
ij_java_method_parameters_wrap = on_every_item
ij_java_modifier_list_wrap = false
ij_java_names_count_to_use_import_on_demand = 100000
ij_java_new_line_after_lparen_in_record_header = false
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
ij_java_place_assignment_sign_on_next_line = false
ij_java_prefer_longer_names = false
ij_java_prefer_parameters_wrap = true
ij_java_record_components_wrap = normal
ij_java_repeat_synchronized = true
ij_java_replace_instanceof_and_cast = false
ij_java_replace_null_check = true
ij_java_replace_sum_lambda_with_method_ref = true
ij_java_resource_list_new_line_after_left_paren = false
ij_java_resource_list_right_paren_on_new_line = false
ij_java_resource_list_wrap = off
ij_java_rparen_on_new_line_in_record_header = false
ij_java_space_after_closing_angle_bracket_in_type_argument = false
ij_java_space_after_colon = true
ij_java_space_after_comma = true
ij_java_space_after_comma_in_type_arguments = true
ij_java_space_after_for_semicolon = true
ij_java_space_after_quest = true
ij_java_space_after_type_cast = true
ij_java_space_before_annotation_array_initializer_left_brace = false
ij_java_space_before_annotation_parameter_list = false
ij_java_space_before_array_initializer_left_brace = false
ij_java_space_before_catch_keyword = true
ij_java_space_before_catch_left_brace = true
ij_java_space_before_catch_parentheses = true
ij_java_space_before_class_left_brace = true
ij_java_space_before_colon = true
ij_java_space_before_colon_in_foreach = true
ij_java_space_before_comma = false
ij_java_space_before_do_left_brace = true
ij_java_space_before_else_keyword = true
ij_java_space_before_else_left_brace = true
ij_java_space_before_finally_keyword = true
ij_java_space_before_finally_left_brace = true
ij_java_space_before_for_left_brace = true
ij_java_space_before_for_parentheses = true
ij_java_space_before_for_semicolon = false
ij_java_space_before_if_left_brace = true
ij_java_space_before_if_parentheses = true
ij_java_space_before_method_call_parentheses = false
ij_java_space_before_method_left_brace = true
ij_java_space_before_method_parentheses = false
ij_java_space_before_opening_angle_bracket_in_type_parameter = false
ij_java_space_before_quest = true
ij_java_space_before_switch_left_brace = true
ij_java_space_before_switch_parentheses = true
ij_java_space_before_synchronized_left_brace = true
ij_java_space_before_synchronized_parentheses = true
ij_java_space_before_try_left_brace = true
ij_java_space_before_try_parentheses = true
ij_java_space_before_type_parameter_list = false
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 = 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
ij_java_spaces_around_assignment_operators = true
ij_java_spaces_around_bitwise_operators = true
ij_java_spaces_around_equality_operators = true
ij_java_spaces_around_lambda_arrow = true
ij_java_spaces_around_logical_operators = true
ij_java_spaces_around_method_ref_dbl_colon = false
ij_java_spaces_around_multiplicative_operators = true
ij_java_spaces_around_relational_operators = true
ij_java_spaces_around_shift_operators = true
ij_java_spaces_around_type_bounds_in_type_parameters = true
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 = false
ij_java_spaces_within_brackets = false
ij_java_spaces_within_cast_parentheses = false
ij_java_spaces_within_catch_parentheses = false
ij_java_spaces_within_for_parentheses = false
ij_java_spaces_within_if_parentheses = false
ij_java_spaces_within_method_call_parentheses = false
ij_java_spaces_within_method_parentheses = false
ij_java_spaces_within_parentheses = false
ij_java_spaces_within_switch_parentheses = false
ij_java_spaces_within_synchronized_parentheses = false
ij_java_spaces_within_try_parentheses = false
ij_java_spaces_within_while_parentheses = false
ij_java_special_else_if_treatment = true
ij_java_subclass_name_suffix = Impl
ij_java_ternary_operation_signs_on_next_line = true
ij_java_ternary_operation_wrap = on_every_item
ij_java_test_name_suffix = Test
ij_java_throws_keyword_wrap = off
ij_java_throws_list_wrap = normal
ij_java_use_external_annotations = false
ij_java_use_fq_class_names = false
ij_java_use_relative_indents = false
ij_java_use_single_class_imports = true
ij_java_variable_annotation_wrap = off
ij_java_visibility = public
ij_java_while_brace_force = always
ij_java_while_on_new_line = false
ij_java_wrap_comments = false
ij_java_wrap_first_method_in_call_chain = true
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
[.editorconfig]
ij_editorconfig_align_group_field_declarations = false
ij_editorconfig_space_after_colon = false
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
[{*.gradle.kts, *.kt, *.kts, *.main.kts}]
ij_kotlin_align_in_columns_case_branch = false
ij_kotlin_align_multiline_binary_operation = false
ij_kotlin_align_multiline_extends_list = false
ij_kotlin_align_multiline_method_parentheses = false
ij_kotlin_align_multiline_parameters = true
ij_kotlin_align_multiline_parameters_in_calls = false
ij_kotlin_allow_trailing_comma = false
ij_kotlin_allow_trailing_comma_on_call_site = false
ij_kotlin_assignment_wrap = off
ij_kotlin_blank_lines_after_class_header = 0
ij_kotlin_blank_lines_around_block_when_branches = 0
ij_kotlin_blank_lines_before_declaration_with_comment_or_annotation_on_separate_line = 1
ij_kotlin_block_comment_at_first_column = true
ij_kotlin_call_parameters_new_line_after_left_paren = false
ij_kotlin_call_parameters_right_paren_on_new_line = false
ij_kotlin_call_parameters_wrap = off
ij_kotlin_catch_on_new_line = false
ij_kotlin_class_annotation_wrap = split_into_lines
ij_kotlin_continuation_indent_for_chained_calls = true
ij_kotlin_continuation_indent_for_expression_bodies = true
ij_kotlin_continuation_indent_in_argument_lists = true
ij_kotlin_continuation_indent_in_elvis = true
ij_kotlin_continuation_indent_in_if_conditions = true
ij_kotlin_continuation_indent_in_parameter_lists = true
ij_kotlin_continuation_indent_in_supertype_lists = true
ij_kotlin_else_on_new_line = false
ij_kotlin_enum_constants_wrap = off
ij_kotlin_extends_list_wrap = off
ij_kotlin_field_annotation_wrap = split_into_lines
ij_kotlin_finally_on_new_line = false
ij_kotlin_if_rparen_on_new_line = false
ij_kotlin_import_nested_classes = false
ij_kotlin_insert_whitespaces_in_simple_one_line_method = true
ij_kotlin_keep_blank_lines_before_right_brace = 2
ij_kotlin_keep_blank_lines_in_code = 2
ij_kotlin_keep_blank_lines_in_declarations = 2
ij_kotlin_keep_first_column_comment = true
ij_kotlin_keep_indents_on_empty_lines = false
ij_kotlin_keep_line_breaks = true
ij_kotlin_lbrace_on_next_line = false
ij_kotlin_line_comment_add_space = false
ij_kotlin_line_comment_at_first_column = true
ij_kotlin_method_annotation_wrap = split_into_lines
ij_kotlin_method_call_chain_wrap = off
ij_kotlin_method_parameters_new_line_after_left_paren = false
ij_kotlin_method_parameters_right_paren_on_new_line = false
ij_kotlin_method_parameters_wrap = off
ij_kotlin_name_count_to_use_star_import = 5
ij_kotlin_name_count_to_use_star_import_for_members = 3
ij_kotlin_parameter_annotation_wrap = off
ij_kotlin_space_after_comma = true
ij_kotlin_space_after_extend_colon = true
ij_kotlin_space_after_type_colon = true
ij_kotlin_space_before_catch_parentheses = true
ij_kotlin_space_before_comma = false
ij_kotlin_space_before_extend_colon = true
ij_kotlin_space_before_for_parentheses = true
ij_kotlin_space_before_if_parentheses = true
ij_kotlin_space_before_lambda_arrow = true
ij_kotlin_space_before_type_colon = false
ij_kotlin_space_before_when_parentheses = true
ij_kotlin_space_before_while_parentheses = true
ij_kotlin_spaces_around_additive_operators = true
ij_kotlin_spaces_around_assignment_operators = true
ij_kotlin_spaces_around_equality_operators = true
ij_kotlin_spaces_around_function_type_arrow = true
ij_kotlin_spaces_around_logical_operators = true
ij_kotlin_spaces_around_multiplicative_operators = true
ij_kotlin_spaces_around_range = false
ij_kotlin_spaces_around_relational_operators = true
ij_kotlin_spaces_around_unary_operator = false
ij_kotlin_spaces_around_when_arrow = true
ij_kotlin_variable_annotation_wrap = off
ij_kotlin_while_on_new_line = false
ij_kotlin_wrap_elvis_expressions = 1
ij_kotlin_wrap_expression_body_functions = 0
ij_kotlin_wrap_first_method_in_call_chain = false
[*.json]
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
[{*.htm, *.html, *.sht, *.shtm, *.shtml}]
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
ij_html_do_not_indent_children_of_tags = html, body, thead, tbody, tfoot
ij_html_enforce_quotes = false
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
ij_html_uniform_ident = false
[{*.yaml, *.yml}]
indent_size = 2
ij_yaml_keep_indents_on_empty_lines = false
ij_yaml_keep_line_breaks = true
ij_yaml_space_before_colon = false
ij_yaml_spaces_within_braces = true
ij_yaml_spaces_within_brackets = true

4
.gitattributes vendored
View File

@ -1,4 +0,0 @@
* text=auto
*.java text
*.jar binary

1
.github/CODEOWNERS vendored
View File

@ -1 +0,0 @@
* @IntellectualSites/plotsquared-team

2
.github/CONTRIBUTING.md vendored Normal file
View File

@ -0,0 +1,2 @@
### Bugs
Please provide a `/plot debugpaste` if you are reporting a bug.

12
.github/ISSUE_TEMPLATE.md vendored Normal file
View File

@ -0,0 +1,12 @@
# Bug report template (clear for feature request)
**Debug paste link**:
**Description of the problem:**
**How to replicate**:
Make sure you've completed the following steps (put X inside of brackets):
- [ ] Include `/plot debugpaste`
- [ ] Made sure there aren't duplicates of this report [(Use Search)](https://github.com/IntellectualSites/PlotSquared/issues)
- [ ] Made sure you're using an updated version of PlotSquared
- [ ] Made sure the bug/error isn't caused by any other plugin

View File

@ -1,105 +0,0 @@
name: Bug report
description: Create a report to help us improve
labels: 'Requires Testing'
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to fill out this bug report for PlotSquared! Fill out the following form to your best ability to help us fix the problem.
Only use this if you're absolutely sure that you found a bug and can reproduce it. For anything else, use: [our Discord server](https://discord.gg/intellectualsites) or [the wiki](https://intellectualsites.github.io/plotsquared-documentation/).
Do NOT use the public issue tracker to report security vulnerabilities! They are disclosed using [this](https://forms.gle/btgdRn9yhGtzEiGW8) form!
- type: dropdown
attributes:
label: Server Implementation
description: Which server Implementation are you using? If your server implementation is not listed, it is not supported. Switch to a supported version first.
multiple: false
options:
- Paper
- Spigot
validations:
required: true
- type: dropdown
attributes:
label: Server Version
description: Which server version version you using? If your server version is not listed, it is not supported. Update to a supported version first.
multiple: false
options:
- '1.19.3'
- '1.19.2'
- '1.19.1'
- '1.19'
- '1.18.2'
- '1.18.1'
- '1.17.1'
- '1.16.5'
validations:
required: true
- type: textarea
attributes:
label: Describe the bug
description: A clear and concise description of what the bug is.
validations:
required: true
- type: textarea
attributes:
label: To Reproduce
description: Steps to reproduce this behaviour
placeholder: |
1. Go to '...'
2. Click on '...'
3. Scroll down to '...'
4. See error
validations:
required: true
- type: textarea
attributes:
label: Expected behaviour
description: A clear and concise description of what you expected to happen.
validations:
required: true
- type: textarea
attributes:
label: Screenshots / Videos
description: If applicable, add screenshots to help explain your problem.
- type: input
attributes:
label: Error log (if applicable)
description: If you are reporting a console error, upload any relevant log excerpts to either https://paste.gg/ or https://gist.github.com, save and the paste the link in this box.
- type: input
attributes:
label: Plot Debugpaste
description: Run `/plot debugpaste` in your console or ingame and provide the output link here.
validations:
required: true
- type: input
attributes:
label: PlotSquared Version
description: What version of PlotSquared are you running? (`/version PlotSquared`)
placeholder: "For example: PlotSquared version 5.13.11-Premium"
validations:
required: true
- type: checkboxes
attributes:
label: Checklist
description: Make sure you have followed each of the steps outlined here.
options:
- label: I have included a Plot debugpaste.
required: true
- label: I am using the newest build from https://www.spigotmc.org/resources/77506/ and the issue still persists.
required: true
- type: textarea
attributes:
label: Anything else?
description: You can provide additional context below.

View File

@ -1,8 +0,0 @@
blank_issues_enabled: false
contact_links:
- name: IntellectualSites Discord
url: https://discord.gg/intellectualsites
about: Our support Discord, please ask questions and seek support here.
- name: PlotSquared Wiki
url: https://intellectualsites.github.io/plotsquared-documentation/
about: Take a look at the wiki page for instructions how to setup PlotSquared and use its commands.

View File

@ -1,29 +0,0 @@
name: Feature request
description: Suggest an idea for this project
labels: 'Enhancement'
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to fill out this feature request for PlotSquared! Fill out the following form to your best ability to help us understand your feature request and greately improve the change of it getting added.
For anything else than a feature request, use: [our Discord server](https://discord.gg/intellectualsites) or [the wiki](https://intellectualsites.github.io/plotsquared-documentation/).
- type: textarea
attributes:
label: What feature do you want to see added?
description: A clear and concise description of your feature request.
validations:
required: true
- type: textarea
attributes:
label: Are there any alternatives?
description: List any alternatives you might have tried
validations:
required: true
- type: textarea
attributes:
label: Anything else?
description: You can provide additional context below.

View File

@ -1 +0,0 @@
_extends: .github

18
.github/stale.yml vendored
View File

@ -1,18 +0,0 @@
daysUntilStale: 30
daysUntilClose: 7
only: issues
exemptLabels:
- "Bug"
- "Enhancement"
- "Approved"
- "Priority"
- "Under investigation"
staleLabel: "resolution: stale"
markComment: >
This issue has been automatically marked as stale because it has not had
recent activity. It will be closed if no further activity occurs. If the issue is still present and can be reproduced, please let the team know.
Thank you for your contributions.
closeComment: >
This issue has been automatically closed because it has not had activity in
a long time. If the issue still applies to the most recent supported
version, please reply to this issue and the team will reopen it.

View File

@ -1,24 +0,0 @@
name: Announce release on discord
on:
release:
types: [published]
jobs:
send_announcement:
runs-on: ubuntu-latest
steps:
- name: send custom message with args
env:
DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }}
DISCORD_USERNAME: PlotSquared Release
DISCORD_AVATAR: https://raw.githubusercontent.com/IntellectualSites/Assets/main/plugins/PlotSquared/PlotSquared.png
uses: Ilshidur/action-discord@08d9328877d6954120eef2b07abbc79249bb6210 # ratchet:Ilshidur/action-discord@0.3.2
with:
args: |
"<@&525015541815967744> <@&679322738552471574> <@&699293353862496266>"
""
"<:plotsquared:730750385886593039> **PlotSquared ${{ github.event.release.tag_name }} has been released!**"
""
"Click here to view changelog: https://github.com/IntellectualSites/PlotSquared/releases/tag/${{ github.event.release.tag_name }}"
""
"The download is available at:"
"- Spigot: <https://www.spigotmc.org/resources/77506/>"

View File

@ -1,21 +0,0 @@
name: Build PR
on: [pull_request]
jobs:
build_pr:
if: github.repository_owner == 'IntellectualSites'
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
steps:
- name: Checkout Repository
uses: actions/checkout@v3
- name: Validate Gradle Wrapper
uses: gradle/wrapper-validation-action@55e685c48d84285a5b0418cd094606e199cca3b6 # v1
- name: Setup Java
uses: actions/setup-java@v3
with:
distribution: temurin
java-version: 17
- name: Clean Build
run: ./gradlew clean build

View File

@ -1,67 +0,0 @@
name: build
on:
push:
branches:
- v6
jobs:
build:
if: github.repository_owner == 'IntellectualSites'
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v3
- name: Validate Gradle Wrapper
uses: gradle/wrapper-validation-action@55e685c48d84285a5b0418cd094606e199cca3b6 # v1
- name: Setup Java
uses: actions/setup-java@v3
with:
distribution: temurin
java-version: 17
- name: Clean Build
run: ./gradlew clean build
- name: Determine release status
if: ${{ runner.os == 'Linux' }}
run: |
if [ "$(./gradlew properties | awk '/^version:/ { print $2; }' | grep '\-SNAPSHOT')" ]; then
echo "STATUS=snapshot" >> $GITHUB_ENV
else
echo "STATUS=release" >> $GITHUB_ENV
fi
- name: Publish Release
if: ${{ runner.os == 'Linux' && env.STATUS == 'release' && github.event_name == 'push' && github.ref == 'refs/heads/v6'}}
run: ./gradlew publishToSonatype closeAndReleaseSonatypeStagingRepository
env:
ORG_GRADLE_PROJECT_sonatypeUsername: ${{ secrets.SONATYPE_USERNAME }}
ORG_GRADLE_PROJECT_sonatypePassword: ${{ secrets.SONATYPE_PASSWORD }}
ORG_GRADLE_PROJECT_signingKey: ${{ secrets.SIGNING_KEY }}
ORG_GRADLE_PROJECT_signingPassword: ${{ secrets.SIGNING_PASSWORD }}
- name: Publish Snapshot
if: ${{ runner.os == 'Linux' && env.STATUS != 'release' && github.event_name == 'push' && github.ref == 'refs/heads/v6' }}
run: ./gradlew publishToSonatype
env:
ORG_GRADLE_PROJECT_sonatypeUsername: ${{ secrets.SONATYPE_USERNAME }}
ORG_GRADLE_PROJECT_sonatypePassword: ${{ secrets.SONATYPE_PASSWORD }}
- name: Publish core javadoc
if: ${{ runner.os == 'Linux' && env.STATUS == 'release' && github.event_name == 'push' && github.ref == 'refs/heads/v6'}}
uses: cpina/github-action-push-to-another-repository@0a14457bb28b04dfa1652e0ffdfda866d2845c73 # main
env:
SSH_DEPLOY_KEY: ${{ secrets.SSH_DEPLOY_KEY }}
with:
source-directory: 'Core/build/docs/javadoc'
destination-github-username: 'IntellectualSites'
destination-repository-name: 'plotsquared-javadocs'
user-email: ${{ secrets.USER_EMAIL }}
target-branch: main
target-directory: core
- name: Publish bukkit javadoc
if: ${{ runner.os == 'Linux' && env.STATUS == 'release' && github.event_name == 'push' && github.ref == 'refs/heads/v6'}}
uses: cpina/github-action-push-to-another-repository@0a14457bb28b04dfa1652e0ffdfda866d2845c73 # main
env:
SSH_DEPLOY_KEY: ${{ secrets.SSH_DEPLOY_KEY }}
with:
source-directory: 'Bukkit/build/docs/javadoc'
destination-github-username: 'IntellectualSites'
destination-repository-name: 'plotsquared-javadocs'
user-email: ${{ secrets.USER_EMAIL }}
target-branch: main
target-directory: bukkit

View File

@ -1,28 +0,0 @@
name: "CodeQL"
on:
pull_request:
# The branches below must be a subset of the branches above
branches: [v6]
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: ['java']
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Initialize CodeQL
uses: github/codeql-action/init@32dc499307d133bb5085bae78498c0ac2cf762d5 # v2
with:
languages: ${{ matrix.language }}
- name: Autobuild
uses: github/codeql-action/autobuild@32dc499307d133bb5085bae78498c0ac2cf762d5 # v2
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@32dc499307d133bb5085bae78498c0ac2cf762d5 # v2

View File

@ -1,17 +0,0 @@
name: draft release
on:
push:
branches:
- v6
pull_request:
types: [opened, reopened, synchronize]
pull_request_target:
types: [opened, reopened, synchronize]
jobs:
update_release_draft:
if: ${{ github.event_name != 'pull_request' || github.repository != github.event.pull_request.head.repo.full_name }}
runs-on: ubuntu-latest
steps:
- uses: release-drafter/release-drafter@v5
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

267
.gitignore vendored
View File

@ -1,139 +1,130 @@
### Others ###
*.cmd
*.sh
*.prefs
Core/build
### Maven ###
/mvn
/target/lib
/target/maven-archiver
/target/classes
/target/maven-status
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties
dependency-reduced-pom.xml
buildNumber.properties
.mvn/timing.properties
out/
### Java ###
*.class
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.war
*.ear
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
*.iml
## Directory-based project format:
/.idea/*
!/.idea/icon.svg
# if you remove the above rule, at least ignore the following:
# User-specific stuff:
# .idea/workspace.xml
# .idea/tasks.xml
# .idea/dictionaries
# .idea/shelf
# Sensitive or high-churn files:
# .idea/dataSources.ids
# .idea/dataSources.xml
# .idea/sqlDataSources.xml
# .idea/dynamic.xml
# .idea/uiDesigner.xml
# Gradle:
# .idea/gradle.xml
# .idea/libraries
.gradle
# Mongo Explorer plugin:
# .idea/mongoSettings.xml
## File-based project format:
*.ipr
*.iws
## Plugin-specific files:
# IntelliJ
/out/
# JIRA plugin
atlassian-ide-plugin.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
### Eclipse ###
*.pydevproject
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
# Eclipse Core
.project
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# CDT-specific
.cproject
# JDT-specific (Eclipse Java Development Tools)
.classpath
# Java annotation processor (APT)
.factorypath
# PDT-specific
.buildpath
# sbteclipse plugin
.target
# TeXlipse plugin
.texlipse
# STS (Spring Tool Suite)
.springBeans
### Others ###
*.bat
*.cmd
*.sh
*.prefs
### Maven ###
/target/lib
/target/maven-archiver
/target/classes
/target/maven-status
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties
dependency-reduced-pom.xml
buildNumber.properties
.mvn/timing.properties
### Java ###
*.class
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
*.iml
## Directory-based project format:
.idea/
# if you remove the above rule, at least ignore the following:
# User-specific stuff:
# .idea/workspace.xml
# .idea/tasks.xml
# .idea/dictionaries
# .idea/shelf
# Sensitive or high-churn files:
# .idea/dataSources.ids
# .idea/dataSources.xml
# .idea/sqlDataSources.xml
# .idea/dynamic.xml
# .idea/uiDesigner.xml
# Gradle:
# .idea/gradle.xml
# .idea/libraries
# Mongo Explorer plugin:
# .idea/mongoSettings.xml
## File-based project format:
*.ipr
*.iws
## Plugin-specific files:
# IntelliJ
/out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
### Eclipse ###
*.pydevproject
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
# Eclipse Core
.project
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# CDT-specific
.cproject
# JDT-specific (Eclipse Java Development Tools)
.classpath
# Java annotation processor (APT)
.factorypath
# PDT-specific
.buildpath
# sbteclipse plugin
.target
# TeXlipse plugin
.texlipse
# STS (Spring Tool Suite)
.springBeans
/target/
checkstyle.xml
classes/
*.bat
# Other
docs/
build/
.DS_Store

50
.idea/icon.svg generated
View File

@ -1,50 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="svg2" xml:space="preserve" width="4000" height="3333.3333" viewBox="0 0 4000 3333.3333" sodipodi:docname="PlotSquared.ai">
<metadata id="metadata8">
<rdf:RDF>
<cc:Work rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
</cc:Work>
</rdf:RDF>
</metadata>
<defs id="defs6">
<clipPath clipPathUnits="userSpaceOnUse" id="clipPath18">
<path d="M 0,2500 H 3000 V 0 H 0 Z" id="path16" />
</clipPath>
</defs>
<sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="640" inkscape:window-height="480" id="namedview4" />
<g id="g10" inkscape:groupmode="layer" inkscape:label="PlotSquared" transform="matrix(1.3333333,0,0,-1.3333333,0,3333.3333)">
<g id="g12">
<g id="g14" clip-path="url(#clipPath18)">
<g id="g20" transform="translate(1486.1511,2242.6453)">
<path d="m 0,0 c 16.533,10.846 33.211,21.453 50.104,31.699 78.972,-48.281 153.985,-102.704 227.269,-159.144 148.61,-115.422 287.884,-243.01 414.393,-382.333 111.39,-122.861 212.751,-255.152 298.898,-396.971 52.744,-87.322 100.544,-177.884 139.514,-272.214 -11.638,-3.551 -23.108,-7.655 -34.362,-12.286 l -0.24,0.288 c -11.135,12.982 -24.141,24.212 -34.915,37.506 -22.557,23.013 -45.425,45.737 -68.03,68.678 -19.725,20.253 -40.601,39.45 -58.958,60.974 -36.355,36.451 -72.517,73.093 -108.944,109.471 -22.628,26.013 -48.064,49.385 -71.965,74.197 -19.029,19.485 -38.706,38.346 -57.519,57.999 -12.166,14.998 -26.684,27.716 -39.93,41.658 -27.668,27.524 -54.903,55.479 -82.571,82.979 -23.924,27.956 -51.664,52.264 -76.692,79.164 -4.68,4.487 -8.855,10.774 -15.886,11.326 -22.34,34.027 -58.311,57.327 -97.377,67.502 -104.312,99.153 -215.487,191.202 -332.661,274.782 -117.942,-83.94 -229.476,-176.781 -334.484,-276.39 -26.684,-0.024 -53.368,0.024 -80.076,-0.024 0.024,-26.564 0.048,-53.104 0,-79.668 -72.229,-73.021 -139.491,-150.937 -202.385,-232.092 -63.758,-82.619 -121.973,-169.51 -173.541,-260.264 131.932,-69.061 257.864,-149.521 375.926,-240.275 0.096,-26.444 -0.12,-52.888 0.096,-79.332 l 0.744,-0.984 c 20.109,-24.14 43.409,-45.233 65.126,-67.861 15.118,-15.382 30.571,-30.404 45.569,-45.881 17.565,-20.733 37.698,-39.042 56.607,-58.503 19.917,-20.781 41.25,-40.218 59.967,-62.151 29.156,-29.299 58.167,-58.815 87.515,-87.922 29.155,-33.043 61.502,-63.111 92.169,-94.738 13.726,-12.67 25.124,-27.571 38.634,-40.457 25.029,-25.365 50.129,-50.657 75.325,-75.853 -37.914,-51.208 -73.741,-103.952 -107.192,-158.183 -167.83,273.317 -397.235,507.305 -662.37,687.158 -81.875,55.335 -167.23,105.584 -255.681,149.641 -52.815,26.276 -106.831,50.248 -162.239,70.381 99.393,233.628 242.795,446.715 410.289,636.79 93.562,106.088 194.634,205.433 301.466,298.13 C -217.335,-155.808 -111.439,-73.789 0,0" style="fill:#062f4c;fill-opacity:1;fill-rule:nonzero;stroke:none" id="path22" />
</g>
<g id="g24" transform="translate(1201.7948,1741.5303)">
<path d="M 0,0 C 105.008,99.609 216.543,192.45 334.485,276.39 451.659,192.81 562.833,100.76 667.146,1.608 c -34.987,8.83 -71.51,9.718 -107.264,6.431 -41.202,-4.296 -82.907,-19.077 -112.543,-48.953 -33.019,-32.155 -49.456,-77.604 -55.311,-122.501 -28.124,27.908 -56.104,55.983 -84.035,84.083 -2.976,2.976 -6.839,4.823 -10.391,6.911 -19.029,26.348 -45.953,46.673 -76.62,57.495 C 187.555,-2.472 151.513,-0.12 116.166,0 Z" style="fill:#4c8fcc;fill-opacity:1;fill-rule:nonzero;stroke:none" id="path26" />
</g>
<g id="g28" transform="translate(919.3342,1429.7462)">
<path d="m 0,0 c 62.894,81.156 130.156,159.072 202.385,232.092 0.048,-244.21 0.024,-488.421 0,-732.631 C 84.323,-409.785 -41.61,-329.325 -173.541,-260.264 -121.973,-169.51 -63.758,-82.619 0,0" style="fill:#4c8fcc;fill-opacity:1;fill-rule:nonzero;stroke:none" id="path30" />
</g>
<g id="g32" transform="translate(1649.134,1700.6166)">
<path d="m 0,0 c 29.635,29.875 71.341,44.657 112.543,48.952 35.754,3.288 72.277,2.4 107.263,-6.431 39.066,-10.174 75.037,-33.474 97.377,-67.501 11.879,-17.661 20.181,-37.411 26.42,-57.687 10.871,-38.802 11.95,-79.356 11.446,-119.358 -44.345,-0.072 -88.69,0.048 -133.035,-0.072 -1.032,30.907 3.263,63.686 -10.175,92.626 -9.526,20.325 -32.107,31.243 -53.751,32.131 -21.453,1.44 -45.065,-4.32 -59.175,-21.597 -12.79,-15.861 -15.382,-37.002 -16.558,-56.655 -1.295,-29.132 3.696,-59.031 17.518,-84.923 16.821,-30.619 39.378,-57.783 64.526,-81.9 31.387,-32.634 67.501,-60.374 97.857,-94.041 27.332,-28.988 51.256,-61.479 68.005,-97.785 20.541,-41.13 26.972,-87.827 25.82,-133.372 -0.912,-32.107 -5.231,-64.406 -16.149,-94.737 -11.59,-31.699 -31.123,-61.047 -58.335,-81.371 -25.124,-19.125 -55.696,-29.852 -86.651,-34.771 -49.552,-6.743 -101.888,-4.847 -148.465,14.854 -35.227,14.829 -64.238,42.689 -81.708,76.548 -20.996,40.242 -27.115,86.339 -27.259,131.212 0.048,17.829 0,35.658 0.048,53.463 44.345,0.048 88.69,-0.023 133.059,0.048 1.728,-35.538 -4.055,-72.06 5.663,-106.807 5.783,-22.173 26.204,-37.794 48.185,-41.754 20.733,-3.431 43.577,-2.015 61.622,9.791 15.502,9.43 23.949,26.78 26.78,44.225 5.903,35.922 1.872,74.293 -15.381,106.688 -16.918,30.595 -39.474,57.711 -64.55,81.899 -33.187,34.099 -71.173,63.254 -102.585,99.081 -26.756,28.867 -49.408,61.646 -65.486,97.641 -24.572,52.48 -26.731,112.422 -20.18,169.102 C -49.456,-77.604 -33.019,-32.155 0,0" style="fill:#feeeee;fill-opacity:1;fill-rule:nonzero;stroke:none" id="path34" />
</g>
<g id="g36" transform="translate(1262.7214,1613.126)">
<path d="m 0,0 v -301.13 c 23.204,0.024 46.409,-0.048 69.613,0.024 18.525,0.288 38.202,6.575 50.153,21.429 12.43,17.277 13.917,39.522 14.613,60.111 0.024,43.985 -0.048,87.994 0.024,131.979 -0.48,23.637 -0.983,50.369 -17.277,69.23 C 104.864,-5.711 86.867,-0.24 69.589,0 46.385,0.048 23.204,0.024 0,0 m -141.002,128.38 c 26.708,0.048 53.392,0 80.075,0.024 H 55.24 c 35.346,-0.12 71.389,-2.471 104.815,-14.925 30.668,-10.823 57.592,-31.148 76.621,-57.496 26.852,-39.09 36.69,-87.202 38.058,-133.947 0.024,-48.833 0.096,-97.689 -0.024,-146.521 -1.728,-47.993 -11.974,-97.953 -41.514,-136.971 -22.748,-30.644 -57.495,-50.801 -94.281,-59.583 -45.377,-11.878 -92.578,-6.791 -138.891,-7.847 -0.072,-111.799 0,-223.574 -0.024,-335.373 -13.942,0 -27.86,0.024 -41.778,-0.024 -32.802,0.072 -65.605,0 -98.384,0.048 l -0.744,0.984 c -0.216,26.444 0,52.888 -0.096,79.332 0.024,244.211 0.048,488.421 0,732.632 0.048,26.563 0.024,53.103 0,79.667" style="fill:#feeeee;fill-opacity:1;fill-rule:nonzero;stroke:none" id="path38" />
</g>
<g id="g40" transform="translate(1966.3174,1675.6364)">
<path d="m 0,0 c 7.031,-0.552 11.206,-6.839 15.885,-11.326 25.029,-26.9 52.768,-51.208 76.693,-79.164 27.667,-27.5 54.903,-55.456 82.571,-82.979 13.246,-13.942 27.764,-26.66 39.93,-41.658 18.813,-19.653 38.49,-38.514 57.519,-57.999 23.9,-24.812 49.337,-48.185 71.965,-74.197 36.427,-36.378 72.589,-73.02 108.943,-109.471 18.358,-21.524 39.234,-40.722 58.959,-60.974 22.605,-22.941 45.473,-45.665 68.03,-68.678 10.774,-13.294 23.78,-24.524 34.914,-37.506 -103.904,-41.97 -203.488,-94.114 -298.922,-152.761 -246.994,-152.28 -466.224,-350.298 -639.333,-583.398 -25.197,25.196 -50.297,50.488 -75.325,75.852 -13.51,12.886 -24.908,27.788 -38.634,40.458 -30.667,31.627 -63.014,61.695 -92.17,94.738 -29.347,29.107 -58.359,58.623 -87.514,87.922 -18.717,21.933 -40.05,41.37 -59.967,62.151 -18.909,19.461 -39.042,37.77 -56.607,58.503 -14.998,15.477 -30.452,30.499 -45.569,45.88 -21.717,22.629 -45.017,43.722 -65.126,67.862 32.779,-0.048 65.582,0.024 98.384,-0.048 114.391,-98.097 220.407,-205.984 315.384,-322.99 92.914,114.318 196.242,220.022 307.753,316.271 30.955,4.919 61.526,15.646 86.65,34.771 27.212,20.325 46.745,49.672 58.335,81.371 107.312,77.988 219.327,149.929 337.509,210.376 -35.299,64.67 -75.829,126.437 -118.254,186.643 C 176.253,-228.037 104.24,-140.115 26.42,-57.687 20.181,-37.41 11.878,-17.661 0,0" style="fill:#042338;fill-opacity:1;fill-rule:nonzero;stroke:none" id="path42" />
</g>
<g id="g44" transform="translate(1499.3971,1669.1094)">
<path d="m 0,0 c 3.551,-2.088 7.415,-3.935 10.39,-6.911 27.932,-28.1 55.912,-56.175 84.036,-84.083 -6.551,-56.679 -4.392,-116.622 20.18,-169.102 16.078,-35.994 38.73,-68.774 65.486,-97.641 31.412,-35.826 69.398,-64.982 102.585,-99.081 25.076,-24.188 47.632,-51.304 64.55,-81.899 17.253,-32.395 21.284,-70.765 15.381,-106.688 -2.831,-17.445 -11.278,-34.794 -26.78,-44.225 -18.045,-11.806 -40.889,-13.222 -61.622,-9.79 -21.981,3.959 -42.402,19.58 -48.185,41.753 -9.718,34.747 -3.935,71.269 -5.663,106.808 -44.369,-0.072 -88.714,0 -133.059,-0.048 -0.048,-17.806 0,-35.635 -0.048,-53.464 0.144,-44.873 6.263,-90.97 27.259,-131.212 17.47,-33.859 46.481,-61.718 81.708,-76.548 46.577,-19.701 98.913,-21.597 148.465,-14.854 -111.511,-96.249 -214.839,-201.953 -307.753,-316.271 -94.977,117.006 -200.993,224.893 -315.383,322.99 13.918,0.048 27.836,0.024 41.777,0.024 0.024,111.799 -0.048,223.574 0.024,335.372 46.313,1.056 93.514,-4.031 138.891,7.847 36.786,8.783 71.533,28.94 94.282,59.583 29.539,39.018 39.785,88.978 41.513,136.971 0.12,48.833 0.048,97.689 0.024,146.522 C 36.69,-87.203 26.852,-39.09 0,0" style="fill:#1c72ba;fill-opacity:1;fill-rule:nonzero;stroke:none" id="path46" />
</g>
<g id="g48" transform="translate(1748.0469,1601.6797)">
<path d="M 0,0 C 14.11,17.277 37.722,23.036 59.175,21.597 80.82,20.709 103.4,9.791 112.927,-10.534 c 13.438,-28.94 9.142,-61.719 10.174,-92.626 44.345,0.12 88.691,0 133.036,0.072 0.504,40.002 -0.576,80.556 -11.447,119.358 77.82,-82.428 149.833,-170.35 215.583,-262.664 42.426,-60.207 82.956,-121.973 118.254,-186.643 -118.182,-60.447 -230.196,-132.388 -337.508,-210.376 10.918,30.331 15.238,62.63 16.149,94.737 1.152,45.545 -5.279,92.242 -25.82,133.372 -16.749,36.306 -40.673,68.797 -68.005,97.785 -30.355,33.667 -66.47,61.406 -97.857,94.041 -25.148,24.117 -47.705,51.28 -64.526,81.9 -13.822,25.892 -18.813,55.791 -17.517,84.923 C -15.382,-37.002 -12.79,-15.862 0,0" style="fill:#1c72ba;fill-opacity:1;fill-rule:nonzero;stroke:none" id="path50" />
</g>
<g id="g52" transform="translate(1262.7214,1613.126)">
<path d="m 0,0 c 23.204,0.024 46.385,0.048 69.589,0 17.278,-0.24 35.275,-5.711 47.537,-18.357 16.294,-18.861 16.797,-45.593 17.277,-69.23 -0.072,-43.985 0,-87.994 -0.024,-131.979 -0.696,-20.589 -2.183,-42.834 -14.613,-60.111 -11.951,-14.854 -31.628,-21.141 -50.153,-21.429 -23.204,-0.072 -46.409,0 -69.613,-0.024 z" style="fill:#1c72ba;fill-opacity:1;fill-rule:nonzero;stroke:none" id="path54" />
</g>
</g>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 11 KiB

View File

@ -1,116 +0,0 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
repositories {
maven {
name = "PlaceholderAPI"
url = uri("https://repo.extendedclip.com/content/repositories/placeholderapi/")
}
maven {
name = "PaperMC"
url = uri("https://repo.papermc.io/repository/maven-public/")
}
maven {
name = "EssentialsX"
url = uri("https://repo.essentialsx.net/releases/")
}
}
dependencies {
api(projects.plotSquaredCore)
// Metrics
implementation("org.bstats:bstats-bukkit")
// Paper
compileOnly("io.papermc.paper:paper-api")
implementation("io.papermc:paperlib")
// Plugins
compileOnly(libs.worldeditBukkit) {
exclude(group = "org.bukkit")
exclude(group = "org.spigotmc")
}
compileOnly("com.fastasyncworldedit:FastAsyncWorldEdit-Bukkit") { isTransitive = false }
testImplementation("com.fastasyncworldedit:FastAsyncWorldEdit-Bukkit") { isTransitive = false }
compileOnly("com.github.MilkBowl:VaultAPI") {
exclude(group = "org.bukkit")
}
compileOnly(libs.placeholderapi)
compileOnly(libs.luckperms)
compileOnly(libs.essentialsx)
compileOnly(libs.mvdwapi) { isTransitive = false }
// Other libraries
implementation(libs.squirrelid) { isTransitive = false }
implementation("dev.notmyfault.serverlib:ServerLib")
// Our libraries
implementation(libs.arkitektonika)
implementation(libs.http4j)
implementation("com.intellectualsites.paster:Paster")
implementation("com.intellectualsites.informative-annotations:informative-annotations")
// Adventure
implementation("net.kyori:adventure-platform-bukkit")
}
tasks.processResources {
filesMatching("plugin.yml") {
expand("version" to project.version)
}
}
tasks.named<ShadowJar>("shadowJar") {
dependencies {
exclude(dependency("org.checkerframework:"))
}
relocate("net.kyori.adventure", "com.plotsquared.core.configuration.adventure")
relocate("net.kyori.examination", "com.plotsquared.core.configuration.examination")
relocate("io.papermc.lib", "com.plotsquared.bukkit.paperlib")
relocate("org.bstats", "com.plotsquared.metrics")
relocate("org.enginehub", "com.plotsquared.squirrelid")
relocate("org.khelekore.prtree", "com.plotsquared.prtree")
relocate("com.google.inject", "com.plotsquared.google")
relocate("org.aopalliance", "com.plotsquared.core.aopalliance")
relocate("cloud.commandframework.services", "com.plotsquared.core.services")
relocate("io.leangen.geantyref", "com.plotsquared.core.geantyref")
relocate("com.intellectualsites.arkitektonika", "com.plotsquared.core.arkitektonika")
relocate("com.intellectualsites.http", "com.plotsquared.core.http")
relocate("com.intellectualsites.paster", "com.plotsquared.core.paster")
relocate("org.incendo.serverlib", "com.plotsquared.bukkit.serverlib")
relocate("org.jetbrains", "com.plotsquared.core.annotations")
relocate("org.intellij.lang", "com.plotsquared.core.intellij.annotations")
relocate("javax.annotation", "com.plotsquared.core.annotation")
relocate("com.github.spotbugs", "com.plotsquared.core.spotbugs")
relocate("javax.inject", "com.plotsquared.core.annotation.inject")
relocate("net.jcip", "com.plotsquared.core.annotations.jcip")
relocate("edu.umd.cs.findbugs", "com.plotsquared.core.annotations.findbugs")
relocate("com.intellectualsites.informative-annotations", "com.plotsquared.core.annotation.informative")
// Get rid of all the libs which are 100% unused.
minimize()
mergeServiceFiles()
}
tasks {
withType<Javadoc> {
val isRelease = if (rootProject.version.toString().endsWith("-SNAPSHOT")) "TODO" else rootProject.version.toString()
val opt = options as StandardJavadocDocletOptions
opt.links("https://jd.papermc.io/paper/1.18/")
opt.links("https://docs.enginehub.org/javadoc/com.sk89q.worldedit/worldedit-bukkit/" + libs.worldeditBukkit.get().versionConstraint.toString())
opt.links("https://intellectualsites.github.io/plotsquared-javadocs/core/")
opt.links("https://jd.adventure.kyori.net/api/4.9.3/")
opt.links("https://google.github.io/guice/api-docs/" + libs.guice.get().versionConstraint.toString() + "/javadoc/")
opt.links("https://checkerframework.org/api/")
opt.isLinkSource = true
opt.bottom(File("$rootDir/javadocfooter.html").readText())
opt.isUse = true
opt.encoding("UTF-8")
opt.keyWords()
opt.addStringOption("-since", isRelease)
}
}

View File

@ -1,86 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.core.command.MainCommand;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.player.ConsolePlayer;
import com.plotsquared.core.player.PlotPlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.command.ProxiedCommandSender;
import org.bukkit.command.RemoteConsoleCommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
public class BukkitCommand implements CommandExecutor, TabCompleter {
@Override
public boolean onCommand(
CommandSender commandSender, Command command, String commandLabel,
String[] args
) {
if (commandSender instanceof Player) {
return MainCommand.onCommand(BukkitUtil.adapt((Player) commandSender), args);
}
if (commandSender instanceof ConsoleCommandSender
|| commandSender instanceof ProxiedCommandSender
|| commandSender instanceof RemoteConsoleCommandSender) {
return MainCommand.onCommand(ConsolePlayer.getConsole(), args);
}
return false;
}
@Override
public List<String> onTabComplete(
CommandSender commandSender, Command command, String label,
String[] args
) {
if (!(commandSender instanceof Player)) {
return null;
}
PlotPlayer<?> player = BukkitUtil.adapt((Player) commandSender);
if (args.length == 0) {
return Collections.singletonList("plots");
}
if (!Settings.Enabled_Components.TAB_COMPLETED_ALIASES.contains(label.toLowerCase(Locale.ENGLISH))) {
return List.of();
}
Collection<com.plotsquared.core.command.Command> objects =
MainCommand.getInstance().tab(player, args, label.endsWith(" "));
if (objects == null) {
return null;
}
List<String> result = new ArrayList<>();
for (com.plotsquared.core.command.Command o : objects) {
result.add(o.toString());
}
return result;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,27 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.entity;
class AgeableStats {
int age;
boolean locked;
boolean adult;
}

View File

@ -1,34 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.entity;
class ArmorStandStats {
final float[] head = new float[3];
final float[] body = new float[3];
final float[] leftLeg = new float[3];
final float[] rightLeg = new float[3];
final float[] leftArm = new float[3];
final float[] rightArm = new float[3];
boolean arms;
boolean noPlate;
boolean invisible;
boolean small;
}

View File

@ -1,31 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.entity;
class EntityBaseStats {
EntityWrapper passenger;
float fall;
short fire;
int age;
double vZ;
double vY;
double vX;
}

View File

@ -1,87 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.entity;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.checkerframework.checker.nullness.qual.NonNull;
public abstract class EntityWrapper {
protected final float yaw;
protected final float pitch;
private final Entity entity;
private final EntityType type;
public double x;
public double y;
public double z;
EntityWrapper(final @NonNull Entity entity) {
this.entity = entity;
this.type = entity.getType();
final Location location = entity.getLocation();
this.x = location.getX();
this.y = location.getY();
this.z = location.getZ();
this.yaw = location.getYaw();
this.pitch = location.getPitch();
}
@SuppressWarnings("deprecation")
@Override
public String toString() {
return String.format("[%s, x=%s, y=%s, z=%s]", type.getName(), x, y, z);
}
public abstract Entity spawn(World world, int xOffset, int zOffset);
public abstract void saveEntity();
public float getYaw() {
return this.yaw;
}
public float getPitch() {
return this.pitch;
}
public Entity getEntity() {
return this.entity;
}
public EntityType getType() {
return this.type;
}
public double getX() {
return this.x;
}
public double getY() {
return this.y;
}
public double getZ() {
return this.z;
}
}

View File

@ -1,31 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.entity;
import org.bukkit.entity.Horse;
class HorseStats {
double jump;
boolean chest;
Horse.Variant variant;
Horse.Color color;
Horse.Style style;
}

View File

@ -1,47 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.entity;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import java.util.Collection;
class LivingEntityStats {
boolean loot;
String name;
boolean visible;
float health;
short air;
boolean persistent;
boolean leashed;
short leashX;
short leashY;
short leashZ;
boolean equipped;
ItemStack mainHand;
ItemStack helmet;
ItemStack boots;
ItemStack leggings;
ItemStack chestplate;
Collection<PotionEffect> potions;
ItemStack offHand;
}

View File

@ -1,763 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.entity;
import com.plotsquared.core.configuration.Settings;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bukkit.Art;
import org.bukkit.DyeColor;
import org.bukkit.Location;
import org.bukkit.Rotation;
import org.bukkit.TreeSpecies;
import org.bukkit.World;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.AbstractHorse;
import org.bukkit.entity.Ageable;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Bat;
import org.bukkit.entity.Boat;
import org.bukkit.entity.ChestedHorse;
import org.bukkit.entity.EnderDragon;
import org.bukkit.entity.Entity;
import org.bukkit.entity.IronGolem;
import org.bukkit.entity.Item;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Painting;
import org.bukkit.entity.Rabbit;
import org.bukkit.entity.Sheep;
import org.bukkit.entity.Slime;
import org.bukkit.entity.Tameable;
import org.bukkit.inventory.EntityEquipment;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.EulerAngle;
import org.bukkit.util.Vector;
import java.util.List;
public final class ReplicatingEntityWrapper extends EntityWrapper {
private static final Logger LOGGER = LogManager.getLogger("PlotSquared/" + ReplicatingEntityWrapper.class.getSimpleName());
private final short depth;
private final int hash;
private final EntityBaseStats base = new EntityBaseStats();
private ItemStack[] inventory;
// Extended
private ItemStack stack;
private byte dataByte;
private byte dataByte2;
private String dataString;
private LivingEntityStats lived;
private AgeableStats aged;
private TameableStats tamed;
private ArmorStandStats stand;
private HorseStats horse;
private boolean noGravity;
public ReplicatingEntityWrapper(Entity entity, short depth) {
super(entity);
this.hash = entity.getEntityId();
this.depth = depth;
if (depth == 0) {
return;
}
List<Entity> passengers = entity.getPassengers();
if (passengers.size() > 0) {
this.base.passenger = new ReplicatingEntityWrapper(passengers.get(0), depth);
}
this.base.fall = entity.getFallDistance();
this.base.fire = (short) entity.getFireTicks();
this.base.age = entity.getTicksLived();
Vector velocity = entity.getVelocity();
this.base.vX = velocity.getX();
this.base.vY = velocity.getY();
this.base.vZ = velocity.getZ();
if (depth == 1) {
return;
}
if (!entity.hasGravity()) {
this.noGravity = true;
}
switch (entity.getType().toString()) {
case "BOAT":
Boat boat = (Boat) entity;
this.dataByte = getOrdinal(TreeSpecies.values(), boat.getWoodType());
return;
case "ARROW":
case "EGG":
case "ENDER_CRYSTAL":
case "ENDER_PEARL":
case "ENDER_SIGNAL":
case "EXPERIENCE_ORB":
case "FALLING_BLOCK":
case "FIREBALL":
case "FIREWORK":
case "FISHING_HOOK":
case "LEASH_HITCH":
case "LIGHTNING":
case "MINECART":
case "MINECART_COMMAND":
case "MINECART_MOB_SPAWNER":
case "MINECART_TNT":
case "PLAYER":
case "PRIMED_TNT":
case "SLIME":
case "SMALL_FIREBALL":
case "SNOWBALL":
case "MINECART_FURNACE":
case "SPLASH_POTION":
case "THROWN_EXP_BOTTLE":
case "WITHER_SKULL":
case "UNKNOWN":
case "SPECTRAL_ARROW":
case "SHULKER_BULLET":
case "DRAGON_FIREBALL":
case "AREA_EFFECT_CLOUD":
case "TRIDENT":
case "LLAMA_SPIT":
// Do this stuff later
return;
// MISC //
case "DROPPED_ITEM":
Item item = (Item) entity;
this.stack = item.getItemStack();
return;
case "ITEM_FRAME":
this.x = Math.floor(this.getX());
this.y = Math.floor(this.getY());
this.z = Math.floor(this.getZ());
ItemFrame itemFrame = (ItemFrame) entity;
this.dataByte = getOrdinal(Rotation.values(), itemFrame.getRotation());
this.stack = itemFrame.getItem().clone();
return;
case "PAINTING":
this.x = Math.floor(this.getX());
this.y = Math.floor(this.getY());
this.z = Math.floor(this.getZ());
Painting painting = (Painting) entity;
Art art = painting.getArt();
this.dataByte = getOrdinal(BlockFace.values(), painting.getFacing());
int h = art.getBlockHeight();
if (h % 2 == 0) {
this.y -= 1;
}
this.dataString = art.name();
return;
// END MISC //
// INVENTORY HOLDER //
case "MINECART_CHEST":
case "MINECART_HOPPER":
storeInventory((InventoryHolder) entity);
return;
// START LIVING ENTITY //
// START AGEABLE //
// START TAMEABLE //
case "HORSE":
case "DONKEY":
case "LLAMA":
case "MULE":
case "SKELETON_HORSE":
AbstractHorse horse = (AbstractHorse) entity;
this.horse = new HorseStats();
this.horse.jump = horse.getJumpStrength();
if (horse instanceof ChestedHorse horse1) {
this.horse.chest = horse1.isCarryingChest();
}
//todo these horse features need fixing
//this.horse.variant = horse.getVariant();
//this.horse.style = horse.getStyle();
//this.horse.color = horse.getColor();
storeTameable(horse);
storeAgeable(horse);
storeLiving(horse);
storeInventory(horse);
return;
// END INVENTORY HOLDER //
case "WOLF":
case "OCELOT":
storeTameable((Tameable) entity);
storeAgeable((Ageable) entity);
storeLiving((LivingEntity) entity);
return;
// END TAMEABLE //
//todo fix sheep
case "SHEEP":
Sheep sheep = (Sheep) entity;
if (sheep.isSheared()) {
this.dataByte = (byte) 1;
} else {
this.dataByte = (byte) 0;
}
this.dataByte2 = sheep.getColor().getDyeData();
storeAgeable(sheep);
storeLiving(sheep);
return;
case "VILLAGER":
case "CHICKEN":
case "COW":
case "MUSHROOM_COW":
case "PIG":
case "TURTLE":
case "POLAR_BEAR":
storeAgeable((Ageable) entity);
storeLiving((LivingEntity) entity);
return;
case "RABBIT":
this.dataByte = getOrdinal(Rabbit.Type.values(), ((Rabbit) entity).getRabbitType());
storeAgeable((Ageable) entity);
storeLiving((LivingEntity) entity);
return;
// END AGEABLE //
case "ARMOR_STAND":
ArmorStand stand = (ArmorStand) entity;
this.inventory =
new ItemStack[]{stand.getItemInHand().clone(), stand.getHelmet().clone(),
stand.getChestplate().clone(), stand.getLeggings().clone(),
stand.getBoots().clone()};
storeLiving(stand);
this.stand = new ArmorStandStats();
EulerAngle head = stand.getHeadPose();
this.stand.head[0] = (float) head.getX();
this.stand.head[1] = (float) head.getY();
this.stand.head[2] = (float) head.getZ();
EulerAngle body = stand.getBodyPose();
this.stand.body[0] = (float) body.getX();
this.stand.body[1] = (float) body.getY();
this.stand.body[2] = (float) body.getZ();
EulerAngle leftLeg = stand.getLeftLegPose();
this.stand.leftLeg[0] = (float) leftLeg.getX();
this.stand.leftLeg[1] = (float) leftLeg.getY();
this.stand.leftLeg[2] = (float) leftLeg.getZ();
EulerAngle rightLeg = stand.getRightLegPose();
this.stand.rightLeg[0] = (float) rightLeg.getX();
this.stand.rightLeg[1] = (float) rightLeg.getY();
this.stand.rightLeg[2] = (float) rightLeg.getZ();
EulerAngle leftArm = stand.getLeftArmPose();
this.stand.leftArm[0] = (float) leftArm.getX();
this.stand.leftArm[1] = (float) leftArm.getY();
this.stand.leftArm[2] = (float) leftArm.getZ();
EulerAngle rightArm = stand.getRightArmPose();
this.stand.rightArm[0] = (float) rightArm.getX();
this.stand.rightArm[1] = (float) rightArm.getY();
this.stand.rightArm[2] = (float) rightArm.getZ();
if (stand.hasArms()) {
this.stand.arms = true;
}
if (!stand.hasBasePlate()) {
this.stand.noPlate = true;
}
if (!stand.isVisible()) {
this.stand.invisible = true;
}
if (stand.isSmall()) {
this.stand.small = true;
}
return;
case "ENDERMITE":
return;
case "BAT":
if (((Bat) entity).isAwake()) {
this.dataByte = (byte) 1;
} else {
this.dataByte = (byte) 0;
}
return;
case "ENDER_DRAGON":
EnderDragon entity1 = (EnderDragon) entity;
this.dataByte = (byte) entity1.getPhase().ordinal();
return;
case "SKELETON":
case "WITHER_SKELETON":
case "GUARDIAN":
case "ELDER_GUARDIAN":
case "GHAST":
case "MAGMA_CUBE":
case "SQUID":
case "PIG_ZOMBIE":
case "HOGLIN":
case "ZOMBIFIED_PIGLIN":
case "PIGLIN":
case "PIGLIN_BRUTE":
case "ZOMBIE":
case "WITHER":
case "WITCH":
case "SPIDER":
case "CAVE_SPIDER":
case "SILVERFISH":
case "GIANT":
case "ENDERMAN":
case "CREEPER":
case "BLAZE":
case "SHULKER":
case "SNOWMAN":
storeLiving((LivingEntity) entity);
return;
case "IRON_GOLEM":
if (((IronGolem) entity).isPlayerCreated()) {
this.dataByte = (byte) 1;
} else {
this.dataByte = (byte) 0;
}
storeLiving((LivingEntity) entity);
// END LIVING //
}
}
@Override
public boolean equals(Object obj) {
return this.hash == obj.hashCode();
}
@Override
public int hashCode() {
return this.hash;
}
public void storeInventory(InventoryHolder held) {
this.inventory = held.getInventory().getContents().clone();
}
void restoreLiving(LivingEntity entity) {
entity.setCanPickupItems(this.lived.loot);
if (this.lived.name != null) {
entity.setCustomName(this.lived.name);
entity.setCustomNameVisible(this.lived.visible);
}
if (this.lived.potions != null && !this.lived.potions.isEmpty()) {
entity.addPotionEffects(this.lived.potions);
}
entity.setRemainingAir(this.lived.air);
entity.setRemoveWhenFarAway(this.lived.persistent);
if (this.lived.equipped) {
this.restoreEquipment(entity);
}
if (this.lived.leashed) {
// TODO leashes
// World world = entity.getWorld();
// Entity leash = world.spawnEntity(new Location(world, Math.floor(x) +
// lived.leashX, Math.floor(y) + lived.leashY, Math.floor(z) + lived.leashZ),
// EntityType.LEASH_HITCH);
// entity.setLeashHolder(leash);
}
}
void restoreEquipment(LivingEntity entity) {
EntityEquipment equipment = entity.getEquipment();
if (equipment != null) {
equipment.setItemInMainHand(this.lived.mainHand);
equipment.setItemInOffHand(this.lived.offHand);
equipment.setHelmet(this.lived.helmet);
equipment.setChestplate(this.lived.chestplate);
equipment.setLeggings(this.lived.leggings);
equipment.setBoots(this.lived.boots);
}
}
private void restoreInventory(InventoryHolder entity) {
try {
entity.getInventory().setContents(this.inventory);
} catch (IllegalArgumentException e) {
LOGGER.error("Failed to restore inventory", e);
}
}
private void storeLiving(LivingEntity lived) {
this.lived = new LivingEntityStats();
this.lived.potions = lived.getActivePotionEffects();
this.lived.loot = lived.getCanPickupItems();
this.lived.name = lived.getCustomName();
this.lived.visible = lived.isCustomNameVisible();
this.lived.health = (float) lived.getHealth();
this.lived.air = (short) lived.getRemainingAir();
this.lived.persistent = lived.getRemoveWhenFarAway();
this.lived.leashed = lived.isLeashed();
if (this.lived.leashed) {
Location location = lived.getLeashHolder().getLocation();
this.lived.leashX = (short) (this.getX() - location.getBlockX());
this.lived.leashY = (short) (this.getY() - location.getBlockY());
this.lived.leashZ = (short) (this.getZ() - location.getBlockZ());
}
EntityEquipment equipment = lived.getEquipment();
this.lived.equipped = equipment != null;
if (this.lived.equipped) {
storeEquipment(equipment);
}
}
void storeEquipment(EntityEquipment equipment) {
this.lived.mainHand = equipment.getItemInMainHand().clone();
this.lived.offHand = equipment.getItemInOffHand().clone();
this.lived.boots = equipment.getBoots().clone();
this.lived.leggings = equipment.getLeggings().clone();
this.lived.chestplate = equipment.getChestplate().clone();
this.lived.helmet = equipment.getHelmet().clone();
}
private void restoreTameable(Tameable entity) {
if (this.tamed.tamed) {
if (this.tamed.owner != null) {
entity.setTamed(true);
entity.setOwner(this.tamed.owner);
}
}
}
private void restoreAgeable(Ageable entity) {
if (!this.aged.adult) {
entity.setBaby();
}
entity.setAgeLock(this.aged.locked);
if (this.aged.age > 0) {
entity.setAge(this.aged.age);
}
}
public void storeAgeable(Ageable aged) {
this.aged = new AgeableStats();
this.aged.age = aged.getAge();
this.aged.locked = aged.getAgeLock();
this.aged.adult = aged.isAdult();
}
public void storeTameable(Tameable tamed) {
this.tamed = new TameableStats();
this.tamed.owner = tamed.getOwner();
this.tamed.tamed = tamed.isTamed();
}
@SuppressWarnings("deprecation") // Paper deprecation
@Override
public Entity spawn(World world, int xOffset, int zOffset) {
Location location = new Location(world, this.getX() + xOffset, this.getY(), this.z + zOffset);
location.setYaw(this.yaw);
location.setPitch(this.pitch);
if (!this.getType().isSpawnable()) {
return null;
}
Entity entity;
switch (this.getType().toString()) {
case "DROPPED_ITEM":
return world.dropItem(location, this.stack);
case "PLAYER":
case "LEASH_HITCH":
return null;
case "ITEM_FRAME":
entity = world.spawn(location, ItemFrame.class);
break;
case "PAINTING":
entity = world.spawn(location, Painting.class);
break;
default:
entity = world.spawnEntity(location, this.getType());
break;
}
if (this.depth == 0) {
return entity;
}
if (this.base.passenger != null) {
try {
entity.addPassenger(this.base.passenger.spawn(world, xOffset, zOffset));
} catch (Exception ignored) {
}
}
if (this.base.fall != 0) {
entity.setFallDistance(this.base.fall);
}
if (this.base.fire != 0) {
entity.setFireTicks(this.base.fire);
}
if (this.base.age != 0) {
entity.setTicksLived(this.base.age);
}
entity.setVelocity(new Vector(this.base.vX, this.base.vY, this.base.vZ));
if (this.depth == 1) {
return entity;
}
if (this.noGravity) {
entity.setGravity(false);
}
switch (entity.getType().toString()) {
case "BOAT":
Boat boat = (Boat) entity;
boat.setWoodType(TreeSpecies.values()[dataByte]);
return entity;
case "SLIME":
((Slime) entity).setSize(this.dataByte);
return entity;
case "ARROW":
case "EGG":
case "ENDER_CRYSTAL":
case "ENDER_PEARL":
case "ENDER_SIGNAL":
case "DROPPED_ITEM":
case "EXPERIENCE_ORB":
case "FALLING_BLOCK":
case "FIREBALL":
case "FIREWORK":
case "FISHING_HOOK":
case "LEASH_HITCH":
case "LIGHTNING":
case "MINECART":
case "MINECART_COMMAND":
case "MINECART_MOB_SPAWNER":
case "MINECART_TNT":
case "PLAYER":
case "PRIMED_TNT":
case "SMALL_FIREBALL":
case "SNOWBALL":
case "SPLASH_POTION":
case "THROWN_EXP_BOTTLE":
case "SPECTRAL_ARROW":
case "SHULKER_BULLET":
case "AREA_EFFECT_CLOUD":
case "DRAGON_FIREBALL":
case "WITHER_SKULL":
case "MINECART_FURNACE":
case "LLAMA_SPIT":
case "TRIDENT":
case "UNKNOWN":
// Do this stuff later
return entity;
// MISC //
case "ITEM_FRAME":
ItemFrame itemframe = (ItemFrame) entity;
itemframe.setRotation(Rotation.values()[this.dataByte]);
itemframe.setItem(this.stack);
return entity;
case "PAINTING":
Painting painting = (Painting) entity;
painting.setFacingDirection(BlockFace.values()[this.dataByte], true);
painting.setArt(Art.getByName(this.dataString), true);
return entity;
// END MISC //
// INVENTORY HOLDER //
case "MINECART_CHEST":
case "MINECART_HOPPER":
restoreInventory((InventoryHolder) entity);
return entity;
// START LIVING ENTITY //
// START AGEABLE //
// START TAMEABLE //
case "HORSE":
case "LLAMA":
case "SKELETON_HORSE":
case "DONKEY":
case "MULE":
AbstractHorse horse = (AbstractHorse) entity;
horse.setJumpStrength(this.horse.jump);
if (horse instanceof ChestedHorse) {
((ChestedHorse) horse).setCarryingChest(this.horse.chest);
}
//todo broken as of 1.13
//horse.setVariant(this.horse.variant);
//horse.setStyle(this.horse.style);
//horse.setColor(this.horse.color);
restoreTameable(horse);
restoreAgeable(horse);
restoreLiving(horse);
restoreInventory(horse);
return entity;
// END INVENTORY HOLDER //
case "WOLF":
case "OCELOT":
restoreTameable((Tameable) entity);
restoreAgeable((Ageable) entity);
restoreLiving((LivingEntity) entity);
return entity;
// END AGEABLE //
case "SHEEP":
Sheep sheep = (Sheep) entity;
if (this.dataByte == 1) {
sheep.setSheared(true);
}
if (this.dataByte2 != 0) {
sheep.setColor(DyeColor.getByDyeData(this.dataByte2));
}
restoreAgeable(sheep);
restoreLiving(sheep);
return sheep;
case "VILLAGER":
case "CHICKEN":
case "COW":
case "TURTLE":
case "POLAR_BEAR":
case "MUSHROOM_COW":
case "PIG":
restoreAgeable((Ageable) entity);
restoreLiving((LivingEntity) entity);
return entity;
// END AGEABLE //
case "RABBIT":
if (this.dataByte != 0) {
((Rabbit) entity).setRabbitType(Rabbit.Type.values()[this.dataByte]);
}
restoreAgeable((Ageable) entity);
restoreLiving((LivingEntity) entity);
return entity;
case "ARMOR_STAND":
// CHECK positions
ArmorStand stand = (ArmorStand) entity;
if (this.inventory[0] != null) {
stand.setItemInHand(this.inventory[0]);
}
if (this.inventory[1] != null) {
stand.setHelmet(this.inventory[1]);
}
if (this.inventory[2] != null) {
stand.setChestplate(this.inventory[2]);
}
if (this.inventory[3] != null) {
stand.setLeggings(this.inventory[3]);
}
if (this.inventory[4] != null) {
stand.setBoots(this.inventory[4]);
}
if (this.stand.head[0] != 0 || this.stand.head[1] != 0 || this.stand.head[2] != 0) {
EulerAngle pose =
new EulerAngle(this.stand.head[0], this.stand.head[1], this.stand.head[2]);
stand.setHeadPose(pose);
}
if (this.stand.body[0] != 0 || this.stand.body[1] != 0 || this.stand.body[2] != 0) {
EulerAngle pose =
new EulerAngle(this.stand.body[0], this.stand.body[1], this.stand.body[2]);
stand.setBodyPose(pose);
}
if (this.stand.leftLeg[0] != 0 || this.stand.leftLeg[1] != 0
|| this.stand.leftLeg[2] != 0) {
EulerAngle pose = new EulerAngle(this.stand.leftLeg[0], this.stand.leftLeg[1],
this.stand.leftLeg[2]
);
stand.setLeftLegPose(pose);
}
if (this.stand.rightLeg[0] != 0 || this.stand.rightLeg[1] != 0
|| this.stand.rightLeg[2] != 0) {
EulerAngle pose = new EulerAngle(this.stand.rightLeg[0], this.stand.rightLeg[1],
this.stand.rightLeg[2]
);
stand.setRightLegPose(pose);
}
if (this.stand.leftArm[0] != 0 || this.stand.leftArm[1] != 0
|| this.stand.leftArm[2] != 0) {
EulerAngle pose = new EulerAngle(this.stand.leftArm[0], this.stand.leftArm[1],
this.stand.leftArm[2]
);
stand.setLeftArmPose(pose);
}
if (this.stand.rightArm[0] != 0 || this.stand.rightArm[1] != 0
|| this.stand.rightArm[2] != 0) {
EulerAngle pose = new EulerAngle(this.stand.rightArm[0], this.stand.rightArm[1],
this.stand.rightArm[2]
);
stand.setRightArmPose(pose);
}
if (this.stand.invisible) {
stand.setVisible(false);
}
if (this.stand.arms) {
stand.setArms(true);
}
if (this.stand.noPlate) {
stand.setBasePlate(false);
}
if (this.stand.small) {
stand.setSmall(true);
}
restoreLiving(stand);
return stand;
case "BAT":
if (this.dataByte != 0) {
((Bat) entity).setAwake(true);
}
restoreLiving((LivingEntity) entity);
return entity;
case "ENDER_DRAGON":
if (this.dataByte != 0) {
((EnderDragon) entity).setPhase(EnderDragon.Phase.values()[this.dataByte]);
}
restoreLiving((LivingEntity) entity);
return entity;
case "ENDERMITE":
case "GHAST":
case "MAGMA_CUBE":
case "SQUID":
case "PIG_ZOMBIE":
case "HOGLIN":
case "PIGLIN":
case "ZOMBIFIED_PIGLIN":
case "PIGLIN_BRUTE":
case "ZOMBIE":
case "WITHER":
case "WITCH":
case "SPIDER":
case "CAVE_SPIDER":
case "SILVERFISH":
case "GIANT":
case "ENDERMAN":
case "CREEPER":
case "BLAZE":
case "SNOWMAN":
case "SHULKER":
case "GUARDIAN":
case "ELDER_GUARDIAN":
case "SKELETON":
case "WITHER_SKELETON":
restoreLiving((LivingEntity) entity);
return entity;
case "IRON_GOLEM":
if (this.dataByte != 0) {
((IronGolem) entity).setPlayerCreated(true);
}
restoreLiving((LivingEntity) entity);
return entity;
default:
if (Settings.DEBUG) {
LOGGER.info("Could not identify entity: {}", entity.getType());
}
return entity;
// END LIVING
}
}
public void saveEntity() {
}
private byte getOrdinal(Object[] list, Object value) {
for (byte i = 0; i < list.length; i++) {
if (list[i].equals(value)) {
return i;
}
}
return 0;
}
}

View File

@ -1,28 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.entity;
import org.bukkit.entity.AnimalTamer;
class TameableStats {
AnimalTamer owner;
boolean tamed;
}

View File

@ -1,116 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.entity;
import com.plotsquared.bukkit.BukkitPlatform;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.metadata.FixedMetadataValue;
public class TeleportEntityWrapper extends EntityWrapper {
private Location oldLocation;
private boolean gravityOld;
private boolean invulnerableOld;
private int fireTicksOld;
private int livingTicksOld;
public TeleportEntityWrapper(final Entity entity) {
super(entity);
}
@Override
public Entity spawn(final World world, final int xOffset, final int zOffset) {
if (!getEntity().getLocation().getChunk().equals(oldLocation.getChunk())) {
final Location oldLocation = this.oldLocation.clone();
oldLocation.add(xOffset, 0, xOffset);
getEntity().teleport(oldLocation);
getEntity().setGravity(gravityOld);
getEntity().setInvulnerable(invulnerableOld);
getEntity().setFireTicks(fireTicksOld);
getEntity().setTicksLived(livingTicksOld);
getEntity().removeMetadata("ps-tmp-teleport", BukkitPlatform.getPlugin(BukkitPlatform.class));
}
return getEntity();
}
@Override
public void saveEntity() {
if (getEntity().hasMetadata("ps-tmp-teleport")) {
this.oldLocation = (Location) this.getEntity().getMetadata("ps-tmp-teleport").get(0);
} else {
this.oldLocation = this.getEntity().getLocation();
}
// To account for offsets in the chunk manager
this.oldLocation = oldLocation.clone();
this.oldLocation.setX(this.getX());
this.oldLocation.setY(this.getY());
this.oldLocation.setZ(this.getZ());
this.gravityOld = this.getEntity().hasGravity();
this.getEntity().setGravity(false);
this.invulnerableOld = this.getEntity().isInvulnerable();
this.getEntity().setInvulnerable(true);
this.fireTicksOld = this.getEntity().getFireTicks();
this.livingTicksOld = this.getEntity().getTicksLived();
this.getEntity().setMetadata(
"ps-tmp-teleport",
new FixedMetadataValue(BukkitPlatform.getPlugin(BukkitPlatform.class), oldLocation)
);
final Chunk newChunk = getNewChunk();
this.getEntity().teleport(
new Location(newChunk.getWorld(), newChunk.getX() << 4, 5000, newChunk.getZ() << 4));
}
private Chunk getNewChunk() {
final Chunk oldChunk = oldLocation.getChunk();
Chunk chunk = null;
for (Chunk lChunk : oldChunk.getWorld().getLoadedChunks()) {
if (!lChunk.equals(oldChunk) && lChunk.isLoaded()) {
chunk = lChunk;
break;
}
}
if (chunk == null) {
for (int dx = 1; dx < Integer.MAX_VALUE; dx++) {
for (int dz = 0; dz < Integer.MAX_VALUE; dz++) {
if ((chunk = getChunkRelative(oldChunk, dx, dz)).isLoaded()) {
break;
} else if ((chunk = getChunkRelative(oldChunk, -dx, dz)).isLoaded()) {
break;
} else if ((chunk = getChunkRelative(oldChunk, dx, -dz)).isLoaded()) {
break;
} else if ((chunk = getChunkRelative(oldChunk, -dx, -dz)).isLoaded()) {
break;
}
}
}
}
return chunk;
}
private Chunk getChunkRelative(final Chunk chunk, final int dx, final int dz) {
return chunk.getWorld().getChunkAt(chunk.getX() + dx, chunk.getZ() + dz);
}
}

View File

@ -1,87 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.generator;
import com.plotsquared.bukkit.queue.LimitedRegionWrapperQueue;
import com.plotsquared.core.generator.HybridPlotWorld;
import com.plotsquared.core.generator.IndependentPlotGenerator;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.location.UncheckedWorldLocation;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.plot.world.SinglePlotArea;
import com.plotsquared.core.queue.ScopedQueueCoordinator;
import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.LimitedRegion;
import org.bukkit.generator.WorldInfo;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.Random;
final class BlockStatePopulator extends BlockPopulator {
private final IndependentPlotGenerator plotGenerator;
/**
* @since 6.9.0
*/
public BlockStatePopulator(
final @NonNull IndependentPlotGenerator plotGenerator
) {
this.plotGenerator = plotGenerator;
}
/**
* @deprecated Use {@link BlockStatePopulator#BlockStatePopulator(IndependentPlotGenerator)} as plotAreManager is unused
*/
@Deprecated(forRemoval = true, since = "6.9.0")
public BlockStatePopulator(
final @NonNull IndependentPlotGenerator plotGenerator,
final @NonNull PlotAreaManager plotAreaManager
) {
this.plotGenerator = plotGenerator;
}
@Override
public void populate(
@NonNull final WorldInfo worldInfo,
@NonNull final Random random,
final int chunkX,
final int chunkZ,
@NonNull final LimitedRegion limitedRegion
) {
PlotArea area = UncheckedWorldLocation.at(worldInfo.getName(), chunkX << 4, 0, chunkZ << 4).getPlotArea();
if (area == null || (area instanceof HybridPlotWorld hpw && !hpw.populationNeeded()) || area instanceof SinglePlotArea) {
return;
}
LimitedRegionWrapperQueue wrapped = new LimitedRegionWrapperQueue(limitedRegion);
// It is possible for the region to be larger than the chunk, but there is no reason for P2 to need to populate
// outside of the actual chunk area.
Location min = UncheckedWorldLocation.at(worldInfo.getName(), chunkX << 4, worldInfo.getMinHeight(), chunkZ << 4);
Location max = UncheckedWorldLocation.at(
worldInfo.getName(),
(chunkX << 4) + 15,
worldInfo.getMaxHeight(),
(chunkZ << 4) + 15
);
ScopedQueueCoordinator offsetChunkQueue = new ScopedQueueCoordinator(wrapped, min, max);
this.plotGenerator.populateChunk(offsetChunkQueue, area);
}
}

View File

@ -1,62 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.generator;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.generator.AugmentedUtils;
import com.plotsquared.core.queue.QueueCoordinator;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.util.SideEffectSet;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.generator.BlockPopulator;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.Random;
public class BukkitAugmentedGenerator extends BlockPopulator {
private static BukkitAugmentedGenerator generator;
public static BukkitAugmentedGenerator get(World world) {
for (BlockPopulator populator : world.getPopulators()) {
if (populator instanceof BukkitAugmentedGenerator) {
return (BukkitAugmentedGenerator) populator;
}
}
if (generator == null) {
generator = new BukkitAugmentedGenerator();
}
world.getPopulators().add(generator);
return generator;
}
@Override
public void populate(@NonNull World world, @NonNull Random random, @NonNull Chunk source) {
QueueCoordinator queue = PlotSquared.platform().globalBlockQueue().getNewQueue(BukkitAdapter.adapt(world));
// The chunk is already loaded and we do not want to load the chunk in "fully" by using any PaperLib methods.
queue.setForceSync(true);
queue.setSideEffectSet(SideEffectSet.none());
queue.setBiomesEnabled(false);
queue.setChunkObject(source);
AugmentedUtils.generateChunk(world.getName(), source.getX(), source.getZ(), queue);
queue.enqueue();
}
}

View File

@ -1,286 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.generator;
import com.plotsquared.bukkit.queue.GenChunk;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.bukkit.util.BukkitWorld;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.generator.GeneratorWrapper;
import com.plotsquared.core.generator.IndependentPlotGenerator;
import com.plotsquared.core.generator.SingleWorldGenerator;
import com.plotsquared.core.location.ChunkWrapper;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.queue.ScopedQueueCoordinator;
import com.plotsquared.core.util.ChunkManager;
import com.sk89q.worldedit.math.BlockVector2;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;
public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrapper<ChunkGenerator> {
@SuppressWarnings("unused")
public final boolean PAPER_ASYNC_SAFE = true;
private final PlotAreaManager plotAreaManager;
private final IndependentPlotGenerator plotGenerator;
private final ChunkGenerator platformGenerator;
private final boolean full;
private final String levelName;
private List<BlockPopulator> populators;
private boolean loaded = false;
public BukkitPlotGenerator(
final @NonNull String name,
final @NonNull IndependentPlotGenerator generator,
final @NonNull PlotAreaManager plotAreaManager
) {
this.plotAreaManager = plotAreaManager;
this.levelName = name;
this.plotGenerator = generator;
this.platformGenerator = this;
this.populators = new ArrayList<>();
int minecraftMinorVersion = PlotSquared.platform().serverVersion()[1];
if (minecraftMinorVersion >= 17) {
this.populators.add(new BlockStatePopulator(this.plotGenerator));
} else {
this.populators.add(new LegacyBlockStatePopulator(this.plotGenerator));
}
this.full = true;
}
public BukkitPlotGenerator(final String world, final ChunkGenerator cg, final @NonNull PlotAreaManager plotAreaManager) {
if (cg instanceof BukkitPlotGenerator) {
throw new IllegalArgumentException("ChunkGenerator: " + cg.getClass().getName()
+ " is already a BukkitPlotGenerator!");
}
this.plotAreaManager = plotAreaManager;
this.levelName = world;
this.full = false;
this.platformGenerator = cg;
this.plotGenerator = new DelegatePlotGenerator(cg, world);
}
@Override
public void augment(PlotArea area) {
BukkitAugmentedGenerator.get(BukkitUtil.getWorld(area.getWorldName()));
}
@Override
public boolean isFull() {
return this.full;
}
@Override
public IndependentPlotGenerator getPlotGenerator() {
return this.plotGenerator;
}
@Override
public ChunkGenerator getPlatformGenerator() {
return this.platformGenerator;
}
@Override
public @NonNull List<BlockPopulator> getDefaultPopulators(@NonNull World world) {
try {
checkLoaded(world);
} catch (Exception e) {
e.printStackTrace();
}
ArrayList<BlockPopulator> toAdd = new ArrayList<>();
List<BlockPopulator> existing = world.getPopulators();
if (populators == null && platformGenerator != null) {
populators = new ArrayList<>(platformGenerator.getDefaultPopulators(world));
}
if (populators != null) {
for (BlockPopulator populator : this.populators) {
if (!existing.contains(populator)) {
toAdd.add(populator);
}
}
}
return toAdd;
}
private synchronized void checkLoaded(@NonNull World world) {
// Do not attempt to load configurations until WorldEdit has a platform ready.
if (!PlotSquared.get().isWeInitialised()) {
return;
}
if (!this.loaded) {
String name = world.getName();
PlotSquared.get().loadWorld(name, this);
final Set<PlotArea> areas = this.plotAreaManager.getPlotAreasSet(name);
if (!areas.isEmpty()) {
PlotArea area = areas.iterator().next();
if (!area.isMobSpawning()) {
if (!area.isSpawnEggs()) {
world.setSpawnFlags(false, false);
}
setSpawnLimits(world, 0);
} else {
world.setSpawnFlags(true, true);
setSpawnLimits(world, -1);
}
}
this.loaded = true;
}
}
@SuppressWarnings("deprecation")
private void setSpawnLimits(@NonNull World world, int limit) {
world.setAmbientSpawnLimit(limit);
world.setAnimalSpawnLimit(limit);
world.setMonsterSpawnLimit(limit);
world.setWaterAnimalSpawnLimit(limit);
}
/**
* The entire method is deprecated, but kept for compatibility with versions lower than or equal to 1.16.2.
* The method will be removed in future versions, because WorldEdit and FastAsyncWorldEdit only support the latest point
* release.
*/
@Deprecated(forRemoval = true, since = "6.11.0")
@Override
public @NonNull ChunkData generateChunkData(
@NonNull World world, @NonNull Random random, int x, int z,
@NonNull BiomeGrid biome
) {
int minY = BukkitWorld.getMinWorldHeight(world);
int maxY = BukkitWorld.getMaxWorldHeight(world);
GenChunk result = new GenChunk(minY, maxY);
if (this.getPlotGenerator() instanceof SingleWorldGenerator) {
if (result.getChunkData() != null) {
for (int chunkX = 0; chunkX < 16; chunkX++) {
for (int chunkZ = 0; chunkZ < 16; chunkZ++) {
for (int y = minY; y < maxY; y++) {
biome.setBiome(chunkX, y, chunkZ, Biome.PLAINS);
}
}
}
return result.getChunkData();
}
}
// Set the chunk location
result.setChunk(new ChunkWrapper(world.getName(), x, z));
// Set the result data
result.setChunkData(createChunkData(world));
result.biomeGrid = biome;
result.result = null;
// Catch any exceptions (as exceptions usually thrown)
try {
// Fill the result data if necessary
if (this.platformGenerator != this) {
return this.platformGenerator.generateChunkData(world, random, x, z, biome);
} else {
generate(BlockVector2.at(x, z), world, result);
}
} catch (Throwable e) {
e.printStackTrace();
}
// Return the result data
return result.getChunkData();
}
private void generate(BlockVector2 loc, World world, ScopedQueueCoordinator result) {
// Load if improperly loaded
if (!this.loaded) {
checkLoaded(world);
}
// Process the chunk
if (ChunkManager.preProcessChunk(loc, result)) {
return;
}
PlotArea area = this.plotAreaManager.getPlotArea(world.getName(), null);
if (area == null && (area = this.plotAreaManager.getPlotArea(this.levelName, null)) == null) {
throw new IllegalStateException(
"Cannot regenerate chunk that does not belong to a plot area." + " Location: " + loc
+ ", world: " + world);
}
try {
this.plotGenerator.generateChunk(result, area);
} catch (Throwable e) {
// Recover from generator error
e.printStackTrace();
}
ChunkManager.postProcessChunk(loc, result);
}
@Override
public boolean canSpawn(final @NonNull World world, final int x, final int z) {
return true;
}
public boolean shouldGenerateCaves() {
return false;
}
public boolean shouldGenerateDecorations() {
return false;
}
public boolean isParallelCapable() {
return true;
}
public boolean shouldGenerateMobs() {
return false;
}
public boolean shouldGenerateStructures() {
return true;
}
@Override
public String toString() {
if (this.platformGenerator == this) {
return this.plotGenerator.getName();
}
if (this.platformGenerator == null) {
return "null";
} else {
return this.platformGenerator.getClass().getName();
}
}
@Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
return toString().equals(obj.toString()) || toString().equals(obj.getClass().getName());
}
public String getLevelName() {
return this.levelName;
}
}

View File

@ -1,102 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.generator;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.generator.IndependentPlotGenerator;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.PlotId;
import com.plotsquared.core.queue.ScopedQueueCoordinator;
import com.plotsquared.core.util.MathMan;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.Random;
final class DelegatePlotGenerator extends IndependentPlotGenerator {
private final ChunkGenerator chunkGenerator;
private final String world;
public DelegatePlotGenerator(ChunkGenerator chunkGenerator, String world) {
this.chunkGenerator = chunkGenerator;
this.world = world;
}
@Override
public void initialize(PlotArea area) {
}
@Override
public String getName() {
return this.chunkGenerator.getClass().getName();
}
@Override
public PlotArea getNewPlotArea(String world, String id, PlotId min, PlotId max) {
return PlotSquared.platform().defaultGenerator().getNewPlotArea(world, id, min, max);
}
@Override
public void generateChunk(final ScopedQueueCoordinator result, PlotArea settings) {
World world = BukkitUtil.getWorld(this.world);
Location min = result.getMin();
int chunkX = min.getX() >> 4;
int chunkZ = min.getZ() >> 4;
Random random = new Random(MathMan.pair((short) chunkX, (short) chunkZ));
try {
ChunkGenerator.BiomeGrid grid = new ChunkGenerator.BiomeGrid() {
@Override
public void setBiome(int x, int z, @NonNull Biome biome) {
result.setBiome(x, z, BukkitAdapter.adapt(biome));
}
//do not annotate with Override until we discontinue support for 1.4.4 (we no longer support 1.4.4)
@Override
public void setBiome(int x, int y, int z, @NonNull Biome biome) {
result.setBiome(x, z, BukkitAdapter.adapt(biome));
}
@Override
public @NonNull Biome getBiome(int x, int z) {
return Biome.FOREST;
}
@Override
public @NonNull Biome getBiome(int x, int y, int z) {
return Biome.FOREST;
}
};
chunkGenerator.generateChunkData(world, random, chunkX, chunkZ, grid);
return;
} catch (Throwable ignored) {
}
for (BlockPopulator populator : chunkGenerator.getDefaultPopulators(world)) {
populator.populate(world, random, world.getChunkAt(chunkX, chunkZ));
}
}
}

View File

@ -1,73 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.generator;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.generator.HybridPlotWorld;
import com.plotsquared.core.generator.IndependentPlotGenerator;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.location.UncheckedWorldLocation;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.world.SinglePlotArea;
import com.plotsquared.core.queue.QueueCoordinator;
import com.plotsquared.core.queue.ScopedQueueCoordinator;
import com.sk89q.worldedit.bukkit.BukkitWorld;
import com.sk89q.worldedit.util.SideEffectSet;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.generator.BlockPopulator;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.Random;
final class LegacyBlockStatePopulator extends BlockPopulator {
private final IndependentPlotGenerator plotGenerator;
/**
* @since 6.9.0
*/
public LegacyBlockStatePopulator(
final @NonNull IndependentPlotGenerator plotGenerator
) {
this.plotGenerator = plotGenerator;
}
@Override
public void populate(@NonNull final World world, @NonNull final Random random, @NonNull final Chunk source) {
int chunkMinX = source.getX() << 4;
int chunkMinZ = source.getZ() << 4;
PlotArea area = Location.at(world.getName(), chunkMinX, 0, chunkMinZ).getPlotArea();
if (area == null || (area instanceof HybridPlotWorld hpw && !hpw.populationNeeded()) || area instanceof SinglePlotArea) {
return;
}
QueueCoordinator queue = PlotSquared.platform().globalBlockQueue().getNewQueue(new BukkitWorld(world));
queue.setForceSync(true);
queue.setSideEffectSet(SideEffectSet.none());
queue.setBiomesEnabled(false);
queue.setChunkObject(source);
Location min = UncheckedWorldLocation.at(world.getName(), chunkMinX, world.getMinHeight(), chunkMinZ);
Location max = UncheckedWorldLocation.at(world.getName(), chunkMinX + 15, world.getMaxHeight(), chunkMinZ + 15);
ScopedQueueCoordinator offsetChunkQueue = new ScopedQueueCoordinator(queue, min, max);
this.plotGenerator.populateChunk(offsetChunkQueue, area);
queue.enqueue();
}
}

View File

@ -1,49 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.inject;
import com.google.inject.AbstractModule;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import com.plotsquared.core.backup.BackupManager;
import com.plotsquared.core.backup.BackupProfile;
import com.plotsquared.core.backup.NullBackupManager;
import com.plotsquared.core.backup.PlayerBackupProfile;
import com.plotsquared.core.backup.SimpleBackupManager;
import com.plotsquared.core.inject.factory.PlayerBackupProfileFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class BackupModule extends AbstractModule {
private static final Logger LOGGER = LogManager.getLogger("PlotSquared/" + BackupModule.class.getSimpleName());
@Override
protected void configure() {
try {
install(new FactoryModuleBuilder()
.implement(BackupProfile.class, PlayerBackupProfile.class).build(PlayerBackupProfileFactory.class));
bind(BackupManager.class).to(SimpleBackupManager.class);
} catch (final Exception e) {
LOGGER.error("Failed to initialize backup manager", e);
LOGGER.error("Backup features will be disabled");
bind(BackupManager.class).to(NullBackupManager.class);
}
}
}

View File

@ -1,148 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.inject;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import com.plotsquared.bukkit.BukkitPlatform;
import com.plotsquared.bukkit.listener.SingleWorldListener;
import com.plotsquared.bukkit.player.BukkitPlayerManager;
import com.plotsquared.bukkit.queue.BukkitChunkCoordinator;
import com.plotsquared.bukkit.queue.BukkitQueueCoordinator;
import com.plotsquared.bukkit.schematic.BukkitSchematicHandler;
import com.plotsquared.bukkit.util.BukkitChunkManager;
import com.plotsquared.bukkit.util.BukkitEconHandler;
import com.plotsquared.bukkit.util.BukkitInventoryUtil;
import com.plotsquared.bukkit.util.BukkitRegionManager;
import com.plotsquared.bukkit.util.BukkitSetupUtils;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.bukkit.util.fawe.FaweRegionManager;
import com.plotsquared.bukkit.util.fawe.FaweSchematicHandler;
import com.plotsquared.core.PlotPlatform;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.generator.HybridGen;
import com.plotsquared.core.generator.IndependentPlotGenerator;
import com.plotsquared.core.inject.annotations.ConsoleActor;
import com.plotsquared.core.inject.annotations.DefaultGenerator;
import com.plotsquared.core.inject.factory.ChunkCoordinatorBuilderFactory;
import com.plotsquared.core.inject.factory.ChunkCoordinatorFactory;
import com.plotsquared.core.inject.factory.HybridPlotWorldFactory;
import com.plotsquared.core.inject.factory.ProgressSubscriberFactory;
import com.plotsquared.core.plot.world.DefaultPlotAreaManager;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.plot.world.SinglePlotAreaManager;
import com.plotsquared.core.queue.ChunkCoordinator;
import com.plotsquared.core.queue.GlobalBlockQueue;
import com.plotsquared.core.queue.QueueProvider;
import com.plotsquared.core.queue.subscriber.DefaultProgressSubscriber;
import com.plotsquared.core.queue.subscriber.ProgressSubscriber;
import com.plotsquared.core.util.ChunkManager;
import com.plotsquared.core.util.EconHandler;
import com.plotsquared.core.util.InventoryUtil;
import com.plotsquared.core.util.PlayerManager;
import com.plotsquared.core.util.RegionManager;
import com.plotsquared.core.util.SchematicHandler;
import com.plotsquared.core.util.SetupUtils;
import com.plotsquared.core.util.WorldUtil;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.extension.platform.Actor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bukkit.Bukkit;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.plugin.java.JavaPlugin;
import org.checkerframework.checker.nullness.qual.NonNull;
public class BukkitModule extends AbstractModule {
private static final Logger LOGGER = LogManager.getLogger("PlotSquared/" + BukkitModule.class.getSimpleName());
private final BukkitPlatform bukkitPlatform;
public BukkitModule(final @NonNull BukkitPlatform bukkitPlatform) {
this.bukkitPlatform = bukkitPlatform;
}
@Override
protected void configure() {
bind(PlayerManager.class).to(BukkitPlayerManager.class);
bind(JavaPlugin.class).toInstance(bukkitPlatform);
bind(PlotPlatform.class).toInstance(bukkitPlatform);
bind(BukkitPlatform.class).toInstance(bukkitPlatform);
bind(IndependentPlotGenerator.class).annotatedWith(DefaultGenerator.class).to(HybridGen.class);
// Console actor
@NonNull ConsoleCommandSender console = Bukkit.getServer().getConsoleSender();
WorldEditPlugin wePlugin = ((WorldEditPlugin) Bukkit.getPluginManager().getPlugin("WorldEdit"));
bind(Actor.class).annotatedWith(ConsoleActor.class).toInstance(wePlugin.wrapCommandSender(console));
bind(InventoryUtil.class).to(BukkitInventoryUtil.class);
bind(SetupUtils.class).to(BukkitSetupUtils.class);
bind(WorldUtil.class).to(BukkitUtil.class);
install(new FactoryModuleBuilder()
.implement(ProgressSubscriber.class, DefaultProgressSubscriber.class)
.build(ProgressSubscriberFactory.class));
bind(ChunkManager.class).to(BukkitChunkManager.class);
if (PlotSquared.platform().isFaweHooking()) {
bind(SchematicHandler.class).to(FaweSchematicHandler.class);
bind(RegionManager.class).to(FaweRegionManager.class);
} else {
bind(SchematicHandler.class).to(BukkitSchematicHandler.class);
bind(RegionManager.class).to(BukkitRegionManager.class);
}
bind(GlobalBlockQueue.class).toInstance(new GlobalBlockQueue(QueueProvider.of(BukkitQueueCoordinator.class)));
if (Settings.Enabled_Components.WORLDS) {
bind(PlotAreaManager.class).to(SinglePlotAreaManager.class);
try {
bind(SingleWorldListener.class).toInstance(new SingleWorldListener());
} catch (Exception e) {
e.printStackTrace();
}
} else {
bind(PlotAreaManager.class).to(DefaultPlotAreaManager.class);
}
install(new FactoryModuleBuilder().build(HybridPlotWorldFactory.class));
install(new FactoryModuleBuilder()
.implement(ChunkCoordinator.class, BukkitChunkCoordinator.class)
.build(ChunkCoordinatorFactory.class));
install(new FactoryModuleBuilder().build(ChunkCoordinatorBuilderFactory.class));
}
@Provides
@Singleton
@NonNull EconHandler provideEconHandler() {
if (!Settings.Enabled_Components.ECONOMY) {
return EconHandler.nullEconHandler();
}
if (Bukkit.getPluginManager().isPluginEnabled("Vault")) {
try {
BukkitEconHandler econHandler = new BukkitEconHandler();
if (!econHandler.init()) {
LOGGER.warn("Economy is enabled but no plugin is providing an economy service. Falling back...");
return EconHandler.nullEconHandler();
}
return econHandler;
} catch (final Exception ignored) {
}
}
return EconHandler.nullEconHandler();
}
}

View File

@ -1,43 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.inject;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.plotsquared.bukkit.permissions.BukkitPermissionHandler;
import com.plotsquared.bukkit.permissions.VaultPermissionHandler;
import com.plotsquared.core.permissions.PermissionHandler;
import org.bukkit.Bukkit;
public class PermissionModule extends AbstractModule {
@Provides
@Singleton
PermissionHandler providePermissionHandler() {
try {
if (Bukkit.getPluginManager().isPluginEnabled("Vault")) {
return new VaultPermissionHandler();
}
} catch (final Exception ignored) {
}
return new BukkitPermissionHandler();
}
}

View File

@ -1,43 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.inject;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.plotsquared.bukkit.managers.BukkitWorldManager;
import com.plotsquared.bukkit.managers.MultiverseWorldManager;
import com.plotsquared.core.util.PlatformWorldManager;
import org.bukkit.Bukkit;
import org.bukkit.World;
public class WorldManagerModule extends AbstractModule {
@SuppressWarnings("removal") // Internal use only
@Provides
@Singleton
PlatformWorldManager<World> provideWorldManager() {
if (Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) {
return new MultiverseWorldManager();
} else {
return new BukkitWorldManager();
}
}
}

View File

@ -1,189 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.listener;
import com.google.inject.Inject;
import com.plotsquared.bukkit.player.BukkitPlayer;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.flag.implementations.CopperOxideFlag;
import com.plotsquared.core.plot.flag.implementations.MiscInteractFlag;
import com.plotsquared.core.util.PlotFlagUtil;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockFertilizeEvent;
import org.bukkit.event.block.BlockFormEvent;
import org.bukkit.event.block.BlockReceiveGameEvent;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
@SuppressWarnings("unused")
public class BlockEventListener117 implements Listener {
private static final Set<Material> COPPER_OXIDIZING = Set.of(
Material.COPPER_BLOCK,
Material.EXPOSED_COPPER,
Material.WEATHERED_COPPER,
Material.OXIDIZED_COPPER,
Material.CUT_COPPER,
Material.EXPOSED_CUT_COPPER,
Material.WEATHERED_CUT_COPPER,
Material.OXIDIZED_CUT_COPPER,
Material.CUT_COPPER_STAIRS,
Material.EXPOSED_CUT_COPPER_STAIRS,
Material.WEATHERED_CUT_COPPER_STAIRS,
Material.OXIDIZED_CUT_COPPER_STAIRS,
Material.CUT_COPPER_SLAB,
Material.EXPOSED_CUT_COPPER_SLAB,
Material.WEATHERED_CUT_COPPER_SLAB,
Material.OXIDIZED_CUT_COPPER_SLAB
);
@Inject
public BlockEventListener117() {
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockReceiveGame(BlockReceiveGameEvent event) {
Block block = event.getBlock();
Location location = BukkitUtil.adapt(block.getLocation());
Entity entity = event.getEntity();
PlotArea area = location.getPlotArea();
if (area == null) {
return;
}
BukkitPlayer plotPlayer = null;
if (entity instanceof Player player) {
plotPlayer = BukkitUtil.adapt(player);
if (area.notifyIfOutsideBuildArea(plotPlayer, location.getY())) {
event.setCancelled(true);
return;
}
}
Plot plot = location.getOwnedPlot();
if (plot == null && !PlotFlagUtil.isAreaRoadFlagsAndFlagEquals(area, MiscInteractFlag.class, true) || plot != null && !plot.getFlag(
MiscInteractFlag.class)) {
if (plotPlayer != null) {
if (plot != null) {
if (!plot.isAdded(plotPlayer.getUUID())) {
plot.debug(plotPlayer.getName() + " couldn't trigger sculk sensors because misc-interact = false");
event.setCancelled(true);
}
}
return;
}
if (entity instanceof Item item) {
UUID itemThrower = item.getThrower();
if (plot != null) {
if (itemThrower == null && (itemThrower = item.getOwner()) == null) {
plot.debug(
"A thrown item couldn't trigger sculk sensors because misc-interact = false and the item's owner could not be resolved.");
event.setCancelled(true);
return;
}
if (!plot.isAdded(itemThrower)) {
if (!plot.isAdded(itemThrower)) {
plot.debug("A thrown item couldn't trigger sculk sensors because misc-interact = false");
event.setCancelled(true);
}
}
}
}
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockFertilize(BlockFertilizeEvent event) {
Block block = event.getBlock();
List<org.bukkit.block.BlockState> blocks = event.getBlocks();
Location location = BukkitUtil.adapt(blocks.get(0).getLocation());
PlotArea area = location.getPlotArea();
if (area == null) {
for (int i = blocks.size() - 1; i >= 0; i--) {
Location blockLocation = BukkitUtil.adapt(blocks.get(i).getLocation());
blockLocation = BukkitUtil.adapt(blocks.get(i).getLocation());
if (blockLocation.isPlotArea()) {
blocks.remove(i);
}
}
} else {
Plot origin = area.getOwnedPlot(location);
if (origin == null) {
event.setCancelled(true);
return;
}
for (int i = blocks.size() - 1; i >= 0; i--) {
Location blockLocation = BukkitUtil.adapt(blocks.get(i).getLocation());
if (!area.contains(blockLocation.getX(), blockLocation.getZ())) {
blocks.remove(i);
continue;
}
Plot plot = area.getOwnedPlot(blockLocation);
if (!Objects.equals(plot, origin)) {
event.getBlocks().remove(i);
continue;
}
if (!area.buildRangeContainsY(location.getY())) {
event.getBlocks().remove(i);
}
}
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockForm(BlockFormEvent event) {
Block block = event.getBlock();
Location location = BukkitUtil.adapt(block.getLocation());
if (location.isPlotRoad()) {
event.setCancelled(true);
return;
}
PlotArea area = location.getPlotArea();
if (area == null) {
return;
}
Plot plot = area.getOwnedPlot(location);
if (plot == null) {
return;
}
if (COPPER_OXIDIZING.contains(event.getNewState().getType())) {
if (!plot.getFlag(CopperOxideFlag.class)) {
plot.debug("Copper could not oxide because copper-oxide = false");
event.setCancelled(true);
}
}
}
}

View File

@ -1,365 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.listener;
import com.google.inject.Inject;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.plot.world.SinglePlotArea;
import com.plotsquared.core.util.ReflectionUtils.RefClass;
import com.plotsquared.core.util.ReflectionUtils.RefField;
import com.plotsquared.core.util.ReflectionUtils.RefMethod;
import com.plotsquared.core.util.task.PlotSquaredTask;
import com.plotsquared.core.util.task.TaskManager;
import com.plotsquared.core.util.task.TaskTime;
import io.papermc.lib.PaperLib;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Item;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.event.world.ChunkUnloadEvent;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Objects;
import static com.plotsquared.core.util.ReflectionUtils.getRefClass;
@SuppressWarnings("unused")
public class ChunkListener implements Listener {
private final PlotAreaManager plotAreaManager;
private final int version;
private RefMethod methodGetHandleChunk;
private RefMethod methodGetHandleWorld;
private RefField mustSave;
/*
private RefMethod methodGetFullChunk;
private RefMethod methodGetBukkitChunk;
private RefMethod methodGetChunkProvider;
private RefMethod methodGetVisibleMap;
private RefField worldServer;
private RefField playerChunkMap;
private RefField updatingChunks;
private RefField visibleChunks;
*/
private Chunk lastChunk;
private boolean ignoreUnload = false;
private boolean isTrueForNotSave = true;
@Inject
public ChunkListener(final @NonNull PlotAreaManager plotAreaManager) {
this.plotAreaManager = plotAreaManager;
version = PlotSquared.platform().serverVersion()[1];
if (!Settings.Chunk_Processor.AUTO_TRIM) {
return;
}
try {
RefClass classCraftWorld = getRefClass("{cb}.CraftWorld");
this.methodGetHandleWorld = classCraftWorld.getMethod("getHandle");
RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle");
try {
if (version < 17) {
RefClass classChunk = getRefClass("{nms}.Chunk");
if (version == 13) {
this.mustSave = classChunk.getField("mustSave");
this.isTrueForNotSave = false;
} else {
this.mustSave = classChunk.getField("mustNotSave");
}
} else {
RefClass classChunk = getRefClass("net.minecraft.world.level.chunk.Chunk");
this.mustSave = classChunk.getField("mustNotSave");
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
} catch (Throwable ignored) {
Settings.Chunk_Processor.AUTO_TRIM = false;
}
for (World world : Bukkit.getWorlds()) {
world.setAutoSave(false);
}
if (version > 13) {
return;
}
TaskManager.runTaskRepeat(() -> {
try {
HashSet<Chunk> toUnload = new HashSet<>();
for (World world : Bukkit.getWorlds()) {
String worldName = world.getName();
if (!this.plotAreaManager.hasPlotArea(worldName)) {
continue;
}
Object craftWorld = methodGetHandleWorld.of(world).call();
if (version == 13) {
Object chunkMap = craftWorld.getClass().getDeclaredMethod("getPlayerChunkMap").invoke(craftWorld);
Method methodIsChunkInUse =
chunkMap.getClass().getDeclaredMethod("isChunkInUse", int.class, int.class);
Chunk[] chunks = world.getLoadedChunks();
for (Chunk chunk : chunks) {
if ((boolean) methodIsChunkInUse.invoke(chunkMap, chunk.getX(), chunk.getZ())) {
continue;
}
int x = chunk.getX();
int z = chunk.getZ();
if (!shouldSave(worldName, x, z)) {
unloadChunk(worldName, chunk, false);
continue;
}
toUnload.add(chunk);
}
}
}
if (toUnload.isEmpty()) {
return;
}
long start = System.currentTimeMillis();
for (Chunk chunk : toUnload) {
if (System.currentTimeMillis() - start > 5) {
return;
}
chunk.unload(true);
}
} catch (Throwable e) {
e.printStackTrace();
}
}, TaskTime.ticks(1L));
}
public boolean unloadChunk(String world, Chunk chunk, boolean safe) {
if (safe && shouldSave(world, chunk.getX(), chunk.getZ())) {
return false;
}
Object c = this.methodGetHandleChunk.of(chunk).call();
RefField.RefExecutor field = this.mustSave.of(c);
if ((Boolean) field.get() != isTrueForNotSave) {
field.set(isTrueForNotSave);
if (chunk.isLoaded()) {
ignoreUnload = true;
chunk.unload(false);
ignoreUnload = false;
}
}
return true;
}
public boolean shouldSave(String world, int chunkX, int chunkZ) {
int x = chunkX << 4;
int z = chunkZ << 4;
int x2 = x + 15;
int z2 = z + 15;
Location loc = Location.at(world, x, 1, z);
PlotArea plotArea = plotAreaManager.getPlotArea(loc);
if (plotArea != null) {
Plot plot = plotArea.getPlot(loc);
if (plot != null && plot.hasOwner()) {
return true;
}
}
loc = Location.at(world, x2, 1, z2);
plotArea = plotAreaManager.getPlotArea(loc);
if (plotArea != null) {
Plot plot = plotArea.getPlot(loc);
if (plot != null && plot.hasOwner()) {
return true;
}
}
loc = Location.at(world, x2, 1, z);
plotArea = plotAreaManager.getPlotArea(loc);
if (plotArea != null) {
Plot plot = plotArea.getPlot(loc);
if (plot != null && plot.hasOwner()) {
return true;
}
}
loc = Location.at(world, x, 1, z2);
plotArea = plotAreaManager.getPlotArea(loc);
if (plotArea != null) {
Plot plot = plotArea.getPlot(loc);
if (plot != null && plot.hasOwner()) {
return true;
}
}
loc = Location.at(world, x + 7, 1, z + 7);
plotArea = plotAreaManager.getPlotArea(loc);
if (plotArea == null) {
return false;
}
Plot plot = plotArea.getPlot(loc);
return plot != null && plot.hasOwner();
}
@EventHandler
public void onChunkUnload(ChunkUnloadEvent event) {
if (ignoreUnload) {
return;
}
Chunk chunk = event.getChunk();
if (Settings.Chunk_Processor.AUTO_TRIM) {
String world = chunk.getWorld().getName();
if ((!Settings.Enabled_Components.WORLDS || !SinglePlotArea.isSinglePlotWorld(world)) && this.plotAreaManager.hasPlotArea(world)) {
if (unloadChunk(world, chunk, true)) {
return;
}
}
}
if (processChunk(event.getChunk(), true)) {
chunk.setForceLoaded(true);
}
}
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
processChunk(event.getChunk(), false);
}
@EventHandler(priority = EventPriority.LOWEST)
public void onItemSpawn(ItemSpawnEvent event) {
Item entity = event.getEntity();
PaperLib.getChunkAtAsync(event.getLocation()).thenAccept(chunk -> {
if (chunk == this.lastChunk) {
event.getEntity().remove();
event.setCancelled(true);
return;
}
if (!this.plotAreaManager.hasPlotArea(chunk.getWorld().getName())) {
return;
}
Entity[] entities = chunk.getEntities();
if (entities.length > Settings.Chunk_Processor.MAX_ENTITIES) {
event.getEntity().remove();
event.setCancelled(true);
this.lastChunk = chunk;
} else {
this.lastChunk = null;
}
});
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockPhysics(BlockPhysicsEvent event) {
if (Settings.Chunk_Processor.DISABLE_PHYSICS) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onEntitySpawn(CreatureSpawnEvent event) {
LivingEntity entity = event.getEntity();
PaperLib.getChunkAtAsync(event.getLocation()).thenAccept(chunk -> {
if (chunk == this.lastChunk) {
event.getEntity().remove();
event.setCancelled(true);
return;
}
if (!this.plotAreaManager.hasPlotArea(chunk.getWorld().getName())) {
return;
}
Entity[] entities = chunk.getEntities();
if (entities.length > Settings.Chunk_Processor.MAX_ENTITIES) {
event.getEntity().remove();
event.setCancelled(true);
this.lastChunk = chunk;
} else {
this.lastChunk = null;
}
});
}
private void cleanChunk(final Chunk chunk) {
final int currentIndex = TaskManager.index.incrementAndGet();
PlotSquaredTask task = TaskManager.runTaskRepeat(() -> {
if (!chunk.isLoaded()) {
Objects.requireNonNull(TaskManager.removeTask(currentIndex)).cancel();
chunk.unload(true);
return;
}
BlockState[] tiles = chunk.getTileEntities();
if (tiles.length == 0) {
Objects.requireNonNull(TaskManager.removeTask(currentIndex)).cancel();
chunk.unload(true);
return;
}
long start = System.currentTimeMillis();
int i = 0;
while (System.currentTimeMillis() - start < 250) {
if (i >= tiles.length - Settings.Chunk_Processor.MAX_TILES) {
Objects.requireNonNull(TaskManager.removeTask(currentIndex)).cancel();
chunk.unload(true);
return;
}
tiles[i].getBlock().setType(Material.AIR, false);
i++;
}
}, TaskTime.ticks(5L));
TaskManager.addTask(task, currentIndex);
}
public boolean processChunk(Chunk chunk, boolean unload) {
if (!this.plotAreaManager.hasPlotArea(chunk.getWorld().getName())) {
return false;
}
Entity[] entities = chunk.getEntities();
BlockState[] tiles = chunk.getTileEntities();
if (entities.length > Settings.Chunk_Processor.MAX_ENTITIES) {
int toRemove = entities.length - Settings.Chunk_Processor.MAX_ENTITIES;
int index = 0;
while (toRemove > 0 && index < entities.length) {
final Entity entity = entities[index++];
if (!(entity instanceof Player)) {
entity.remove();
toRemove--;
}
}
}
if (tiles.length > Settings.Chunk_Processor.MAX_TILES) {
if (unload) {
cleanChunk(chunk);
return true;
}
for (int i = 0; i < (tiles.length - Settings.Chunk_Processor.MAX_TILES); i++) {
tiles[i].getBlock().setType(Material.AIR, false);
}
}
return false;
}
}

View File

@ -1,439 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.listener;
import com.google.inject.Inject;
import com.plotsquared.bukkit.player.BukkitPlayer;
import com.plotsquared.bukkit.util.BukkitEntityUtil;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.listener.PlayerBlockEventType;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.permissions.Permission;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.PlotHandler;
import com.plotsquared.core.plot.flag.implementations.DisablePhysicsFlag;
import com.plotsquared.core.plot.flag.implementations.EntityChangeBlockFlag;
import com.plotsquared.core.plot.flag.implementations.ExplosionFlag;
import com.plotsquared.core.plot.flag.implementations.InvincibleFlag;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.PlotFlagUtil;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.world.block.BlockType;
import org.bukkit.Material;
import org.bukkit.Particle;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Ageable;
import org.bukkit.entity.Boat;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.FallingBlock;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.entity.Vehicle;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityCombustByEntityEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.ExplosionPrimeEvent;
import org.bukkit.event.vehicle.VehicleCreateEvent;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.plugin.Plugin;
import org.bukkit.projectiles.BlockProjectileSource;
import org.bukkit.projectiles.ProjectileSource;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.Iterator;
import java.util.List;
@SuppressWarnings("unused")
public class EntityEventListener implements Listener {
private final PlotAreaManager plotAreaManager;
private final EventDispatcher eventDispatcher;
private float lastRadius;
@Inject
public EntityEventListener(
final @NonNull PlotAreaManager plotAreaManager,
final @NonNull EventDispatcher eventDispatcher
) {
this.plotAreaManager = plotAreaManager;
this.eventDispatcher = eventDispatcher;
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onEntityCombustByEntity(EntityCombustByEntityEvent event) {
EntityDamageByEntityEvent eventChange =
new EntityDamageByEntityEvent(
event.getCombuster(),
event.getEntity(),
EntityDamageEvent.DamageCause.FIRE_TICK,
event.getDuration()
);
onEntityDamageByEntityEvent(eventChange);
if (eventChange.isCancelled()) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent event) {
Entity damager = event.getDamager();
Location location = BukkitUtil.adapt(damager.getLocation());
if (!this.plotAreaManager.hasPlotArea(location.getWorldName())) {
return;
}
Entity victim = event.getEntity();
/*
if (victim.getType().equals(EntityType.ITEM_FRAME)) {
Plot plot = BukkitUtil.getLocation(victim).getPlot();
if (plot != null && !plot.isAdded(damager.getUniqueId())) {
event.setCancelled(true);
return;
}
}
*/
if (!BukkitEntityUtil.entityDamage(damager, victim, event.getCause())) {
if (event.isCancelled()) {
if (victim instanceof Ageable ageable) {
if (ageable.getAge() == -24000) {
ageable.setAge(0);
ageable.setAdult();
}
}
}
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void creatureSpawnEvent(CreatureSpawnEvent event) {
Entity entity = event.getEntity();
Location location = BukkitUtil.adapt(entity.getLocation());
PlotArea area = location.getPlotArea();
if (area == null) {
return;
}
CreatureSpawnEvent.SpawnReason reason = event.getSpawnReason();
switch (reason.toString()) {
case "DISPENSE_EGG":
case "EGG":
case "OCELOT_BABY":
case "SPAWNER_EGG":
if (!area.isSpawnEggs()) {
event.setCancelled(true);
return;
}
break;
case "REINFORCEMENTS":
case "NATURAL":
case "MOUNT":
case "PATROL":
case "RAID":
case "SHEARED":
case "SILVERFISH_BLOCK":
case "ENDER_PEARL":
case "TRAP":
case "VILLAGE_DEFENSE":
case "VILLAGE_INVASION":
case "BEEHIVE":
case "CHUNK_GEN":
if (!area.isMobSpawning()) {
event.setCancelled(true);
return;
}
break;
case "BREEDING":
if (!area.isSpawnBreeding()) {
event.setCancelled(true);
return;
}
break;
case "BUILD_IRONGOLEM":
case "BUILD_SNOWMAN":
case "BUILD_WITHER":
case "CUSTOM":
if (!area.isSpawnCustom() && entity.getType() != EntityType.ARMOR_STAND) {
event.setCancelled(true);
return;
}
break;
case "SPAWNER":
if (!area.isMobSpawnerSpawning()) {
event.setCancelled(true);
return;
}
break;
}
Plot plot = area.getOwnedPlotAbs(location);
if (plot == null) {
if (!area.isMobSpawning()) {
event.setCancelled(true);
}
return;
}
if (BukkitEntityUtil.checkEntity(entity, plot.getBasePlot(false))) {
event.setCancelled(true);
}
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onEntityFall(EntityChangeBlockEvent event) {
if (event.getEntityType() != EntityType.FALLING_BLOCK) {
return;
}
Block block = event.getBlock();
World world = block.getWorld();
String worldName = world.getName();
if (!this.plotAreaManager.hasPlotArea(worldName)) {
return;
}
Location location = BukkitUtil.adapt(block.getLocation());
PlotArea area = location.getPlotArea();
if (area == null) {
return;
}
Plot plot = area.getOwnedPlotAbs(location);
if (plot == null || plot.getFlag(DisablePhysicsFlag.class)) {
event.setCancelled(true);
if (plot != null) {
if (block.getType().hasGravity()) {
BlockEventListener.sendBlockChange(block.getLocation(), block.getBlockData());
}
plot.debug("Falling block event was cancelled because disable-physics = true");
}
return;
}
if (event.getTo().hasGravity()) {
Entity entity = event.getEntity();
List<MetadataValue> meta = entity.getMetadata("plot");
if (meta.isEmpty()) {
return;
}
Plot origin = (Plot) meta.get(0).value();
if (origin != null && !origin.equals(plot)) {
event.setCancelled(true);
entity.remove();
}
} else if (event.getTo() == Material.AIR) {
event.getEntity().setMetadata("plot", new FixedMetadataValue((Plugin) PlotSquared.platform(), plot));
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onDamage(EntityDamageEvent event) {
if (event.getEntityType() != EntityType.PLAYER) {
return;
}
Location location = BukkitUtil.adapt(event.getEntity().getLocation());
PlotArea area = location.getPlotArea();
if (area == null) {
return;
}
Plot plot = location.getOwnedPlot();
if (plot == null) {
if (PlotFlagUtil.isAreaRoadFlagsAndFlagEquals(area, InvincibleFlag.class, true)) {
event.setCancelled(true);
}
return;
}
if (plot.getFlag(InvincibleFlag.class)) {
plot.debug(event.getEntity().getName() + " could not take damage because invincible = true");
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBigBoom(EntityExplodeEvent event) {
Location location = BukkitUtil.adapt(event.getLocation());
PlotArea area = location.getPlotArea();
boolean plotArea = location.isPlotArea();
if (!plotArea) {
if (!this.plotAreaManager.hasPlotArea(location.getWorldName())) {
return;
}
return;
}
Plot plot = area.getOwnedPlot(location);
if (plot != null) {
if (plot.getFlag(ExplosionFlag.class)) {
List<MetadataValue> meta = event.getEntity().getMetadata("plot");
Plot origin;
if (meta.isEmpty()) {
origin = plot;
} else {
origin = (Plot) meta.get(0).value();
}
if (this.lastRadius != 0) {
List<Entity> nearby = event.getEntity().getNearbyEntities(this.lastRadius, this.lastRadius, this.lastRadius);
for (Entity near : nearby) {
if (near instanceof TNTPrimed || near.getType().equals(EntityType.MINECART_TNT)) {
if (!near.hasMetadata("plot")) {
near.setMetadata("plot", new FixedMetadataValue((Plugin) PlotSquared.platform(), plot));
}
}
}
this.lastRadius = 0;
}
Iterator<Block> iterator = event.blockList().iterator();
while (iterator.hasNext()) {
Block block = iterator.next();
location = BukkitUtil.adapt(block.getLocation());
if (!area.contains(location.getX(), location.getZ()) || !origin.equals(area.getOwnedPlot(location))) {
iterator.remove();
}
}
return;
} else {
plot.debug("Explosion was cancelled because explosion = false");
}
}
event.setCancelled(true);
//Spawn Explosion Particles when enabled in settings
if (Settings.General.ALWAYS_SHOW_EXPLOSIONS) {
event.getLocation().getWorld().spawnParticle(Particle.EXPLOSION_HUGE, event.getLocation(), 0);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPeskyMobsChangeTheWorldLikeWTFEvent(EntityChangeBlockEvent event) {
Entity e = event.getEntity();
Material type = event.getBlock().getType();
Location location = BukkitUtil.adapt(event.getBlock().getLocation());
PlotArea area = location.getPlotArea();
if (area == null) {
return;
}
if (e instanceof FallingBlock) {
// allow falling blocks converting to blocks and vice versa
return;
} else if (e instanceof Boat) {
// allow boats destroying lily pads
if (type == Material.LILY_PAD) {
return;
}
} else if (e instanceof Player player) {
BukkitPlayer pp = BukkitUtil.adapt(player);
if (type.toString().equals("POWDER_SNOW")) {
// Burning player evaporating powder snow. Use same checks as
// trampling farmland
BlockType blockType = BukkitAdapter.asBlockType(type);
if (!this.eventDispatcher.checkPlayerBlockEvent(pp,
PlayerBlockEventType.TRIGGER_PHYSICAL, location, blockType, true
)) {
event.setCancelled(true);
}
return;
} else {
// already handled by other flags (mainly the 'use' flag):
// - player tilting big dripleaf by standing on it
// - player picking glow berries from cave vine
// - player trampling farmland
// - player standing on or clicking redstone ore
return;
}
} else if (e instanceof Projectile entity) {
// Exact same as the ProjectileHitEvent listener, except that we let
// the entity-change-block determine what to do with shooters that
// aren't players and aren't blocks
Plot plot = area.getPlot(location);
ProjectileSource shooter = entity.getShooter();
if (shooter instanceof Player) {
PlotPlayer<?> pp = BukkitUtil.adapt((Player) shooter);
if (plot == null) {
if (!pp.hasPermission(Permission.PERMISSION_ADMIN_PROJECTILE_UNOWNED)) {
entity.remove();
event.setCancelled(true);
}
return;
}
if (plot.isAdded(pp.getUUID()) || pp.hasPermission(Permission.PERMISSION_ADMIN_PROJECTILE_OTHER)) {
return;
}
entity.remove();
event.setCancelled(true);
return;
}
if (!(shooter instanceof Entity) && shooter != null) {
if (plot == null) {
entity.remove();
event.setCancelled(true);
return;
}
Location sLoc =
BukkitUtil.adapt(((BlockProjectileSource) shooter).getBlock().getLocation());
if (!area.contains(sLoc.getX(), sLoc.getZ())) {
entity.remove();
event.setCancelled(true);
return;
}
Plot sPlot = area.getOwnedPlotAbs(sLoc);
if (sPlot == null || !PlotHandler.sameOwners(plot, sPlot)) {
entity.remove();
event.setCancelled(true);
}
return;
}
// fall back to entity-change-block flag
}
Plot plot = area.getOwnedPlot(location);
if (plot != null && !plot.getFlag(EntityChangeBlockFlag.class)) {
plot.debug(e.getType() + " could not change block because entity-change-block = false");
event.setCancelled(true);
}
}
@EventHandler
public void onPrime(ExplosionPrimeEvent event) {
this.lastRadius = event.getRadius() + 1;
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onVehicleCreate(VehicleCreateEvent event) {
Vehicle entity = event.getVehicle();
Location location = BukkitUtil.adapt(entity.getLocation());
PlotArea area = location.getPlotArea();
if (area == null) {
return;
}
Plot plot = area.getOwnedPlotAbs(location);
if (plot == null || BukkitEntityUtil.checkEntity(entity, plot)) {
entity.remove();
return;
}
if (Settings.Enabled_Components.KILL_ROAD_VEHICLES) {
entity.setMetadata("plot", new FixedMetadataValue((Plugin) PlotSquared.platform(), plot));
}
}
}

View File

@ -1,231 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.listener;
import com.plotsquared.bukkit.util.BukkitEntityUtil;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.flag.implementations.DoneFlag;
import io.papermc.lib.PaperLib;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Vehicle;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntitySpawnEvent;
import org.bukkit.event.entity.EntityTeleportEvent;
import org.bukkit.event.vehicle.VehicleBlockCollisionEvent;
import org.bukkit.event.vehicle.VehicleCreateEvent;
import org.bukkit.event.vehicle.VehicleMoveEvent;
import org.bukkit.event.vehicle.VehicleUpdateEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.plugin.Plugin;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.List;
public class EntitySpawnListener implements Listener {
private static final String KEY = "P2";
private static boolean ignoreTP = false;
private static boolean hasPlotArea = false;
private static String areaName = null;
public static void testNether(final Entity entity) {
@NonNull World world = entity.getWorld();
if (world.getEnvironment() != World.Environment.NETHER && world.getEnvironment() != World.Environment.THE_END) {
return;
}
test(entity);
}
public static void testCreate(final Entity entity) {
@NonNull World world = entity.getWorld();
if (!world.getName().equals(areaName)) {
areaName = world.getName();
hasPlotArea = PlotSquared.get().getPlotAreaManager().hasPlotArea(areaName);
}
if (!hasPlotArea) {
return;
}
test(entity);
}
public static void test(Entity entity) {
@NonNull World world = entity.getWorld();
List<MetadataValue> meta = entity.getMetadata(KEY);
if (meta.isEmpty()) {
if (PlotSquared.get().getPlotAreaManager().hasPlotArea(world.getName())) {
entity.setMetadata(KEY, new FixedMetadataValue((Plugin) PlotSquared.platform(), entity.getLocation()));
}
} else {
org.bukkit.Location origin = (org.bukkit.Location) meta.get(0).value();
World originWorld = origin.getWorld();
if (!originWorld.equals(world)) {
if (!ignoreTP) {
if (!world.getName().equalsIgnoreCase(originWorld + "_the_end")) {
if (entity.getType() == EntityType.PLAYER) {
return;
}
try {
ignoreTP = true;
PaperLib.teleportAsync(entity, origin);
} finally {
ignoreTP = false;
}
if (entity.getLocation().getWorld().equals(world)) {
entity.remove();
}
}
} else {
if (entity.getType() == EntityType.PLAYER) {
return;
}
entity.remove();
}
}
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void creatureSpawnEvent(EntitySpawnEvent event) {
Entity entity = event.getEntity();
Location location = BukkitUtil.adapt(entity.getLocation());
PlotArea area = location.getPlotArea();
if (!location.isPlotArea()) {
return;
}
Plot plot = location.getOwnedPlotAbs();
EntityType type = entity.getType();
if (plot == null) {
if (type == EntityType.DROPPED_ITEM) {
if (Settings.Enabled_Components.KILL_ROAD_ITEMS) {
event.setCancelled(true);
}
return;
}
if (!area.isMobSpawning()) {
if (type == EntityType.PLAYER) {
return;
}
if (type.isAlive()) {
event.setCancelled(true);
}
}
if (!area.isMiscSpawnUnowned() && !type.isAlive()) {
event.setCancelled(true);
}
return;
}
if (Settings.Done.RESTRICT_BUILDING && DoneFlag.isDone(plot)) {
event.setCancelled(true);
}
if (type == EntityType.ENDER_CRYSTAL) {
if (BukkitEntityUtil.checkEntity(entity, plot)) {
event.setCancelled(true);
}
return;
}
if (type == EntityType.SHULKER) {
if (!entity.hasMetadata("shulkerPlot")) {
entity.setMetadata("shulkerPlot", new FixedMetadataValue((Plugin) PlotSquared.platform(), plot.getId()));
}
}
}
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
@NonNull Chunk chunk = event.getChunk();
for (final Entity entity : chunk.getEntities()) {
testCreate(entity);
}
}
@EventHandler
public void onVehicle(VehicleUpdateEvent event) {
testNether(event.getVehicle());
}
@EventHandler
public void onVehicle(VehicleCreateEvent event) {
testCreate(event.getVehicle());
}
@EventHandler
public void onVehicle(VehicleBlockCollisionEvent event) {
testNether(event.getVehicle());
}
@EventHandler
public void onTeleport(EntityTeleportEvent event) {
Entity entity = event.getEntity();
Entity fromLocation = event.getEntity();
Block toLocation = event.getTo().getBlock();
final Location fromLocLocation = BukkitUtil.adapt(fromLocation.getLocation());
final PlotArea fromArea = fromLocLocation.getPlotArea();
Location toLocLocation = BukkitUtil.adapt(toLocation.getLocation());
PlotArea toArea = toLocLocation.getPlotArea();
if (toArea == null) {
if (fromLocation.getType() == EntityType.SHULKER && fromArea != null) {
event.setCancelled(true);
}
return;
}
Plot toPlot = toArea.getOwnedPlot(toLocLocation);
if (fromLocation.getType() == EntityType.SHULKER && fromArea != null) {
final Plot fromPlot = fromArea.getOwnedPlot(fromLocLocation);
if (fromPlot != null || toPlot != null) {
if ((fromPlot == null || !fromPlot.equals(toPlot)) && (toPlot == null || !toPlot.equals(fromPlot))) {
event.setCancelled(true);
return;
}
}
}
if (entity instanceof Vehicle || entity instanceof ArmorStand) {
testNether(event.getEntity());
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void vehicleMove(VehicleMoveEvent event) {
testNether(event.getVehicle());
}
@EventHandler
public void spawn(CreatureSpawnEvent event) {
if (event.getEntityType() == EntityType.ARMOR_STAND) {
testCreate(event.getEntity());
}
}
}

View File

@ -1,128 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.listener;
import com.plotsquared.bukkit.player.BukkitPlayer;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.permissions.Permission;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.flag.implementations.ForcefieldFlag;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
@SuppressWarnings("unused")
public class ForceFieldListener {
private static Set<PlotPlayer<?>> getNearbyPlayers(Player player, Plot plot) {
Set<PlotPlayer<?>> players = new HashSet<>();
for (Player nearPlayer : player.getNearbyEntities(5d, 5d, 5d).stream()
.filter(entity -> entity instanceof Player)
.map(entity -> (Player) entity)
.toList()
) {
PlotPlayer<?> plotPlayer;
if ((plotPlayer = BukkitUtil.adapt(nearPlayer)) == null || !plot
.equals(plotPlayer.getCurrentPlot())) {
continue;
}
if (!plot.isAdded(plotPlayer.getUUID())) {
players.add(plotPlayer);
}
}
return players;
}
private static PlotPlayer<?> hasNearbyPermitted(Player player, Plot plot) {
for (Player nearPlayer : player.getNearbyEntities(5d, 5d, 5d).stream()
.filter(entity -> entity instanceof Player)
.map(entity -> (Player) entity)
.toList()
) {
PlotPlayer<?> plotPlayer;
if ((plotPlayer = BukkitUtil.adapt(nearPlayer)) == null || !plot
.equals(plotPlayer.getCurrentPlot())) {
continue;
}
if (plot.isAdded(plotPlayer.getUUID())) {
return plotPlayer;
}
}
return null;
}
private static Vector calculateVelocity(PlotPlayer<?> player, PlotPlayer<?> e) {
Location playerLocation = player.getLocationFull();
Location oPlayerLocation = e.getLocation();
double playerX = playerLocation.getX();
double playerY = playerLocation.getY();
double playerZ = playerLocation.getZ();
double oPlayerX = oPlayerLocation.getX();
double oPlayerY = oPlayerLocation.getY();
double oPlayerZ = oPlayerLocation.getZ();
double x = 0d;
if (playerX < oPlayerX) {
x = 1.0d;
} else if (playerX > oPlayerX) {
x = -1.0d;
}
double y = 0d;
if (playerY < oPlayerY) {
y = 0.5d;
} else if (playerY > oPlayerY) {
y = -0.5d;
}
double z = 0d;
if (playerZ < oPlayerZ) {
z = 1.0d;
} else if (playerZ > oPlayerZ) {
z = -1.0d;
}
return new Vector(x, y, z);
}
public static void handleForcefield(Player player, PlotPlayer<?> plotPlayer, Plot plot) {
if (plot.getFlag(ForcefieldFlag.class)) {
UUID uuid = plotPlayer.getUUID();
if (plot.isAdded(uuid)) {
Set<PlotPlayer<?>> players = getNearbyPlayers(player, plot);
for (PlotPlayer<?> oPlayer : players) {
if (!oPlayer.hasPermission(Permission.PERMISSION_ADMIN_ENTRY_FORCEFIELD)) {
((BukkitPlayer) oPlayer).player
.setVelocity(calculateVelocity(plotPlayer, oPlayer));
}
}
} else {
PlotPlayer<?> oPlayer = hasNearbyPermitted(player, plot);
if (oPlayer == null) {
return;
}
if (!plotPlayer.hasPermission(Permission.PERMISSION_ADMIN_ENTRY_FORCEFIELD)) {
player.setVelocity(calculateVelocity(oPlayer, plotPlayer));
}
}
}
}
}

View File

@ -1,456 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.listener;
import com.destroystokyo.paper.event.block.BeaconEffectEvent;
import com.destroystokyo.paper.event.entity.EntityPathfindEvent;
import com.destroystokyo.paper.event.entity.PlayerNaturallySpawnCreaturesEvent;
import com.destroystokyo.paper.event.entity.PreCreatureSpawnEvent;
import com.destroystokyo.paper.event.entity.PreSpawnerSpawnEvent;
import com.destroystokyo.paper.event.entity.SlimePathfindEvent;
import com.destroystokyo.paper.event.player.PlayerLaunchProjectileEvent;
import com.destroystokyo.paper.event.server.AsyncTabCompleteEvent;
import com.google.inject.Inject;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.core.command.Command;
import com.plotsquared.core.command.MainCommand;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.configuration.caption.TranslatableCaption;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.permissions.Permission;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.flag.FlagContainer;
import com.plotsquared.core.plot.flag.implementations.BeaconEffectsFlag;
import com.plotsquared.core.plot.flag.implementations.DoneFlag;
import com.plotsquared.core.plot.flag.implementations.ProjectilesFlag;
import com.plotsquared.core.plot.flag.types.BooleanFlag;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.util.PlotFlagUtil;
import net.kyori.adventure.text.minimessage.Template;
import org.bukkit.Chunk;
import org.bukkit.block.Block;
import org.bukkit.block.TileState;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.Slime;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.projectiles.ProjectileSource;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
/**
* Events specific to Paper. Some toit nups here
*/
@SuppressWarnings("unused")
public class PaperListener implements Listener {
private final PlotAreaManager plotAreaManager;
private Chunk lastChunk;
@Inject
public PaperListener(final @NonNull PlotAreaManager plotAreaManager) {
this.plotAreaManager = plotAreaManager;
}
@EventHandler
public void onEntityPathfind(EntityPathfindEvent event) {
if (!Settings.Paper_Components.ENTITY_PATHING) {
return;
}
Location toLoc = BukkitUtil.adapt(event.getLoc());
Location fromLoc = BukkitUtil.adapt(event.getEntity().getLocation());
PlotArea tarea = toLoc.getPlotArea();
if (tarea == null) {
return;
}
PlotArea farea = fromLoc.getPlotArea();
if (farea == null) {
return;
}
if (tarea != farea) {
event.setCancelled(true);
return;
}
Plot tplot = toLoc.getPlot();
Plot fplot = fromLoc.getPlot();
if (tplot == null ^ fplot == null) {
event.setCancelled(true);
return;
}
if (tplot == null || tplot.getId().hashCode() == fplot.getId().hashCode()) {
return;
}
if (fplot.isMerged() && fplot.getConnectedPlots().contains(fplot)) {
return;
}
event.setCancelled(true);
}
@EventHandler
public void onEntityPathfind(SlimePathfindEvent event) {
if (!Settings.Paper_Components.ENTITY_PATHING) {
return;
}
Slime slime = event.getEntity();
Block b = slime.getTargetBlock(4);
if (b == null) {
return;
}
Location toLoc = BukkitUtil.adapt(b.getLocation());
Location fromLoc = BukkitUtil.adapt(event.getEntity().getLocation());
PlotArea tarea = toLoc.getPlotArea();
if (tarea == null) {
return;
}
PlotArea farea = fromLoc.getPlotArea();
if (farea == null) {
return;
}
if (tarea != farea) {
event.setCancelled(true);
return;
}
Plot tplot = toLoc.getPlot();
Plot fplot = fromLoc.getPlot();
if (tplot == null ^ fplot == null) {
event.setCancelled(true);
return;
}
if (tplot == null || tplot.getId().hashCode() == fplot.getId().hashCode()) {
return;
}
if (fplot.isMerged() && fplot.getConnectedPlots().contains(fplot)) {
return;
}
event.setCancelled(true);
}
@EventHandler
public void onPreCreatureSpawnEvent(PreCreatureSpawnEvent event) {
if (!Settings.Paper_Components.CREATURE_SPAWN) {
return;
}
Location location = BukkitUtil.adapt(event.getSpawnLocation());
PlotArea area = location.getPlotArea();
if (!location.isPlotArea()) {
return;
}
//If entities are spawning... the chunk should be loaded?
Entity[] entities = event.getSpawnLocation().getChunk().getEntities();
if (entities.length > Settings.Chunk_Processor.MAX_ENTITIES) {
event.setShouldAbortSpawn(true);
event.setCancelled(true);
return;
}
CreatureSpawnEvent.SpawnReason reason = event.getReason();
switch (reason.toString()) {
case "DISPENSE_EGG":
case "EGG":
case "OCELOT_BABY":
case "SPAWNER_EGG":
if (!area.isSpawnEggs()) {
event.setShouldAbortSpawn(true);
event.setCancelled(true);
return;
}
break;
case "REINFORCEMENTS":
case "NATURAL":
case "MOUNT":
case "PATROL":
case "RAID":
case "SHEARED":
case "SILVERFISH_BLOCK":
case "ENDER_PEARL":
case "TRAP":
case "VILLAGE_DEFENSE":
case "VILLAGE_INVASION":
case "BEEHIVE":
case "CHUNK_GEN":
if (!area.isMobSpawning()) {
event.setShouldAbortSpawn(true);
event.setCancelled(true);
return;
}
break;
case "BREEDING":
if (!area.isSpawnBreeding()) {
event.setShouldAbortSpawn(true);
event.setCancelled(true);
return;
}
break;
case "BUILD_IRONGOLEM":
case "BUILD_SNOWMAN":
case "BUILD_WITHER":
case "CUSTOM":
if (!area.isSpawnCustom() && event.getType() != EntityType.ARMOR_STAND) {
event.setShouldAbortSpawn(true);
event.setCancelled(true);
return;
}
break;
case "SPAWNER":
if (!area.isMobSpawnerSpawning()) {
event.setShouldAbortSpawn(true);
event.setCancelled(true);
return;
}
break;
}
Plot plot = location.getOwnedPlotAbs();
if (plot == null) {
EntityType type = event.getType();
// PreCreatureSpawnEvent **should** not be called for DROPPED_ITEM, just for the sake of consistency
if (type == EntityType.DROPPED_ITEM) {
if (Settings.Enabled_Components.KILL_ROAD_ITEMS) {
event.setCancelled(true);
}
return;
}
if (!area.isMobSpawning()) {
if (type == EntityType.PLAYER) {
return;
}
if (type.isAlive()) {
event.setShouldAbortSpawn(true);
event.setCancelled(true);
}
}
if (!area.isMiscSpawnUnowned() && !type.isAlive()) {
event.setShouldAbortSpawn(true);
event.setCancelled(true);
}
return;
}
if (Settings.Done.RESTRICT_BUILDING && DoneFlag.isDone(plot)) {
event.setShouldAbortSpawn(true);
event.setCancelled(true);
}
}
@EventHandler
public void onPlayerNaturallySpawnCreaturesEvent(PlayerNaturallySpawnCreaturesEvent event) {
if (Settings.Paper_Components.CANCEL_CHUNK_SPAWN) {
Location location = BukkitUtil.adapt(event.getPlayer().getLocation());
PlotArea area = location.getPlotArea();
if (area != null && !area.isMobSpawning()) {
event.setCancelled(true);
}
}
}
@EventHandler
public void onPreSpawnerSpawnEvent(PreSpawnerSpawnEvent event) {
if (Settings.Paper_Components.SPAWNER_SPAWN) {
Location location = BukkitUtil.adapt(event.getSpawnerLocation());
PlotArea area = location.getPlotArea();
if (area != null && !area.isMobSpawnerSpawning()) {
event.setCancelled(true);
event.setShouldAbortSpawn(true);
}
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onBlockPlace(BlockPlaceEvent event) {
if (!Settings.Paper_Components.TILE_ENTITY_CHECK || !Settings.Enabled_Components.CHUNK_PROCESSOR) {
return;
}
if (!(event.getBlock().getState(false) instanceof TileState)) {
return;
}
final Location location = BukkitUtil.adapt(event.getBlock().getLocation());
final PlotArea plotArea = location.getPlotArea();
if (plotArea == null) {
return;
}
final int tileEntityCount = event.getBlock().getChunk().getTileEntities(false).length;
if (tileEntityCount >= Settings.Chunk_Processor.MAX_TILES) {
final PlotPlayer<?> plotPlayer = BukkitUtil.adapt(event.getPlayer());
plotPlayer.sendMessage(
TranslatableCaption.of("errors.tile_entity_cap_reached"),
Template.of("amount", String.valueOf(Settings.Chunk_Processor.MAX_TILES))
);
event.setCancelled(true);
event.setBuild(false);
}
}
/**
* Unsure if this will be any performance improvement over the spigot version,
* but here it is anyway :)
*
* @param event Paper's PlayerLaunchProjectileEvent
*/
@EventHandler
public void onProjectileLaunch(PlayerLaunchProjectileEvent event) {
if (!Settings.Paper_Components.PLAYER_PROJECTILE) {
return;
}
Projectile entity = event.getProjectile();
ProjectileSource shooter = entity.getShooter();
if (!(shooter instanceof Player)) {
return;
}
Location location = BukkitUtil.adapt(entity.getLocation());
PlotArea area = location.getPlotArea();
if (area == null) {
return;
}
PlotPlayer<Player> pp = BukkitUtil.adapt((Player) shooter);
Plot plot = location.getOwnedPlot();
if (plot == null) {
if (!PlotFlagUtil.isAreaRoadFlagsAndFlagEquals(area, ProjectilesFlag.class, true) && !pp.hasPermission(
Permission.PERMISSION_ADMIN_PROJECTILE_ROAD
)) {
pp.sendMessage(
TranslatableCaption.of("permission.no_permission_event"),
Template.of("node", String.valueOf(Permission.PERMISSION_ADMIN_PROJECTILE_ROAD))
);
entity.remove();
event.setCancelled(true);
}
} else if (!plot.hasOwner()) {
if (!pp.hasPermission(Permission.PERMISSION_ADMIN_PROJECTILE_UNOWNED)) {
pp.sendMessage(
TranslatableCaption.of("permission.no_permission_event"),
Template.of("node", String.valueOf(Permission.PERMISSION_ADMIN_PROJECTILE_UNOWNED))
);
entity.remove();
event.setCancelled(true);
}
} else if (!plot.isAdded(pp.getUUID())) {
if (!plot.getFlag(ProjectilesFlag.class)) {
if (!pp.hasPermission(Permission.PERMISSION_ADMIN_PROJECTILE_OTHER)) {
pp.sendMessage(
TranslatableCaption.of("permission.no_permission_event"),
Template.of("node", String.valueOf(Permission.PERMISSION_ADMIN_PROJECTILE_OTHER))
);
entity.remove();
event.setCancelled(true);
}
}
}
}
@EventHandler
public void onAsyncTabCompletion(final AsyncTabCompleteEvent event) {
if (!Settings.Paper_Components.ASYNC_TAB_COMPLETION) {
return;
}
String buffer = event.getBuffer();
if (!(event.getSender() instanceof Player)) {
return;
}
if ((!event.isCommand() && !buffer.startsWith("/")) || buffer.indexOf(' ') == -1) {
return;
}
if (buffer.startsWith("/")) {
buffer = buffer.substring(1);
}
final String[] unprocessedArgs = buffer.split(Pattern.quote(" "));
if (unprocessedArgs.length == 1) {
return; // We don't do anything in this case
} else if (!Settings.Enabled_Components.TAB_COMPLETED_ALIASES
.contains(unprocessedArgs[0].toLowerCase(Locale.ENGLISH))) {
return;
}
final String[] args = new String[unprocessedArgs.length - 1];
System.arraycopy(unprocessedArgs, 1, args, 0, args.length);
try {
final PlotPlayer<?> player = BukkitUtil.adapt((Player) event.getSender());
final Collection<Command> objects = MainCommand.getInstance().tab(player, args, buffer.endsWith(" "));
if (objects == null) {
return;
}
final List<String> result = new ArrayList<>();
for (final com.plotsquared.core.command.Command o : objects) {
result.add(o.toString());
}
event.setCompletions(result);
event.setHandled(true);
} catch (final Exception ignored) {
}
}
@EventHandler(ignoreCancelled = true)
public void onBeaconEffect(final BeaconEffectEvent event) {
Block block = event.getBlock();
Location beaconLocation = BukkitUtil.adapt(block.getLocation());
Plot beaconPlot = beaconLocation.getPlot();
PlotArea area = beaconLocation.getPlotArea();
if (area == null) {
return;
}
Player player = event.getPlayer();
Location playerLocation = BukkitUtil.adapt(player.getLocation());
PlotPlayer<Player> plotPlayer = BukkitUtil.adapt(player);
Plot playerStandingPlot = playerLocation.getPlot();
if (playerStandingPlot == null) {
FlagContainer container = area.getRoadFlagContainer();
if (!getBooleanFlagValue(container, BeaconEffectsFlag.class, true) ||
(beaconPlot != null && Settings.Enabled_Components.DISABLE_BEACON_EFFECT_OVERFLOW)) {
event.setCancelled(true);
}
return;
}
FlagContainer container = playerStandingPlot.getFlagContainer();
boolean plotBeaconEffects = getBooleanFlagValue(container, BeaconEffectsFlag.class, true);
if (playerStandingPlot.equals(beaconPlot)) {
if (!plotBeaconEffects) {
event.setCancelled(true);
}
return;
}
if (!plotBeaconEffects || Settings.Enabled_Components.DISABLE_BEACON_EFFECT_OVERFLOW) {
event.setCancelled(true);
}
}
private boolean getBooleanFlagValue(@NonNull FlagContainer container,
@NonNull Class<? extends BooleanFlag<?>> flagClass,
boolean defaultValue) {
BooleanFlag<?> flag = container.getFlag(flagClass);
return flag == null ? defaultValue : flag.getValue();
}
}

View File

@ -1,91 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.listener;
import com.google.inject.Inject;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.configuration.caption.TranslatableCaption;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.world.PlotAreaManager;
import net.kyori.adventure.text.minimessage.Template;
import org.bukkit.block.Banner;
import org.bukkit.block.Beacon;
import org.bukkit.block.BlockState;
import org.bukkit.block.CommandBlock;
import org.bukkit.block.Comparator;
import org.bukkit.block.Conduit;
import org.bukkit.block.Container;
import org.bukkit.block.CreatureSpawner;
import org.bukkit.block.DaylightDetector;
import org.bukkit.block.EnchantingTable;
import org.bukkit.block.EndGateway;
import org.bukkit.block.EnderChest;
import org.bukkit.block.Jukebox;
import org.bukkit.block.Sign;
import org.bukkit.block.Skull;
import org.bukkit.block.Structure;
import org.bukkit.block.data.type.Bed;
import org.bukkit.event.EventHandler;
import org.bukkit.event.block.BlockPlaceEvent;
import org.checkerframework.checker.nullness.qual.NonNull;
/**
* @deprecated P2 effectively no longer supports 1.13
*/
@Deprecated(forRemoval = true, since = "6.10.4")
public class PaperListener113 extends PaperListener {
@Inject
public PaperListener113(@NonNull PlotAreaManager plotAreaManager) {
super(plotAreaManager);
}
@EventHandler
public void onBlockPlace(BlockPlaceEvent event) {
if (!Settings.Paper_Components.TILE_ENTITY_CHECK || !Settings.Enabled_Components.CHUNK_PROCESSOR) {
return;
}
BlockState state = event.getBlock().getState(false);
if (!(state instanceof Banner || state instanceof Beacon || state instanceof Bed || state instanceof CommandBlock
|| state instanceof Comparator || state instanceof Conduit || state instanceof Container || state instanceof CreatureSpawner
|| state instanceof DaylightDetector || state instanceof EnchantingTable || state instanceof EnderChest || state instanceof EndGateway
|| state instanceof Jukebox || state instanceof Sign || state instanceof Skull || state instanceof Structure)) {
return;
}
final Location location = BukkitUtil.adapt(event.getBlock().getLocation());
final PlotArea plotArea = location.getPlotArea();
if (plotArea == null) {
return;
}
final int tileEntityCount = event.getBlock().getChunk().getTileEntities(false).length;
if (tileEntityCount >= Settings.Chunk_Processor.MAX_TILES) {
final PlotPlayer<?> plotPlayer = BukkitUtil.adapt(event.getPlayer());
plotPlayer.sendMessage(
TranslatableCaption.of("errors.tile_entity_cap_reached"),
Template.of("amount", String.valueOf(Settings.Chunk_Processor.MAX_TILES))
);
event.setCancelled(true);
event.setBuild(false);
}
}
}

View File

@ -1,208 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.listener;
import com.google.inject.Inject;
import com.plotsquared.bukkit.util.BukkitEntityUtil;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.core.configuration.caption.TranslatableCaption;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.permissions.Permission;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.PlotHandler;
import com.plotsquared.core.plot.flag.implementations.ProjectilesFlag;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.util.PlotFlagUtil;
import net.kyori.adventure.text.minimessage.Template;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.ThrownPotion;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.LingeringPotionSplashEvent;
import org.bukkit.event.entity.PotionSplashEvent;
import org.bukkit.event.entity.ProjectileHitEvent;
import org.bukkit.event.entity.ProjectileLaunchEvent;
import org.bukkit.projectiles.BlockProjectileSource;
import org.bukkit.projectiles.ProjectileSource;
import org.checkerframework.checker.nullness.qual.NonNull;
@SuppressWarnings("unused")
public class ProjectileEventListener implements Listener {
private final PlotAreaManager plotAreaManager;
@Inject
public ProjectileEventListener(final @NonNull PlotAreaManager plotAreaManager) {
this.plotAreaManager = plotAreaManager;
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onLingeringPotionSplash(LingeringPotionSplashEvent event) {
// Cancelling projectile hit events still results in area effect clouds.
// We need to cancel the splash events to get rid of those.
onProjectileHit(event);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPotionSplash(PotionSplashEvent event) {
ThrownPotion damager = event.getPotion();
Location location = BukkitUtil.adapt(damager.getLocation());
if (!this.plotAreaManager.hasPlotArea(location.getWorldName())) {
return;
}
int count = 0;
for (LivingEntity victim : event.getAffectedEntities()) {
if (!BukkitEntityUtil.entityDamage(damager, victim)) {
event.setIntensity(victim, 0);
count++;
}
}
if (count > 0 && count == event.getAffectedEntities().size()) {
event.setCancelled(true);
} else {
// Cancelling projectile hit events still results in potions
// splashing in the world. We need to cancel the splash events to
// avoid that.
onProjectileHit(event);
}
}
@EventHandler(ignoreCancelled = true)
public void onProjectileLaunch(ProjectileLaunchEvent event) {
Projectile entity = event.getEntity();
ProjectileSource shooter = entity.getShooter();
if (!(shooter instanceof Player)) {
return;
}
Location location = BukkitUtil.adapt(entity.getLocation());
PlotArea area = location.getPlotArea();
if (area == null) {
return;
}
PlotPlayer<Player> pp = BukkitUtil.adapt((Player) shooter);
Plot plot = location.getOwnedPlot();
if (plot == null) {
if (!PlotFlagUtil.isAreaRoadFlagsAndFlagEquals(area, ProjectilesFlag.class, true) && !pp.hasPermission(
Permission.PERMISSION_ADMIN_PROJECTILE_ROAD
)) {
pp.sendMessage(
TranslatableCaption.of("permission.no_permission_event"),
Template.of("node", String.valueOf(Permission.PERMISSION_ADMIN_PROJECTILE_ROAD))
);
entity.remove();
event.setCancelled(true);
}
} else if (!plot.hasOwner()) {
if (!pp.hasPermission(Permission.PERMISSION_ADMIN_PROJECTILE_UNOWNED)) {
pp.sendMessage(
TranslatableCaption.of("permission.no_permission_event"),
Template.of("node", String.valueOf(Permission.PERMISSION_ADMIN_PROJECTILE_UNOWNED))
);
entity.remove();
event.setCancelled(true);
}
} else if (!plot.isAdded(pp.getUUID())) {
if (!plot.getFlag(ProjectilesFlag.class)) {
if (!pp.hasPermission(Permission.PERMISSION_ADMIN_PROJECTILE_OTHER)) {
pp.sendMessage(
TranslatableCaption.of("permission.no_permission_event"),
Template.of("node", String.valueOf(Permission.PERMISSION_ADMIN_PROJECTILE_OTHER))
);
entity.remove();
event.setCancelled(true);
}
}
}
}
@EventHandler
public void onProjectileHit(ProjectileHitEvent event) {
Projectile entity = event.getEntity();
Location location = BukkitUtil.adapt(entity.getLocation());
if (!this.plotAreaManager.hasPlotArea(location.getWorldName())) {
return;
}
PlotArea area = location.getPlotArea();
if (area == null) {
return;
}
Plot plot = area.getPlot(location);
ProjectileSource shooter = entity.getShooter();
if (shooter instanceof Player) {
if (!((Player) shooter).isOnline()) {
if (plot != null) {
if (plot.isAdded(((Player) shooter).getUniqueId()) || plot.getFlag(ProjectilesFlag.class)) {
return;
}
} else if (PlotFlagUtil.isAreaRoadFlagsAndFlagEquals(area, ProjectilesFlag.class, true)) {
return;
}
entity.remove();
event.setCancelled(true);
return;
}
PlotPlayer<?> pp = BukkitUtil.adapt((Player) shooter);
if (plot == null) {
if (!PlotFlagUtil.isAreaRoadFlagsAndFlagEquals(area, ProjectilesFlag.class, true) && !pp.hasPermission(
Permission.PERMISSION_ADMIN_PROJECTILE_UNOWNED
)) {
entity.remove();
event.setCancelled(true);
}
return;
}
if (plot.isAdded(pp.getUUID()) || pp.hasPermission(Permission.PERMISSION_ADMIN_PROJECTILE_OTHER) || plot.getFlag(
ProjectilesFlag.class)) {
return;
}
entity.remove();
event.setCancelled(true);
return;
}
if (!(shooter instanceof Entity) && shooter != null) {
if (plot == null) {
entity.remove();
event.setCancelled(true);
return;
}
Location sLoc =
BukkitUtil.adapt(((BlockProjectileSource) shooter).getBlock().getLocation());
if (!area.contains(sLoc.getX(), sLoc.getZ())) {
entity.remove();
event.setCancelled(true);
return;
}
Plot sPlot = area.getOwnedPlotAbs(sLoc);
if (sPlot == null || !PlotHandler.sameOwners(plot, sPlot)) {
entity.remove();
event.setCancelled(true);
}
}
}
}

View File

@ -1,50 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.listener;
import com.google.inject.Inject;
import com.plotsquared.bukkit.BukkitPlatform;
import com.plotsquared.bukkit.placeholder.MVdWPlaceholders;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.configuration.caption.TranslatableCaption;
import com.plotsquared.core.player.ConsolePlayer;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.server.ServerLoadEvent;
import org.checkerframework.checker.nullness.qual.NonNull;
public class ServerListener implements Listener {
private final BukkitPlatform plugin;
@Inject
public ServerListener(final @NonNull BukkitPlatform plugin) {
this.plugin = plugin;
}
@EventHandler
public void onServerLoad(ServerLoadEvent event) {
if (Bukkit.getPluginManager().getPlugin("MVdWPlaceholderAPI") != null && Settings.Enabled_Components.USE_MVDWAPI) {
new MVdWPlaceholders(this.plugin, this.plugin.placeholderRegistry());
ConsolePlayer.getConsole().sendMessage(TranslatableCaption.of("placeholder.hooked"));
}
}
}

View File

@ -1,102 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.listener;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.plot.world.SinglePlotArea;
import com.plotsquared.core.plot.world.SinglePlotAreaManager;
import com.plotsquared.core.util.ReflectionUtils;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.world.ChunkEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import static com.plotsquared.core.util.ReflectionUtils.getRefClass;
public class SingleWorldListener implements Listener {
private final Method methodGetHandleChunk;
private Field shouldSave = null;
public SingleWorldListener() throws Exception {
ReflectionUtils.RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle").getRealMethod();
try {
if (PlotSquared.platform().serverVersion()[1] < 17) {
ReflectionUtils.RefClass classChunk = getRefClass("{nms}.Chunk");
if (PlotSquared.platform().serverVersion()[1] == 13) {
this.shouldSave = classChunk.getField("mustSave").getRealField();
} else {
this.shouldSave = classChunk.getField("s").getRealField();
}
} else if (PlotSquared.platform().serverVersion()[1] == 17) {
ReflectionUtils.RefClass classChunk = getRefClass("net.minecraft.world.level.chunk.Chunk");
this.shouldSave = classChunk.getField("r").getRealField();
} else if (PlotSquared.platform().serverVersion()[1] == 18) {
ReflectionUtils.RefClass classChunk = getRefClass("net.minecraft.world.level.chunk.IChunkAccess");
this.shouldSave = classChunk.getField("b").getRealField();
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
public void markChunkAsClean(Chunk chunk) {
try {
Object nmsChunk = methodGetHandleChunk.invoke(chunk);
if (shouldSave != null) {
this.shouldSave.set(nmsChunk, false);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
private void handle(ChunkEvent event) {
World world = event.getWorld();
String name = world.getName();
PlotAreaManager man = PlotSquared.get().getPlotAreaManager();
if (!(man instanceof SinglePlotAreaManager)) {
return;
}
if (!SinglePlotArea.isSinglePlotWorld(name)) {
return;
}
markChunkAsClean(event.getChunk());
}
// @EventHandler
// public void onPopulate(ChunkPopulateEvent event) {
// handle(event);
// }
@EventHandler(priority = EventPriority.LOWEST)
public void onChunkLoad(ChunkLoadEvent event) {
handle(event);
}
}

View File

@ -1,57 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.listener;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.flag.FlagContainer;
import com.plotsquared.core.plot.flag.implementations.BeaconEffectsFlag;
import org.bukkit.entity.Entity;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityPotionEffectEvent;
import org.checkerframework.checker.nullness.qual.NonNull;
/**
* Fallback listener for paper events on spigot
*/
public class SpigotListener implements Listener {
@EventHandler(ignoreCancelled = true)
public void onEffect(@NonNull EntityPotionEffectEvent event) {
if (event.getCause() != EntityPotionEffectEvent.Cause.BEACON) {
return;
}
Entity entity = event.getEntity();
Location location = BukkitUtil.adapt(entity.getLocation());
Plot plot = location.getPlot();
if (plot == null) {
return;
}
FlagContainer container = plot.getFlagContainer();
BeaconEffectsFlag effectsEnabled = container.getFlag(BeaconEffectsFlag.class);
if (effectsEnabled != null && !effectsEnabled.getValue()) {
event.setCancelled(true);
}
}
}

View File

@ -1,63 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.listener;
import com.google.inject.Inject;
import com.plotsquared.bukkit.generator.BukkitPlotGenerator;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.generator.GeneratorWrapper;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.plot.world.SinglePlotAreaManager;
import org.bukkit.World;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.world.WorldInitEvent;
import org.bukkit.generator.ChunkGenerator;
import org.checkerframework.checker.nullness.qual.NonNull;
@SuppressWarnings("unused")
public class WorldEvents implements Listener {
private final PlotAreaManager plotAreaManager;
@Inject
public WorldEvents(final @NonNull PlotAreaManager plotAreaManager) {
this.plotAreaManager = plotAreaManager;
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onWorldInit(WorldInitEvent event) {
World world = event.getWorld();
String name = world.getName();
if (this.plotAreaManager instanceof final SinglePlotAreaManager single) {
if (single.isWorld(name)) {
world.setKeepSpawnInMemory(false);
return;
}
}
ChunkGenerator gen = world.getGenerator();
if (gen instanceof GeneratorWrapper) {
PlotSquared.get().loadWorld(name, (GeneratorWrapper<?>) gen);
} else {
PlotSquared.get().loadWorld(name, new BukkitPlotGenerator(name, gen, this.plotAreaManager));
}
}
}

View File

@ -1,89 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.managers;
import com.google.inject.Singleton;
import com.plotsquared.core.configuration.file.YamlConfiguration;
import com.plotsquared.core.util.PlatformWorldManager;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.WorldCreator;
import org.bukkit.WorldType;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Default Bukkit world manager. It will handle world creation by
* registering the generator in bukkit.yml
*/
@Singleton
public class BukkitWorldManager implements PlatformWorldManager<World> {
@Override
public void initialize() {
}
@Override
public @Nullable World handleWorldCreation(@NonNull String worldName, @Nullable String generator) {
this.setGenerator(worldName, generator);
final WorldCreator wc = new WorldCreator(worldName);
wc.environment(World.Environment.NORMAL);
if (generator != null) {
wc.generator(generator);
wc.type(WorldType.FLAT);
}
return Bukkit.createWorld(wc);
}
protected void setGenerator(final @Nullable String worldName, final @Nullable String generator) {
if (generator == null) {
return;
}
File file = new File("bukkit.yml").getAbsoluteFile();
YamlConfiguration yml = YamlConfiguration.loadConfiguration(file);
yml.set(String.format("worlds.%s.generator", worldName), generator);
try {
yml.save(file);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public String getName() {
return "bukkit";
}
@Override
public Collection<String> getWorlds() {
final List<World> worlds = Bukkit.getWorlds();
final List<String> worldNames = new ArrayList<>();
for (final World world : worlds) {
worldNames.add(world.getName());
}
return worldNames;
}
}

View File

@ -1,63 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.managers;
/*
import com.google.inject.Singleton;
import org.bukkit.World;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import se.hyperver.hyperverse.Hyperverse;
import se.hyperver.hyperverse.world.WorldConfiguration;
import se.hyperver.hyperverse.world.WorldConfigurationBuilder;
import se.hyperver.hyperverse.world.WorldFeatures;
import se.hyperver.hyperverse.world.WorldType;
Hyperverse implementation is currently put on ice until Hyperverse is released on a stable line and deployed to the central
repository.
@Singleton
public class HyperverseWorldManager extends BukkitWorldManager {
@Override
public @Nullable World handleWorldCreation(@NonNull String worldName, @Nullable String generator) {
// First let Bukkit register the world
this.setGenerator(worldName, generator);
// Create the world
final WorldConfigurationBuilder worldConfigurationBuilder = WorldConfiguration.builder()
.setName(worldName).setType(WorldType.OVER_WORLD);
if (generator != null) {
worldConfigurationBuilder.setGenerator(generator).setWorldFeatures(WorldFeatures.FLATLAND);
}
try {
return Hyperverse.getApi().createWorld(worldConfigurationBuilder.createWorldConfiguration())
.getBukkitWorld();
} catch (final Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public String getName() {
return "bukkit-hyperverse";
}
}
*/

View File

@ -1,58 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.managers;
import com.google.inject.Singleton;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Multiverse specific manager that informs Multiverse of
* world creation by executing a console command
*
* @deprecated Deprecated and scheduled for removal without replacement
* in favor of the build in setup wizard.
* However, this class will be kept around for a while, given it's not a maintenance burden.
*/
@Deprecated
@Singleton
public class MultiverseWorldManager extends BukkitWorldManager {
@Override
public @Nullable World handleWorldCreation(final @NonNull String worldName, final @Nullable String generator) {
// First let Bukkit register the world
this.setGenerator(worldName, generator);
// Then we send the console command
final StringBuilder commandBuilder = new StringBuilder("mv create ")
.append(worldName).append(" normal");
if (generator != null) {
commandBuilder.append(" -g ").append(generator);
}
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), commandBuilder.toString());
return Bukkit.getWorld(worldName);
}
@Override
public String getName() {
return "bukkit-multiverse";
}
}

View File

@ -1,100 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.permissions;
import com.plotsquared.bukkit.player.BukkitPlayer;
import com.plotsquared.core.permissions.ConsolePermissionProfile;
import com.plotsquared.core.permissions.PermissionHandler;
import com.plotsquared.core.permissions.PermissionProfile;
import com.plotsquared.core.player.ConsolePlayer;
import com.plotsquared.core.player.OfflinePlotPlayer;
import com.plotsquared.core.player.PlotPlayer;
import org.bukkit.entity.Player;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.lang.ref.WeakReference;
import java.util.EnumSet;
import java.util.Optional;
import java.util.Set;
public class BukkitPermissionHandler implements PermissionHandler {
@Override
public void initialize() {
}
@NonNull
@Override
public Optional<PermissionProfile> getPermissionProfile(
@NonNull PlotPlayer<?> playerPlotPlayer
) {
if (playerPlotPlayer instanceof final BukkitPlayer bukkitPlayer) {
return Optional.of(new BukkitPermissionProfile(bukkitPlayer.getPlatformPlayer()));
} else if (playerPlotPlayer instanceof ConsolePlayer) {
return Optional.of(ConsolePermissionProfile.INSTANCE);
}
return Optional.empty();
}
@NonNull
@Override
public Optional<PermissionProfile> getPermissionProfile(
@NonNull OfflinePlotPlayer offlinePlotPlayer
) {
return Optional.empty();
}
@NonNull
@Override
public Set<PermissionHandlerCapability> getCapabilities() {
return EnumSet.of(PermissionHandlerCapability.ONLINE_PERMISSIONS);
}
private static final class BukkitPermissionProfile implements PermissionProfile {
private final WeakReference<Player> playerReference;
private BukkitPermissionProfile(final @NonNull Player player) {
this.playerReference = new WeakReference<>(player);
}
@Override
public boolean hasPermission(
final @Nullable String world,
final @NonNull String permission
) {
final Player player = this.playerReference.get();
return player != null && player.hasPermission(permission);
}
@Override
public boolean hasKeyedPermission(
final @Nullable String world,
final @NonNull String stub,
final @NonNull String key
) {
final Player player = this.playerReference.get();
return player != null && (player.hasPermission(stub + "." + key) || player.hasPermission(stub + ".*"));
}
}
}

View File

@ -1,135 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.permissions;
import com.plotsquared.bukkit.player.BukkitOfflinePlayer;
import com.plotsquared.bukkit.player.BukkitPlayer;
import com.plotsquared.core.permissions.ConsolePermissionProfile;
import com.plotsquared.core.permissions.PermissionHandler;
import com.plotsquared.core.permissions.PermissionProfile;
import com.plotsquared.core.player.ConsolePlayer;
import com.plotsquared.core.player.OfflinePlotPlayer;
import com.plotsquared.core.player.PlotPlayer;
import net.milkbowl.vault.permission.Permission;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.EnumSet;
import java.util.Optional;
import java.util.Set;
public class VaultPermissionHandler implements PermissionHandler {
private Permission permissions;
@Override
public void initialize() {
if (Bukkit.getServer().getPluginManager().getPlugin("Vault") == null) {
throw new IllegalStateException("Vault is not present on the server");
}
RegisteredServiceProvider<Permission> permissionProvider =
Bukkit.getServer().getServicesManager().getRegistration(Permission.class);
if (permissionProvider != null) {
this.permissions = permissionProvider.getProvider();
}
}
@NonNull
@Override
public Optional<PermissionProfile> getPermissionProfile(
@NonNull PlotPlayer<?> playerPlotPlayer
) {
if (playerPlotPlayer instanceof final BukkitPlayer bukkitPlayer) {
return Optional.of(new VaultPermissionProfile(bukkitPlayer.getPlatformPlayer()));
} else if (playerPlotPlayer instanceof ConsolePlayer) {
return Optional.of(ConsolePermissionProfile.INSTANCE);
}
return Optional.empty();
}
@NonNull
@Override
public Optional<PermissionProfile> getPermissionProfile(
@NonNull OfflinePlotPlayer offlinePlotPlayer
) {
if (offlinePlotPlayer instanceof BukkitOfflinePlayer) {
return Optional.of(new VaultPermissionProfile(((BukkitOfflinePlayer) offlinePlotPlayer).player));
}
return Optional.empty();
}
@NonNull
@Override
public Set<PermissionHandlerCapability> getCapabilities() {
return EnumSet.of(
PermissionHandlerCapability.PER_WORLD_PERMISSIONS,
PermissionHandlerCapability.ONLINE_PERMISSIONS,
PermissionHandlerCapability.OFFLINE_PERMISSIONS
);
}
private final class VaultPermissionProfile implements PermissionProfile {
private final OfflinePlayer offlinePlayer;
private VaultPermissionProfile(final @NonNull OfflinePlayer offlinePlayer) {
this.offlinePlayer = offlinePlayer;
}
@Override
public boolean hasPermission(
final @Nullable String world,
final @NonNull String permission
) {
if (permissions == null) {
return false;
}
if (world == null && offlinePlayer instanceof BukkitPlayer) {
return permissions.playerHas(((BukkitPlayer) offlinePlayer).getPlatformPlayer(), permission);
}
return permissions.playerHas(world, offlinePlayer, permission);
}
@Override
public boolean hasKeyedPermission(
final @Nullable String world,
final @NonNull String stub,
final @NonNull String key
) {
if (permissions == null) {
return false;
}
if (world == null && offlinePlayer instanceof BukkitPlayer) {
return permissions.playerHas(
((BukkitPlayer) offlinePlayer).getPlatformPlayer(),
stub + ".*"
) || permissions.playerHas(((BukkitPlayer) offlinePlayer).getPlatformPlayer(), stub + "." + key);
}
return permissions.playerHas(world, offlinePlayer, stub + ".*") || permissions.playerHas(world, offlinePlayer,
stub + "." + key
);
}
}
}

View File

@ -1,73 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.placeholder;
import be.maximvdw.placeholderapi.PlaceholderAPI;
import com.google.common.eventbus.Subscribe;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.util.placeholders.Placeholder;
import com.plotsquared.core.util.placeholders.PlaceholderRegistry;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.checkerframework.checker.nullness.qual.NonNull;
/**
* Placeholder support for MVdWPlaceholderAPI
*/
public class MVdWPlaceholders {
private static final String PREFIX = "plotsquared_";
private final Plugin plugin;
private final PlaceholderRegistry registry;
public MVdWPlaceholders(
final @NonNull Plugin plugin,
final @NonNull PlaceholderRegistry registry
) {
this.plugin = plugin;
this.registry = registry;
for (final Placeholder placeholder : registry.getPlaceholders()) {
this.addPlaceholder(placeholder);
}
PlotSquared.get().getEventDispatcher().registerListener(this);
}
@Subscribe
public void onNewPlaceholder(final PlaceholderRegistry.@NonNull PlaceholderAddedEvent event) {
this.addPlaceholder(event.getPlaceholder());
}
private void addPlaceholder(final @NonNull Placeholder placeholder) {
PlaceholderAPI.registerPlaceholder(
plugin,
PREFIX + String.format("%s", placeholder.getKey()),
placeholderReplaceEvent -> {
if (!placeholderReplaceEvent.isOnline() || placeholderReplaceEvent.getPlayer() == null) {
return "";
}
final PlotPlayer<Player> player = BukkitUtil.adapt(placeholderReplaceEvent.getPlayer());
String key = placeholderReplaceEvent.getPlaceholder().substring(PREFIX.length());
return registry.getPlaceholderValue(key, player);
}
);
}
}

View File

@ -1,90 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.placeholder;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.player.PlotPlayer;
import me.clip.placeholderapi.PlaceholderAPIPlugin;
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import org.bukkit.entity.Player;
public class PAPIPlaceholders extends PlaceholderExpansion {
public PAPIPlaceholders() {
}
@Override
public boolean persist() {
return true;
}
@Override
public boolean canRegister() {
return true;
}
@Override
public String getAuthor() {
return "IntellectualSites";
}
@Override
public String getIdentifier() {
return "plotsquared";
}
@Override
public String getVersion() {
return "3";
}
@Override
public String onPlaceholderRequest(Player p, String identifier) {
final PlotPlayer<?> pl = PlotSquared.platform().playerManager().getPlayerIfExists(p.getUniqueId());
if (pl == null) {
return "";
}
// PAPI specific ones that don't translate well over into other placeholder APIs
if (identifier.startsWith("has_plot_")) {
identifier = identifier.substring("has_plot_".length());
if (identifier.isEmpty()) {
return "";
}
return pl.getPlotCount(identifier) > 0 ?
PlaceholderAPIPlugin.booleanTrue() :
PlaceholderAPIPlugin.booleanFalse();
}
if (identifier.startsWith("plot_count_")) {
identifier = identifier.substring("plot_count_".length());
if (identifier.isEmpty()) {
return "";
}
return String.valueOf(pl.getPlotCount(identifier));
}
// PlotSquared placeholders
return PlotSquared.platform().placeholderRegistry().getPlaceholderValue(identifier, pl);
}
}

View File

@ -1,43 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.placeholder;
import com.plotsquared.bukkit.player.BukkitPlayer;
import com.plotsquared.core.configuration.caption.ChatFormatter;
import com.plotsquared.core.player.PlotPlayer;
import me.clip.placeholderapi.PlaceholderAPI;
import org.bukkit.entity.Player;
import org.checkerframework.checker.nullness.qual.NonNull;
public class PlaceholderFormatter implements ChatFormatter {
@Override
public void format(final @NonNull ChatContext context) {
final PlotPlayer<?> recipient = context.getRecipient();
if (recipient instanceof BukkitPlayer) {
if (context.isRawOutput()) {
context.setMessage(context.getMessage().replace('%', '\u2010'));
} else {
final Player player = ((BukkitPlayer) recipient).player;
context.setMessage(PlaceholderAPI.setPlaceholders(player, context.getMessage()));
}
}
}
}

View File

@ -1,95 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.player;
import com.plotsquared.core.permissions.NullPermissionProfile;
import com.plotsquared.core.permissions.PermissionHandler;
import com.plotsquared.core.permissions.PermissionProfile;
import com.plotsquared.core.player.OfflinePlotPlayer;
import org.bukkit.OfflinePlayer;
import org.checkerframework.checker.index.qual.NonNegative;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.UUID;
public class BukkitOfflinePlayer implements OfflinePlotPlayer {
public final OfflinePlayer player;
private final PermissionProfile permissionProfile;
/**
* Please do not use this method. Instead use BukkitUtil.getPlayer(Player),
* as it caches player objects.
*
* @param player Bukkit OfflinePlayer player to convert
* @param permissionHandler Permission Profile to be used
*/
public BukkitOfflinePlayer(
final @NonNull OfflinePlayer player, final @NonNull
PermissionHandler permissionHandler
) {
this.player = player;
this.permissionProfile = permissionHandler.getPermissionProfile(this)
.orElse(NullPermissionProfile.INSTANCE);
}
@NonNull
@Override
public UUID getUUID() {
return this.player.getUniqueId();
}
@Override
@NonNegative
public long getLastPlayed() {
return this.player.getLastSeen();
}
@Override
public String getName() {
return this.player.getName();
}
@Override
public boolean hasPermission(
final @Nullable String world,
final @NonNull String permission
) {
return this.permissionProfile.hasPermission(world, permission);
}
@Override
public boolean hasKeyedPermission(
final @Nullable String world,
final @NonNull String stub,
final @NonNull String key
) {
return this.permissionProfile.hasPermission(world, stub + "." + key) || this.permissionProfile.hasPermission(
world,
stub + ".*"
);
}
@Override
public boolean hasPermission(@NonNull final String permission, final boolean notify) {
return hasPermission(permission);
}
}

View File

@ -1,394 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.player;
import com.google.common.base.Charsets;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.events.TeleportCause;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.permissions.Permission;
import com.plotsquared.core.permissions.PermissionHandler;
import com.plotsquared.core.player.ConsolePlayer;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.PlotWeather;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.MathMan;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.world.item.ItemType;
import com.sk89q.worldedit.world.item.ItemTypes;
import io.papermc.lib.PaperLib;
import net.kyori.adventure.audience.Audience;
import org.bukkit.GameMode;
import org.bukkit.Sound;
import org.bukkit.WeatherType;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.EventException;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.permissions.PermissionAttachmentInfo;
import org.bukkit.plugin.RegisteredListener;
import org.bukkit.potion.PotionEffectType;
import org.checkerframework.checker.index.qual.NonNegative;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.Arrays;
import java.util.Set;
import java.util.UUID;
import static com.sk89q.worldedit.world.gamemode.GameModes.ADVENTURE;
import static com.sk89q.worldedit.world.gamemode.GameModes.CREATIVE;
import static com.sk89q.worldedit.world.gamemode.GameModes.SPECTATOR;
import static com.sk89q.worldedit.world.gamemode.GameModes.SURVIVAL;
public class BukkitPlayer extends PlotPlayer<Player> {
private static boolean CHECK_EFFECTIVE = true;
public final Player player;
private String name;
/**
* @param plotAreaManager PlotAreaManager instance
* @param eventDispatcher EventDispatcher instance
* @param player Bukkit player instance
* @param permissionHandler PermissionHandler instance
*
* @deprecated Please do not use this method. Instead use {@link BukkitUtil#adapt(Player)}, as it caches player objects.
* This method will be made private in a future release.
*/
@Deprecated(forRemoval = true, since = "6.10.9")
public BukkitPlayer(
final @NonNull PlotAreaManager plotAreaManager, final @NonNull EventDispatcher eventDispatcher,
final @NonNull Player player, final @NonNull PermissionHandler permissionHandler
) {
this(plotAreaManager, eventDispatcher, player, false, permissionHandler);
}
/**
* @param plotAreaManager PlotAreaManager instance
* @param eventDispatcher EventDispatcher instance
* @param player Bukkit player instance
* @param permissionHandler PermissionHandler instance
*
* @deprecated Please do not use this method. Instead use {@link BukkitUtil#adapt(Player)}, as it caches player objects.
* This method will be made private in a future release.
*/
@Deprecated(forRemoval = true, since = "6.10.9")
public BukkitPlayer(
final @NonNull PlotAreaManager plotAreaManager, final @NonNull
EventDispatcher eventDispatcher, final @NonNull Player player,
final boolean realPlayer,
final @NonNull PermissionHandler permissionHandler
) {
super(plotAreaManager, eventDispatcher, permissionHandler);
this.player = player;
this.setupPermissionProfile();
if (realPlayer) {
super.populatePersistentMetaMap();
}
}
@Override
public Actor toActor() {
return BukkitAdapter.adapt(player);
}
@Override
public Player getPlatformPlayer() {
return this.player;
}
@NonNull
@Override
public UUID getUUID() {
if (Settings.UUID.OFFLINE) {
if (Settings.UUID.FORCE_LOWERCASE) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" +
getName().toLowerCase()).getBytes(Charsets.UTF_8));
} else {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" +
getName()).getBytes(Charsets.UTF_8));
}
}
return player.getUniqueId();
}
@Override
@NonNegative
public long getLastPlayed() {
return this.player.getLastSeen();
}
@Override
public boolean canTeleport(final @NonNull Location location) {
final org.bukkit.Location to = BukkitUtil.adapt(location);
final org.bukkit.Location from = player.getLocation();
PlayerTeleportEvent event = new PlayerTeleportEvent(player, from, to);
callEvent(event);
if (event.isCancelled() || !event.getTo().equals(to)) {
return false;
}
event = new PlayerTeleportEvent(player, to, from);
callEvent(event);
return true;
}
private void callEvent(final @NonNull Event event) {
final RegisteredListener[] listeners = event.getHandlers().getRegisteredListeners();
for (final RegisteredListener listener : listeners) {
if (listener.getPlugin().getName().equals(PlotSquared.platform().pluginName())) {
continue;
}
try {
listener.callEvent(event);
} catch (final EventException e) {
e.printStackTrace();
}
}
}
@SuppressWarnings("StringSplitter")
@Override
@NonNegative
public int hasPermissionRange(
final @NonNull String stub,
@NonNegative final int range
) {
if (hasPermission(Permission.PERMISSION_ADMIN.toString())) {
return Integer.MAX_VALUE;
}
final String[] nodes = stub.split("\\.");
final StringBuilder n = new StringBuilder();
for (int i = 0; i < (nodes.length - 1); i++) {
n.append(nodes[i]).append(".");
if (!stub.equals(n + Permission.PERMISSION_STAR.toString())) {
if (hasPermission(n + Permission.PERMISSION_STAR.toString())) {
return Integer.MAX_VALUE;
}
}
}
if (hasPermission(stub + ".*")) {
return Integer.MAX_VALUE;
}
int max = 0;
if (CHECK_EFFECTIVE) {
boolean hasAny = false;
String stubPlus = stub + ".";
final Set<PermissionAttachmentInfo> effective = player.getEffectivePermissions();
if (!effective.isEmpty()) {
for (PermissionAttachmentInfo attach : effective) {
String permStr = attach.getPermission();
if (permStr.startsWith(stubPlus)) {
hasAny = true;
String end = permStr.substring(stubPlus.length());
if (MathMan.isInteger(end)) {
int val = Integer.parseInt(end);
if (val > range) {
return val;
}
if (val > max) {
max = val;
}
}
}
}
if (hasAny) {
return max;
}
// Workaround
for (PermissionAttachmentInfo attach : effective) {
String permStr = attach.getPermission();
if (permStr.startsWith("plots.") && !permStr.equals("plots.use")) {
return max;
}
}
CHECK_EFFECTIVE = false;
}
}
for (int i = range; i > 0; i--) {
if (hasPermission(stub + "." + i)) {
return i;
}
}
return max;
}
@Override
public void teleport(final @NonNull Location location, final @NonNull TeleportCause cause) {
if (Math.abs(location.getX()) >= 30000000 || Math.abs(location.getZ()) >= 30000000) {
return;
}
final org.bukkit.Location bukkitLocation =
new org.bukkit.Location(BukkitUtil.getWorld(location.getWorldName()), location.getX() + 0.5,
location.getY(), location.getZ() + 0.5, location.getYaw(), location.getPitch()
);
PaperLib.teleportAsync(player, bukkitLocation, getTeleportCause(cause));
}
@Override
public String getName() {
if (this.name == null) {
this.name = this.player.getName();
}
return this.name;
}
@Override
public void setCompassTarget(Location location) {
this.player.setCompassTarget(
new org.bukkit.Location(BukkitUtil.getWorld(location.getWorldName()), location.getX(),
location.getY(), location.getZ()
));
}
@Override
public Location getLocationFull() {
return BukkitUtil.adaptComplete(this.player.getLocation());
}
@Override
public void setWeather(final @NonNull PlotWeather weather) {
switch (weather) {
case CLEAR -> this.player.setPlayerWeather(WeatherType.CLEAR);
case RAIN -> this.player.setPlayerWeather(WeatherType.DOWNFALL);
case WORLD -> this.player.resetPlayerWeather();
default -> {
//do nothing as this is PlotWeather.OFF
}
}
}
@Override
public com.sk89q.worldedit.world.gamemode.GameMode getGameMode() {
return switch (this.player.getGameMode()) {
case ADVENTURE -> ADVENTURE;
case CREATIVE -> CREATIVE;
case SPECTATOR -> SPECTATOR;
default -> SURVIVAL;
};
}
@Override
public void setGameMode(final com.sk89q.worldedit.world.gamemode.GameMode gameMode) {
if (ADVENTURE.equals(gameMode)) {
this.player.setGameMode(GameMode.ADVENTURE);
} else if (CREATIVE.equals(gameMode)) {
this.player.setGameMode(GameMode.CREATIVE);
} else if (SPECTATOR.equals(gameMode)) {
this.player.setGameMode(GameMode.SPECTATOR);
} else {
this.player.setGameMode(GameMode.SURVIVAL);
}
}
@Override
public void setTime(final long time) {
if (time != Long.MAX_VALUE) {
this.player.setPlayerTime(time, false);
} else {
this.player.resetPlayerTime();
}
}
@Override
public boolean getFlight() {
return player.getAllowFlight();
}
@Override
public void setFlight(boolean fly) {
this.player.setAllowFlight(fly);
}
@Override
public void playMusic(final @NonNull Location location, final @NonNull ItemType id) {
if (id == ItemTypes.AIR) {
// Let's just stop all the discs because why not?
for (final Sound sound : Arrays.stream(Sound.values())
.filter(sound -> sound.name().contains("DISC")).toList()) {
player.stopSound(sound);
}
// this.player.playEffect(BukkitUtil.getLocation(location), Effect.RECORD_PLAY, Material.AIR);
} else {
// this.player.playEffect(BukkitUtil.getLocation(location), Effect.RECORD_PLAY, id.to(Material.class));
this.player.playSound(BukkitUtil.adapt(location),
Sound.valueOf(BukkitAdapter.adapt(id).name()), Float.MAX_VALUE, 1f
);
}
}
@SuppressWarnings("deprecation") // Needed for Spigot compatibility
@Override
public void kick(final String message) {
this.player.kickPlayer(message);
}
@Override
public void stopSpectating() {
if (getGameMode() == SPECTATOR) {
this.player.setSpectatorTarget(null);
}
}
@Override
public boolean isBanned() {
return this.player.isBanned();
}
@Override
public @NonNull Audience getAudience() {
return BukkitUtil.BUKKIT_AUDIENCES.player(this.player);
}
@Override
public void removeEffect(@NonNull String name) {
PotionEffectType type = PotionEffectType.getByName(name);
if (type != null) {
player.removePotionEffect(type);
}
}
@Override
public boolean canSee(final PlotPlayer<?> other) {
if (other instanceof ConsolePlayer) {
return true;
} else {
return this.player.canSee(((BukkitPlayer) other).getPlatformPlayer());
}
}
/**
* Convert from PlotSquared's {@link TeleportCause} to Bukkit's {@link PlayerTeleportEvent.TeleportCause}
*
* @param cause PlotSquared teleport cause to convert
* @return Bukkit's equivalent teleport cause
*/
public PlayerTeleportEvent.TeleportCause getTeleportCause(final @NonNull TeleportCause cause) {
if (TeleportCause.CauseSets.COMMAND.contains(cause)) {
return PlayerTeleportEvent.TeleportCause.COMMAND;
} else if (cause == TeleportCause.UNKNOWN) {
return PlayerTeleportEvent.TeleportCause.UNKNOWN;
}
return PlayerTeleportEvent.TeleportCause.PLUGIN;
}
}

View File

@ -1,93 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.player;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.plotsquared.core.permissions.PermissionHandler;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.PlayerManager;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.UUID;
/**
* Player manager providing {@link BukkitPlayer Bukkit players}
*/
@Singleton
public class BukkitPlayerManager extends PlayerManager<BukkitPlayer, Player> {
private final PlotAreaManager plotAreaManager;
private final EventDispatcher eventDispatcher;
private final PermissionHandler permissionHandler;
@Inject
public BukkitPlayerManager(
final @NonNull PlotAreaManager plotAreaManager,
final @NonNull EventDispatcher eventDispatcher,
final @NonNull PermissionHandler permissionHandler
) {
this.plotAreaManager = plotAreaManager;
this.eventDispatcher = eventDispatcher;
this.permissionHandler = permissionHandler;
}
@NonNull
@Override
@SuppressWarnings("deprecation")
public BukkitPlayer getPlayer(final @NonNull Player object) {
if (object.getUniqueId().version() == 2) { // not a real player
return new BukkitPlayer(this.plotAreaManager, this.eventDispatcher, object, false, this.permissionHandler);
}
if (!object.isOnline()) {
throw new NoSuchPlayerException(object.getUniqueId());
}
return getPlayer(object.getUniqueId());
}
@Override
@SuppressWarnings("deprecation")
public @NonNull BukkitPlayer createPlayer(final @NonNull UUID uuid) {
final Player player = Bukkit.getPlayer(uuid);
if (player == null || !player.isOnline()) {
throw new NoSuchPlayerException(uuid);
}
return new BukkitPlayer(this.plotAreaManager, this.eventDispatcher, player, this.permissionHandler);
}
@Nullable
@Override
public BukkitOfflinePlayer getOfflinePlayer(final @Nullable UUID uuid) {
if (uuid == null) {
return null;
}
return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(uuid), this.permissionHandler);
}
@NonNull
@Override
public BukkitOfflinePlayer getOfflinePlayer(final @NonNull String username) {
return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(username), this.permissionHandler);
}
}

View File

@ -1,283 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.queue;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import com.plotsquared.bukkit.BukkitPlatform;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.queue.ChunkCoordinator;
import com.plotsquared.core.queue.subscriber.ProgressSubscriber;
import com.plotsquared.core.util.task.PlotSquaredTask;
import com.plotsquared.core.util.task.TaskManager;
import com.plotsquared.core.util.task.TaskTime;
import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.world.World;
import io.papermc.lib.PaperLib;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
/**
* Utility that allows for the loading and coordination of chunk actions
* <p>
* The coordinator takes in collection of chunk coordinates, loads them
* and allows the caller to specify a sink for the loaded chunks. The
* coordinator will prevent the chunks from being unloaded until the sink
* has fully consumed the chunk
* </p>
**/
public final class BukkitChunkCoordinator extends ChunkCoordinator {
private final List<ProgressSubscriber> progressSubscribers = new LinkedList<>();
private final Queue<BlockVector2> requestedChunks;
private final Queue<Chunk> availableChunks;
private final long maxIterationTime;
private final Plugin plugin;
private final Consumer<BlockVector2> chunkConsumer;
private final org.bukkit.World bukkitWorld;
private final Runnable whenDone;
private final Consumer<Throwable> throwableConsumer;
private final boolean unloadAfter;
private final int totalSize;
private final AtomicInteger expectedSize;
private final AtomicInteger loadingChunks = new AtomicInteger();
private final boolean forceSync;
private int batchSize;
private PlotSquaredTask task;
private volatile boolean shouldCancel;
private boolean finished;
@Inject
private BukkitChunkCoordinator(
@Assisted final long maxIterationTime,
@Assisted final int initialBatchSize,
@Assisted final @NonNull Consumer<BlockVector2> chunkConsumer,
@Assisted final @NonNull World world,
@Assisted final @NonNull Collection<BlockVector2> requestedChunks,
@Assisted final @NonNull Runnable whenDone,
@Assisted final @NonNull Consumer<Throwable> throwableConsumer,
@Assisted("unloadAfter") final boolean unloadAfter,
@Assisted final @NonNull Collection<ProgressSubscriber> progressSubscribers,
@Assisted("forceSync") final boolean forceSync
) {
this.requestedChunks = new LinkedBlockingQueue<>(requestedChunks);
this.availableChunks = new LinkedBlockingQueue<>();
this.totalSize = requestedChunks.size();
this.expectedSize = new AtomicInteger(this.totalSize);
this.batchSize = initialBatchSize;
this.chunkConsumer = chunkConsumer;
this.maxIterationTime = maxIterationTime;
this.whenDone = whenDone;
this.throwableConsumer = throwableConsumer;
this.unloadAfter = unloadAfter;
this.plugin = JavaPlugin.getPlugin(BukkitPlatform.class);
this.bukkitWorld = Bukkit.getWorld(world.getName());
this.progressSubscribers.addAll(progressSubscribers);
this.forceSync = forceSync;
}
@Override
public void start() {
if (!forceSync) {
// Request initial batch
this.requestBatch();
// Wait until next tick to give the chunks a chance to be loaded
TaskManager.runTaskLater(() -> task = TaskManager.runTaskRepeat(this, TaskTime.ticks(1)), TaskTime.ticks(1));
} else {
try {
while (!shouldCancel && !requestedChunks.isEmpty()) {
chunkConsumer.accept(requestedChunks.poll());
}
} catch (Throwable t) {
throwableConsumer.accept(t);
} finally {
finish();
}
}
}
@Override
public void cancel() {
shouldCancel = true;
}
private void finish() {
try {
this.whenDone.run();
} catch (final Throwable throwable) {
this.throwableConsumer.accept(throwable);
} finally {
for (final ProgressSubscriber subscriber : this.progressSubscribers) {
subscriber.notifyEnd();
}
if (task != null) {
task.cancel();
}
finished = true;
}
}
@Override
public void run() {
if (shouldCancel) {
if (unloadAfter) {
Chunk chunk;
while ((chunk = availableChunks.poll()) != null) {
freeChunk(chunk);
}
}
finish();
return;
}
Chunk chunk = this.availableChunks.poll();
if (chunk == null) {
if (this.availableChunks.isEmpty()) {
if (this.requestedChunks.isEmpty() && loadingChunks.get() == 0) {
finish();
} else {
requestBatch();
}
}
return;
}
long[] iterationTime = new long[2];
int processedChunks = 0;
do {
final long start = System.currentTimeMillis();
try {
this.chunkConsumer.accept(BlockVector2.at(chunk.getX(), chunk.getZ()));
} catch (final Throwable throwable) {
this.throwableConsumer.accept(throwable);
}
if (unloadAfter) {
this.freeChunk(chunk);
}
processedChunks++;
final long end = System.currentTimeMillis();
// Update iteration time
iterationTime[0] = iterationTime[1];
iterationTime[1] = end - start;
} while (iterationTime[0] + iterationTime[1] < this.maxIterationTime * 2 && (chunk = availableChunks.poll()) != null);
if (processedChunks < this.batchSize) {
// Adjust batch size based on the amount of processed chunks per tick
this.batchSize = processedChunks;
}
final int expected = this.expectedSize.addAndGet(-processedChunks);
if (expected <= 0) {
finish();
} else {
if (this.availableChunks.size() < processedChunks) {
final double progress = ((double) totalSize - (double) expected) / (double) totalSize;
for (final ProgressSubscriber subscriber : this.progressSubscribers) {
subscriber.notifyProgress(this, progress);
}
this.requestBatch();
}
}
}
/**
* Requests a batch of chunks to be loaded
*/
private void requestBatch() {
BlockVector2 chunk;
for (int i = 0; i < this.batchSize && (chunk = this.requestedChunks.poll()) != null; i++) {
// This required PaperLib to be bumped to version 1.0.4 to mark the request as urgent
loadingChunks.incrementAndGet();
PaperLib
.getChunkAtAsync(this.bukkitWorld, chunk.getX(), chunk.getZ(), true, true)
.whenComplete((chunkObject, throwable) -> {
loadingChunks.decrementAndGet();
if (throwable != null) {
throwable.printStackTrace();
// We want one less because this couldn't be processed
this.expectedSize.decrementAndGet();
} else if (PlotSquared.get().isMainThread(Thread.currentThread())) {
this.processChunk(chunkObject);
} else {
TaskManager.runTask(() -> this.processChunk(chunkObject));
}
});
}
}
/**
* Once a chunk has been loaded, process it (add a plugin ticket and add to
* available chunks list). It is important that this gets executed on the
* server's main thread.
*/
private void processChunk(final @NonNull Chunk chunk) {
/* Chunk#isLoaded does not necessarily return true shortly after PaperLib#getChunkAtAsync completes, but the chunk is
still loaded.
if (!chunk.isLoaded()) {
throw new IllegalArgumentException(String.format("Chunk %d;%d is is not loaded", chunk.getX(), chunk.getZ());
}*/
if (finished) {
return;
}
chunk.addPluginChunkTicket(this.plugin);
this.availableChunks.add(chunk);
}
/**
* Once a chunk has been used, free it up for unload by removing the plugin ticket
*/
private void freeChunk(final @NonNull Chunk chunk) {
if (!chunk.isLoaded()) {
throw new IllegalArgumentException(String.format("Chunk %d;%d is is not loaded", chunk.getX(), chunk.getZ()));
}
chunk.removePluginChunkTicket(this.plugin);
}
@Override
public int getRemainingChunks() {
return this.expectedSize.get();
}
@Override
public int getTotalChunks() {
return this.totalSize;
}
/**
* Subscribe to coordinator progress updates
*
* @param subscriber Subscriber
*/
public void subscribeToProgress(final @NonNull ProgressSubscriber subscriber) {
this.progressSubscribers.add(subscriber);
}
}

View File

@ -1,402 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.queue;
import com.google.inject.Inject;
import com.plotsquared.bukkit.schematic.StateWrapper;
import com.plotsquared.bukkit.util.BukkitBlockUtil;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.inject.factory.ChunkCoordinatorBuilderFactory;
import com.plotsquared.core.inject.factory.ChunkCoordinatorFactory;
import com.plotsquared.core.queue.BasicQueueCoordinator;
import com.plotsquared.core.queue.ChunkCoordinator;
import com.plotsquared.core.queue.LocalChunk;
import com.plotsquared.core.util.ChunkUtil;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard;
import com.sk89q.worldedit.extent.clipboard.Clipboard;
import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.SideEffect;
import com.sk89q.worldedit.util.SideEffectSet;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.block.Block;
import org.bukkit.block.Container;
import org.bukkit.block.data.BlockData;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.function.Consumer;
public class BukkitQueueCoordinator extends BasicQueueCoordinator {
private static final SideEffectSet NO_SIDE_EFFECT_SET;
private static final SideEffectSet EDGE_SIDE_EFFECT_SET;
private static final SideEffectSet LIGHTING_SIDE_EFFECT_SET;
private static final SideEffectSet EDGE_LIGHTING_SIDE_EFFECT_SET;
static {
NO_SIDE_EFFECT_SET = SideEffectSet.none().with(SideEffect.LIGHTING, SideEffect.State.OFF).with(
SideEffect.NEIGHBORS,
SideEffect.State.OFF
);
EDGE_SIDE_EFFECT_SET = SideEffectSet.none().with(SideEffect.UPDATE, SideEffect.State.ON).with(
SideEffect.NEIGHBORS,
SideEffect.State.ON
);
LIGHTING_SIDE_EFFECT_SET = SideEffectSet.none().with(SideEffect.NEIGHBORS, SideEffect.State.OFF);
EDGE_LIGHTING_SIDE_EFFECT_SET = SideEffectSet.none().with(SideEffect.UPDATE, SideEffect.State.ON).with(
SideEffect.NEIGHBORS,
SideEffect.State.ON
);
}
private org.bukkit.World bukkitWorld;
@Inject
private ChunkCoordinatorBuilderFactory chunkCoordinatorBuilderFactory;
@Inject
private ChunkCoordinatorFactory chunkCoordinatorFactory;
private ChunkCoordinator chunkCoordinator;
@Inject
public BukkitQueueCoordinator(@NonNull World world) {
super(world);
}
@Override
public BlockState getBlock(int x, int y, int z) {
Block block = getBukkitWorld().getBlockAt(x, y, z);
return BukkitBlockUtil.get(block);
}
@Override
public void start() {
chunkCoordinator.start();
}
@Override
public void cancel() {
chunkCoordinator.cancel();
}
@Override
public boolean enqueue() {
final Clipboard regenClipboard;
if (isRegen()) {
BlockVector3 start = BlockVector3.at(getRegenStart()[0] << 4, getMinY(), getRegenStart()[1] << 4);
BlockVector3 end = BlockVector3.at((getRegenEnd()[0] << 4) + 15, getMaxY(), (getRegenEnd()[1] << 4) + 15);
Region region = new CuboidRegion(start, end);
regenClipboard = new BlockArrayClipboard(region);
regenClipboard.setOrigin(start);
getWorld().regenerate(region, regenClipboard);
} else if (getRegenRegion() != null) {
regenClipboard = new BlockArrayClipboard(getRegenRegion());
regenClipboard.setOrigin(getRegenRegion().getMinimumPoint());
getWorld().regenerate(getRegenRegion(), regenClipboard);
} else {
regenClipboard = null;
}
Consumer<BlockVector2> consumer = getChunkConsumer();
if (consumer == null) {
consumer = blockVector2 -> {
LocalChunk localChunk = getBlockChunks().get(blockVector2);
boolean isRegenChunk =
regenClipboard != null && blockVector2.getBlockX() > getRegenStart()[0] && blockVector2.getBlockZ() > getRegenStart()[1]
&& blockVector2.getBlockX() < getRegenEnd()[0] && blockVector2.getBlockZ() < getRegenEnd()[1];
int sx = blockVector2.getX() << 4;
int sz = blockVector2.getZ() << 4;
if (isRegenChunk) {
for (int layer = getMinLayer(); layer <= getMaxLayer(); layer++) {
for (int y = 0; y < 16; y++) {
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
x += sx;
y += layer << 4;
z += sz;
BaseBlock block = regenClipboard.getFullBlock(BlockVector3.at(x, y, z));
if (block != null) {
boolean edge = Settings.QUEUE.UPDATE_EDGES && isEdgeRegen(x & 15, z & 15, blockVector2);
setWorldBlock(x, y, z, block, blockVector2, edge);
}
}
}
}
}
}
// Allow regen and then blocks to be placed (plot schematic etc)
if (localChunk == null) {
return;
}
for (int layer = 0; layer < localChunk.getBaseblocks().length; layer++) {
BaseBlock[] blocksLayer = localChunk.getBaseblocks()[layer];
if (blocksLayer == null) {
continue;
}
for (int j = 0; j < blocksLayer.length; j++) {
if (blocksLayer[j] == null) {
continue;
}
BaseBlock block = blocksLayer[j];
if (block != null) {
int lx = ChunkUtil.getX(j);
int lz = ChunkUtil.getZ(j);
int x = sx + lx;
int y = ChunkUtil.getY(layer + localChunk.getMinSection(), j);
int z = sz + lz;
boolean edge = Settings.QUEUE.UPDATE_EDGES && isEdge(y >> 4, lx, y & 15, lz, blockVector2,
localChunk
);
setWorldBlock(x, y, z, block, blockVector2, edge);
}
}
}
for (int layer = 0; layer < localChunk.getBiomes().length; layer++) {
BiomeType[] biomesLayer = localChunk.getBiomes()[layer];
if (biomesLayer == null) {
continue;
}
for (int j = 0; j < biomesLayer.length; j++) {
if (biomesLayer[j] == null) {
continue;
}
BiomeType biome = biomesLayer[j];
if (biome != null) {
int x = sx + ChunkUtil.getX(j);
int y = ChunkUtil.getY(layer, j);
int z = sz + ChunkUtil.getZ(j);
getWorld().setBiome(BlockVector3.at(x, y, z), biome);
}
}
}
if (localChunk.getTiles().size() > 0) {
localChunk.getTiles().forEach((blockVector3, tag) -> {
try {
BaseBlock block = getWorld().getBlock(blockVector3).toBaseBlock(tag);
getWorld().setBlock(blockVector3, block, getSideEffectSet(SideEffectState.NONE));
} catch (WorldEditException ignored) {
StateWrapper sw = new StateWrapper(tag);
sw.restoreTag(getWorld().getName(), blockVector3.getX(), blockVector3.getY(), blockVector3.getZ());
}
});
}
if (localChunk.getEntities().size() > 0) {
localChunk.getEntities().forEach((location, entity) -> getWorld().createEntity(location, entity));
}
};
}
Collection<BlockVector2> read = new ArrayList<>();
if (getReadChunks().size() > 0) {
read.addAll(getReadChunks());
}
chunkCoordinator =
chunkCoordinatorBuilderFactory
.create(chunkCoordinatorFactory)
.inWorld(getWorld())
.withChunks(getBlockChunks().keySet())
.withChunks(read)
.withInitialBatchSize(3)
.withMaxIterationTime(40)
.withThrowableConsumer(Throwable::printStackTrace)
.withFinalAction(getCompleteTask())
.withConsumer(consumer)
.unloadAfter(isUnloadAfter())
.withProgressSubscribers(getProgressSubscribers())
.forceSync(isForceSync())
.build();
return super.enqueue();
}
/**
* Set a block to the world. First tries WNA but defaults to normal block setting methods if that fails
*/
@SuppressWarnings("unused")
private void setWorldBlock(int x, int y, int z, @NonNull BaseBlock block, @NonNull BlockVector2 blockVector2, boolean edge) {
try {
BlockVector3 loc = BlockVector3.at(x, y, z);
boolean lighting = false;
switch (getLightingMode()) {
case NONE:
break;
case PLACEMENT:
lighting = block.getBlockType().getMaterial().getLightValue() > 0;
break;
case REPLACEMENT:
lighting = block.getBlockType().getMaterial().getLightValue() > 0
|| getWorld().getBlock(loc).getBlockType().getMaterial().getLightValue() > 0;
break;
default:
// Can only be "all"
lighting = true;
}
SideEffectSet sideEffectSet;
if (lighting) {
sideEffectSet = getSideEffectSet(edge ? SideEffectState.EDGE_LIGHTING : SideEffectState.LIGHTING);
} else {
sideEffectSet = getSideEffectSet(edge ? SideEffectState.EDGE : SideEffectState.NONE);
}
getWorld().setBlock(loc, block, sideEffectSet);
} catch (WorldEditException ignored) {
// Fallback to not so nice method
BlockData blockData = BukkitAdapter.adapt(block);
Block existing;
// Assume a chunk object has been given only when it should have been.
if (getChunkObject() instanceof Chunk chunkObject) {
existing = chunkObject.getBlock(x & 15, y, z & 15);
} else {
existing = getBukkitWorld().getBlockAt(x, y, z);
}
final BlockState existingBaseBlock = BukkitAdapter.adapt(existing.getBlockData());
if (BukkitBlockUtil.get(existing).equals(existingBaseBlock) && existing.getBlockData().matches(blockData)) {
return;
}
if (existing.getState() instanceof Container) {
((Container) existing.getState()).getInventory().clear();
}
existing.setType(BukkitAdapter.adapt(block.getBlockType()), false);
existing.setBlockData(blockData, false);
if (block.hasNbtData()) {
CompoundTag tag = block.getNbtData();
StateWrapper sw = new StateWrapper(tag);
sw.restoreTag(existing);
}
}
}
private org.bukkit.World getBukkitWorld() {
if (bukkitWorld == null) {
bukkitWorld = Bukkit.getWorld(getWorld().getName());
}
return bukkitWorld;
}
private boolean isEdge(int layer, int x, int y, int z, BlockVector2 blockVector2, LocalChunk localChunk) {
int layerIndex = (layer - localChunk.getMinSection());
if (layer == localChunk.getMinSection() || layerIndex == localChunk.getBaseblocks().length - 1) {
return false;
}
if (x == 0) {
LocalChunk localChunkX = getBlockChunks().get(blockVector2.withX(blockVector2.getX() - 1));
if (localChunkX == null || localChunkX.getBaseblocks()[layerIndex] == null ||
localChunkX.getBaseblocks()[layerIndex][ChunkUtil.getJ(15, y, z)] != null) {
return true;
}
} else if (x == 15) {
LocalChunk localChunkX = getBlockChunks().get(blockVector2.withX(blockVector2.getX() + 1));
if (localChunkX == null || localChunkX.getBaseblocks()[layerIndex] == null ||
localChunkX.getBaseblocks()[layerIndex][ChunkUtil.getJ(0, y, z)] != null) {
return true;
}
}
if (z == 0) {
LocalChunk localChunkZ = getBlockChunks().get(blockVector2.withZ(blockVector2.getZ() - 1));
if (localChunkZ == null || localChunkZ.getBaseblocks()[layerIndex] == null ||
localChunkZ.getBaseblocks()[layerIndex][ChunkUtil.getJ(x, y, 15)] != null) {
return true;
}
} else if (z == 15) {
LocalChunk localChunkZ = getBlockChunks().get(blockVector2.withZ(blockVector2.getZ() + 1));
if (localChunkZ == null || localChunkZ.getBaseblocks()[layerIndex] == null ||
localChunkZ.getBaseblocks()[layerIndex][ChunkUtil.getJ(x, y, 0)] != null) {
return true;
}
}
if (y == 0) {
if (localChunk.getBaseblocks()[layerIndex - 1] == null ||
localChunk.getBaseblocks()[layerIndex][ChunkUtil.getJ(x, 15, z)] != null) {
return true;
}
} else if (y == 15) {
if (localChunk.getBaseblocks()[layerIndex + 1] == null ||
localChunk.getBaseblocks()[layerIndex][ChunkUtil.getJ(x, 0, z)] != null) {
return true;
}
}
BaseBlock[] baseBlocks = localChunk.getBaseblocks()[layerIndex];
if (x > 0 && baseBlocks[ChunkUtil.getJ(x - 1, y, z)] == null) {
return true;
}
if (x < 15 && baseBlocks[ChunkUtil.getJ(x + 1, y, z)] == null) {
return true;
}
if (y > 0 && baseBlocks[ChunkUtil.getJ(x, y - 1, z)] == null) {
return true;
}
if (y < 15 && baseBlocks[ChunkUtil.getJ(x, y + 1, z)] == null) {
return true;
}
if (z > 0 && baseBlocks[ChunkUtil.getJ(x, y, z - 1)] == null) {
return true;
}
return z < 15 && baseBlocks[ChunkUtil.getJ(x, y, z + 1)] == null;
}
private boolean isEdgeRegen(int x, int z, BlockVector2 blockVector2) {
if (x == 0) {
LocalChunk localChunkX = getBlockChunks().get(blockVector2.withX(blockVector2.getX() - 1));
if (localChunkX == null) {
return true;
}
} else if (x == 15) {
LocalChunk localChunkX = getBlockChunks().get(blockVector2.withX(blockVector2.getX() + 1));
if (localChunkX == null) {
return true;
}
}
if (z == 0) {
return getBlockChunks().get(blockVector2.withZ(blockVector2.getZ() - 1)) == null;
} else if (z == 15) {
return getBlockChunks().get(blockVector2.withZ(blockVector2.getZ() + 1)) == null;
}
return false;
}
private SideEffectSet getSideEffectSet(SideEffectState state) {
if (getSideEffectSet() != null) {
return getSideEffectSet();
}
return switch (state) {
case NONE -> NO_SIDE_EFFECT_SET;
case EDGE -> EDGE_SIDE_EFFECT_SET;
case LIGHTING -> LIGHTING_SIDE_EFFECT_SET;
case EDGE_LIGHTING -> EDGE_LIGHTING_SIDE_EFFECT_SET;
};
}
private enum SideEffectState {
NONE,
EDGE,
LIGHTING,
EDGE_LIGHTING
}
}

View File

@ -1,281 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.queue;
import com.google.common.base.Preconditions;
import com.intellectualsites.annotations.DoNotUse;
import com.plotsquared.bukkit.util.BukkitBlockUtil;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.core.location.ChunkWrapper;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.queue.ScopedQueueCoordinator;
import com.plotsquared.core.util.ChunkUtil;
import com.plotsquared.core.util.PatternUtil;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockTypes;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.generator.ChunkGenerator.BiomeGrid;
import org.bukkit.generator.ChunkGenerator.ChunkData;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.Arrays;
@DoNotUse
public class GenChunk extends ScopedQueueCoordinator {
public final Biome[] biomes;
public BlockState[][] result;
public BiomeGrid biomeGrid;
public Chunk chunk;
public String world;
public int chunkX;
public int chunkZ;
private ChunkData chunkData = null;
/**
* @param minY minimum world Y, inclusive
* @param maxY maximum world Y, inclusive
*
* @since 6.6.0
*/
public GenChunk(int minY, int maxY) {
super(null, Location.at("", 0, minY, 0), Location.at("", 15, maxY, 15));
this.biomes = Biome.values();
}
public @Nullable ChunkData getChunkData() {
return this.chunkData;
}
/**
* Set the internal Bukkit chunk data
*
* @param chunkData Bukkit ChunkData
*/
public void setChunkData(@NonNull ChunkData chunkData) {
this.chunkData = chunkData;
}
public @NonNull Chunk getChunk() {
if (chunk == null) {
World worldObj = BukkitUtil.getWorld(world);
if (worldObj != null) {
this.chunk = worldObj.getChunkAt(chunkX, chunkZ);
}
}
return chunk;
}
/**
* Set the chunk being represented
*
* @param chunk Bukkit Chunk
*/
public void setChunk(@NonNull Chunk chunk) {
this.chunk = chunk;
}
/**
* Set the world and XZ of the chunk being represented via {@link ChunkWrapper}
*
* @param wrap PlotSquared ChunkWrapper
*/
public void setChunk(@NonNull ChunkWrapper wrap) {
chunk = null;
world = wrap.world;
chunkX = wrap.x;
chunkZ = wrap.z;
}
@Override
public void fillBiome(@NonNull BiomeType biomeType) {
if (biomeGrid == null) {
return;
}
Biome biome = BukkitAdapter.adapt(biomeType);
for (int y = getMin().getY(); y <= getMax().getY(); y++) {
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
this.biomeGrid.setBiome(x, y, z, biome);
}
}
}
}
@Override
public void setCuboid(@NonNull Location pos1, @NonNull Location pos2, @NonNull BlockState block) {
if (result != null && pos1.getX() == 0 && pos1.getZ() == 0 && pos2.getX() == 15 && pos2.getZ() == 15) {
for (int y = pos1.getY(); y <= pos2.getY(); y++) {
int layer = getLayerIndex(y);
BlockState[] data = result[layer];
if (data == null) {
result[layer] = data = new BlockState[4096];
}
int start = y << 8;
int end = start + 256;
Arrays.fill(data, start, end, block);
}
}
int minX = Math.min(pos1.getX(), pos2.getX());
int minY = Math.min(pos1.getY(), pos2.getY());
int minZ = Math.min(pos1.getZ(), pos2.getZ());
int maxX = Math.max(pos1.getX(), pos2.getX());
int maxY = Math.max(pos1.getY(), pos2.getY());
int maxZ = Math.max(pos1.getZ(), pos2.getZ());
chunkData.setRegion(minX, minY, minZ, maxX + 1, maxY + 1, maxZ + 1, BukkitAdapter.adapt(block));
}
@Override
public boolean setBiome(int x, int z, @NonNull BiomeType biomeType) {
return setBiome(x, z, BukkitAdapter.adapt(biomeType));
}
/**
* Set the in the whole column of XZ
*
* @param x Relative x location within the chunk (0 - 15)
* @param z Relative z location within the chunk (0 - 15)
* @param biome Bukkit biome to set
* @return if successful
*/
public boolean setBiome(int x, int z, @NonNull Biome biome) {
if (this.biomeGrid != null) {
for (int y = getMin().getY(); y <= getMax().getY(); y++) {
this.setBiome(x, y, z, biome);
}
return true;
}
return false;
}
public boolean setBiome(int x, int y, int z, @NonNull Biome biome) {
if (this.biomeGrid != null) {
this.biomeGrid.setBiome(x, y, z, biome);
return true;
}
return false;
}
@Override
public boolean setBlock(int x, int y, int z, @NonNull Pattern pattern) {
final BaseBlock block = PatternUtil.apply(Preconditions.checkNotNull(
pattern,
"Pattern may not be null"
), x + (chunkX << 4), y, z + (chunkZ << 4));
return setBlock(x, y, z, block);
}
@Override
public boolean setBlock(int x, int y, int z, @NonNull BlockState id) {
if (this.result == null) {
this.chunkData.setBlock(x, y, z, BukkitAdapter.adapt(id));
return true;
}
this.chunkData.setBlock(x, y, z, BukkitAdapter.adapt(id));
this.storeCache(x, y, z, id);
return true;
}
private void storeCache(final int x, final int y, final int z, final @NonNull BlockState id) {
int i = getLayerIndex(y);
BlockState[] v = this.result[i];
if (v == null) {
this.result[i] = v = new BlockState[4096];
}
int j = ChunkUtil.getJ(x, y, z);
v[j] = id;
}
@Override
public boolean setBlock(int x, int y, int z, @NonNull BaseBlock id) {
if (this.result == null) {
this.chunkData.setBlock(x, y, z, BukkitAdapter.adapt(id));
return true;
}
this.chunkData.setBlock(x, y, z, BukkitAdapter.adapt(id));
this.storeCache(x, y, z, id.toImmutableState());
return true;
}
@Override
public @Nullable BlockState getBlock(int x, int y, int z) {
int i = getLayerIndex(y);
if (result == null) {
return BukkitBlockUtil.get(chunkData.getType(x, y, z));
}
BlockState[] array = result[i];
if (array == null) {
return BlockTypes.AIR.getDefaultState();
}
int j = ChunkUtil.getJ(x, y, z);
return array[j];
}
public int getX() {
return chunk == null ? chunkX : chunk.getX();
}
public int getZ() {
return chunk == null ? chunkZ : chunk.getZ();
}
@Override
public com.sk89q.worldedit.world.@NonNull World getWorld() {
return chunk == null ? BukkitAdapter.adapt(Bukkit.getWorld(world)) : BukkitAdapter.adapt(chunk.getWorld());
}
@Override
public @NonNull Location getMax() {
return Location.at(getWorld().getName(), 15 + (getX() << 4), super.getMax().getY(), 15 + (getZ() << 4));
}
@Override
public @NonNull Location getMin() {
return Location.at(getWorld().getName(), getX() << 4, super.getMin().getY(), getZ() << 4);
}
public @NonNull GenChunk clone() {
GenChunk toReturn = new GenChunk(getMin().getY(), getMax().getY());
if (this.result != null) {
for (int i = 0; i < this.result.length; i++) {
BlockState[] matrix = this.result[i];
if (matrix != null) {
toReturn.result[i] = new BlockState[matrix.length];
System.arraycopy(matrix, 0, toReturn.result[i], 0, matrix.length);
}
}
}
toReturn.chunkData = this.chunkData;
return toReturn;
}
private int getLayerIndex(int y) {
return (y - getMin().getY()) >> 4;
}
}

View File

@ -1,130 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.queue;
import com.plotsquared.bukkit.schematic.StateWrapper;
import com.plotsquared.core.queue.DelegateQueueCoordinator;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.entity.Entity;
import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bukkit.Location;
import org.bukkit.entity.EntityType;
import org.bukkit.generator.LimitedRegion;
import org.checkerframework.checker.nullness.qual.NonNull;
/**
* Wraps a {@link LimitedRegion} inside a {@link com.plotsquared.core.queue.QueueCoordinator} so it can be written to.
*
* @since 6.9.0
*/
public class LimitedRegionWrapperQueue extends DelegateQueueCoordinator {
private static final Logger LOGGER = LogManager.getLogger("PlotSquared/" + LimitedRegionWrapperQueue.class.getSimpleName());
private final LimitedRegion limitedRegion;
private boolean useOtherRestoreTagMethod = false;
/**
* @since 6.9.0
*/
public LimitedRegionWrapperQueue(LimitedRegion limitedRegion) {
super(null);
this.limitedRegion = limitedRegion;
}
@Override
public boolean setBlock(final int x, final int y, final int z, @NonNull final Pattern pattern) {
return setBlock(x, y, z, pattern.applyBlock(BlockVector3.at(x, y, z)));
}
@Override
public boolean setBlock(final int x, final int y, final int z, @NonNull final BaseBlock id) {
boolean result = setBlock(x, y, z, id.toImmutableState());
if (result && id.hasNbtData()) {
CompoundTag tag = id.getNbtData();
StateWrapper sw = new StateWrapper(tag);
try {
if (useOtherRestoreTagMethod && getWorld() != null) {
sw.restoreTag(getWorld().getName(), x, y, z);
} else {
sw.restoreTag(limitedRegion.getBlockState(x, y, z).getBlock());
}
} catch (IllegalArgumentException e) {
LOGGER.error("Error attempting to populate tile entity into the world at location {},{},{}", x, y, z, e);
return false;
} catch (IllegalStateException e) {
useOtherRestoreTagMethod = true;
LOGGER.warn("IllegalStateException attempting to populate tile entity into the world at location {},{},{}. " +
"Possibly on <=1.17.1, switching to secondary method.", x, y, z, e);
}
}
return result;
}
@Override
public boolean setBlock(final int x, final int y, final int z, @NonNull final BlockState id) {
try {
limitedRegion.setType(x, y, z, BukkitAdapter.adapt(id.getBlockType()));
limitedRegion.setBlockData(x, y, z, BukkitAdapter.adapt(id));
} catch (IllegalArgumentException e) {
LOGGER.error("Error attempting to populate block into the world at location {},{},{}", x, y, z, e);
return false;
}
return true;
}
@Override
public boolean setEntity(@NonNull final Entity entity) {
EntityType type = BukkitAdapter.adapt(entity.getState().getType());
double x = entity.getLocation().getX();
double y = entity.getLocation().getY();
double z = entity.getLocation().getZ();
Location location = new Location(limitedRegion.getWorld(), x, y, z);
try {
limitedRegion.spawnEntity(location, type);
} catch (IllegalArgumentException e) {
LOGGER.error("Error attempting to populate entity into the world at location {},{},{}", (int) x, (int) y, (int) z, e);
return false;
}
return true;
}
@Override
public boolean setTile(final int x, final int y, final int z, @NonNull final CompoundTag tag) {
StateWrapper sw = new StateWrapper(tag);
try {
return sw.restoreTag(limitedRegion.getBlockState(x, y, z).getBlock());
} catch (IllegalArgumentException e) {
LOGGER.error("Error attempting to populate tile entity into the world at location {},{},{}", x, y, z, e);
return false;
}
}
@Override
public boolean isSettingTiles() {
return true;
}
}

View File

@ -1,46 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.schematic;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.plotsquared.core.inject.factory.ProgressSubscriberFactory;
import com.plotsquared.core.queue.QueueCoordinator;
import com.plotsquared.core.util.SchematicHandler;
import com.plotsquared.core.util.WorldUtil;
import com.sk89q.jnbt.CompoundTag;
import org.checkerframework.checker.nullness.qual.NonNull;
/**
* Schematic Handler.
*/
@Singleton
public class BukkitSchematicHandler extends SchematicHandler {
@Inject
public BukkitSchematicHandler(final @NonNull WorldUtil worldUtil, @NonNull ProgressSubscriberFactory subscriberFactory) {
super(worldUtil, subscriberFactory);
}
@Override
public boolean restoreTile(QueueCoordinator queue, CompoundTag ct, int x, int y, int z) {
return new StateWrapper(ct).restoreTag(queue.getWorld().getName(), x, y, z);
}
}

View File

@ -1,317 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.schematic;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.sk89q.jnbt.ByteTag;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.ListTag;
import com.sk89q.jnbt.ShortTag;
import com.sk89q.jnbt.StringTag;
import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.blocks.BaseItemStack;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.world.item.ItemType;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.Container;
import org.bukkit.block.Sign;
import org.bukkit.block.Skull;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class StateWrapper {
public org.bukkit.block.BlockState state = null;
public CompoundTag tag = null;
/**
* @deprecated in favour of using WE methods for obtaining NBT, specifically by obtaining a
* {@link com.sk89q.worldedit.world.block.BaseBlock} and then using {@link com.sk89q.worldedit.world.block.BaseBlock#getNbtData()}
*/
@Deprecated(forRemoval = true, since = "6.9.0")
public StateWrapper(org.bukkit.block.BlockState state) {
this.state = state;
}
public StateWrapper(CompoundTag tag) {
this.tag = tag;
}
public static String jsonToColourCode(String str) {
str = str.replace("{\"extra\":", "").replace("],\"text\":\"\"}", "]")
.replace("[{\"color\":\"black\",\"text\":\"", "&0")
.replace("[{\"color\":\"dark_blue\",\"text\":\"", "&1")
.replace("[{\"color\":\"dark_green\",\"text\":\"", "&2")
.replace("[{\"color\":\"dark_aqua\",\"text\":\"", "&3")
.replace("[{\"color\":\"dark_red\",\"text\":\"", "&4")
.replace("[{\"color\":\"dark_purple\",\"text\":\"", "&5")
.replace("[{\"color\":\"gold\",\"text\":\"", "&6")
.replace("[{\"color\":\"gray\",\"text\":\"", "&7")
.replace("[{\"color\":\"dark_gray\",\"text\":\"", "&8")
.replace("[{\"color\":\"blue\",\"text\":\"", "&9")
.replace("[{\"color\":\"green\",\"text\":\"", "&a")
.replace("[{\"color\":\"aqua\",\"text\":\"", "&b")
.replace("[{\"color\":\"red\",\"text\":\"", "&c")
.replace("[{\"color\":\"light_purple\",\"text\":\"", "&d")
.replace("[{\"color\":\"yellow\",\"text\":\"", "&e")
.replace("[{\"color\":\"white\",\"text\":\"", "&f")
.replace("[{\"obfuscated\":true,\"text\":\"", "&k")
.replace("[{\"bold\":true,\"text\":\"", "&l")
.replace("[{\"strikethrough\":true,\"text\":\"", "&m")
.replace("[{\"underlined\":true,\"text\":\"", "&n")
.replace("[{\"italic\":true,\"text\":\"", "&o").replace("[{\"color\":\"black\",", "&0")
.replace("[{\"color\":\"dark_blue\",", "&1")
.replace("[{\"color\":\"dark_green\",", "&2")
.replace("[{\"color\":\"dark_aqua\",", "&3").replace("[{\"color\":\"dark_red\",", "&4")
.replace("[{\"color\":\"dark_purple\",", "&5").replace("[{\"color\":\"gold\",", "&6")
.replace("[{\"color\":\"gray\",", "&7").replace("[{\"color\":\"dark_gray\",", "&8")
.replace("[{\"color\":\"blue\",", "&9").replace("[{\"color\":\"green\",", "&a")
.replace("[{\"color\":\"aqua\",", "&b").replace("[{\"color\":\"red\",", "&c")
.replace("[{\"color\":\"light_purple\",", "&d").replace("[{\"color\":\"yellow\",", "&e")
.replace("[{\"color\":\"white\",", "&f").replace("[{\"obfuscated\":true,", "&k")
.replace("[{\"bold\":true,", "&l").replace("[{\"strikethrough\":true,", "&m")
.replace("[{\"underlined\":true,", "&n").replace("[{\"italic\":true,", "&o")
.replace("{\"color\":\"black\",\"text\":\"", "&0")
.replace("{\"color\":\"dark_blue\",\"text\":\"", "&1")
.replace("{\"color\":\"dark_green\",\"text\":\"", "&2")
.replace("{\"color\":\"dark_aqua\",\"text\":\"", "&3")
.replace("{\"color\":\"dark_red\",\"text\":\"", "&4")
.replace("{\"color\":\"dark_purple\",\"text\":\"", "&5")
.replace("{\"color\":\"gold\",\"text\":\"", "&6")
.replace("{\"color\":\"gray\",\"text\":\"", "&7")
.replace("{\"color\":\"dark_gray\",\"text\":\"", "&8")
.replace("{\"color\":\"blue\",\"text\":\"", "&9")
.replace("{\"color\":\"green\",\"text\":\"", "&a")
.replace("{\"color\":\"aqua\",\"text\":\"", "&b")
.replace("{\"color\":\"red\",\"text\":\"", "&c")
.replace("{\"color\":\"light_purple\",\"text\":\"", "&d")
.replace("{\"color\":\"yellow\",\"text\":\"", "&e")
.replace("{\"color\":\"white\",\"text\":\"", "&f")
.replace("{\"obfuscated\":true,\"text\":\"", "&k")
.replace("{\"bold\":true,\"text\":\"", "&l")
.replace("{\"strikethrough\":true,\"text\":\"", "&m")
.replace("{\"underlined\":true,\"text\":\"", "&n")
.replace("{\"italic\":true,\"text\":\"", "&o").replace("{\"color\":\"black\",", "&0")
.replace("{\"color\":\"dark_blue\",", "&1").replace("{\"color\":\"dark_green\",", "&2")
.replace("{\"color\":\"dark_aqua\",", "&3").replace("{\"color\":\"dark_red\",", "&4")
.replace("{\"color\":\"dark_purple\",", "&5").replace("{\"color\":\"gold\",", "&6")
.replace("{\"color\":\"gray\",", "&7").replace("{\"color\":\"dark_gray\",", "&8")
.replace("{\"color\":\"blue\",", "&9").replace("{\"color\":\"green\",", "&a")
.replace("{\"color\":\"aqua\",", "&b").replace("{\"color\":\"red\",", "&c")
.replace("{\"color\":\"light_purple\",", "&d").replace("{\"color\":\"yellow\",", "&e")
.replace("{\"color\":\"white\",", "&f").replace("{\"obfuscated\":true,", "&k")
.replace("{\"bold\":true,", "&l").replace("{\"strikethrough\":true,", "&m")
.replace("{\"underlined\":true,", "&n").replace("{\"italic\":true,", "&o")
.replace("\"color\":\"black\",\"text\":\"", "&0")
.replace("\"color\":\"dark_blue\",\"text\":\"", "&1")
.replace("\"color\":\"dark_green\",\"text\":\"", "&2")
.replace("\"color\":\"dark_aqua\",\"text\":\"", "&3")
.replace("\"color\":\"dark_red\",\"text\":\"", "&4")
.replace("\"color\":\"dark_purple\",\"text\":\"", "&5")
.replace("\"color\":\"gold\",\"text\":\"", "&6")
.replace("\"color\":\"gray\",\"text\":\"", "&7")
.replace("\"color\":\"dark_gray\",\"text\":\"", "&8")
.replace("\"color\":\"blue\",\"text\":\"", "&9")
.replace("\"color\":\"green\",\"text\":\"", "&a")
.replace("\"color\":\"aqua\",\"text\":\"", "&b")
.replace("\"color\":\"red\",\"text\":\"", "&c")
.replace("\"color\":\"light_purple\",\"text\":\"", "&d")
.replace("\"color\":\"yellow\",\"text\":\"", "&e")
.replace("\"color\":\"white\",\"text\":\"", "&f")
.replace("\"obfuscated\":true,\"text\":\"", "&k")
.replace("\"bold\":true,\"text\":\"", "&l")
.replace("\"strikethrough\":true,\"text\":\"", "&m")
.replace("\"underlined\":true,\"text\":\"", "&n")
.replace("\"italic\":true,\"text\":\"", "&o").replace("\"color\":\"black\",", "&0")
.replace("\"color\":\"dark_blue\",", "&1").replace("\"color\":\"dark_green\",", "&2")
.replace("\"color\":\"dark_aqua\",", "&3").replace("\"color\":\"dark_red\",", "&4")
.replace("\"color\":\"dark_purple\",", "&5").replace("\"color\":\"gold\",", "&6")
.replace("\"color\":\"gray\",", "&7").replace("\"color\":\"dark_gray\",", "&8")
.replace("\"color\":\"blue\",", "&9").replace("\"color\":\"green\",", "&a")
.replace("\"color\":\"aqua\",", "&b").replace("\"color\":\"red\",", "&c")
.replace("\"color\":\"light_purple\",", "&d").replace("\"color\":\"yellow\",", "&e")
.replace("\"color\":\"white\",", "&f").replace("\"obfuscated\":true,", "&k")
.replace("\"bold\":true,", "&l").replace("\"strikethrough\":true,", "&m")
.replace("\"underlined\":true,", "&n").replace("\"italic\":true,", "&o")
.replace("[{\"text\":\"", "&0").replace("{\"text\":\"", "&0").replace("\"},", "")
.replace("\"}]", "").replace("\"}", "");
str = ChatColor.translateAlternateColorCodes('&', str);
return str;
}
/**
* Restore the TileEntity data to the given world at the given coordinates.
*
* @param worldName World name
* @param x x position
* @param y y position
* @param z z position
* @return true if successful
*/
public boolean restoreTag(String worldName, int x, int y, int z) {
World world = BukkitUtil.getWorld(worldName);
if (world == null) {
return false;
}
return restoreTag(world.getBlockAt(x, y, z));
}
/**
* Restore the TileEntity data to the given block
*
* @param block Block to restore to
* @return true if successful
*/
@SuppressWarnings("deprecation") // #setLine is needed for Spigot compatibility
public boolean restoreTag(@NonNull Block block) {
if (this.tag == null) {
return false;
}
org.bukkit.block.BlockState state = block.getState();
switch (getId()) {
case "chest", "beacon", "brewingstand", "dispenser", "dropper", "furnace", "hopper", "shulkerbox" -> {
if (!(state instanceof Container container)) {
return false;
}
List<Tag> itemsTag = this.tag.getListTag("Items").getValue();
Inventory inv = container.getSnapshotInventory();
for (Tag itemTag : itemsTag) {
CompoundTag itemComp = (CompoundTag) itemTag;
ItemType type = ItemType.REGISTRY.get(itemComp.getString("id").toLowerCase());
if (type == null) {
continue;
}
int count = itemComp.getByte("Count");
int slot = itemComp.getByte("Slot");
CompoundTag tag = (CompoundTag) itemComp.getValue().get("tag");
BaseItemStack baseItemStack = new BaseItemStack(type, tag, count);
ItemStack itemStack = BukkitAdapter.adapt(baseItemStack);
inv.setItem(slot, itemStack);
}
container.update(true, false);
return true;
}
case "sign" -> {
if (state instanceof Sign sign) {
sign.setLine(0, jsonToColourCode(tag.getString("Text1")));
sign.setLine(1, jsonToColourCode(tag.getString("Text2")));
sign.setLine(2, jsonToColourCode(tag.getString("Text3")));
sign.setLine(3, jsonToColourCode(tag.getString("Text4")));
state.update(true);
return true;
}
return false;
}
case "skull" -> {
if (state instanceof Skull skull) {
CompoundTag skullOwner = ((CompoundTag) this.tag.getValue().get("SkullOwner"));
if (skullOwner == null) {
return true;
}
String player = skullOwner.getString("Name");
if (player == null || player.isEmpty()) {
return false;
}
try {
skull.setOwningPlayer(Bukkit.getOfflinePlayer(player));
skull.update(true);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
return false;
}
}
return false;
}
/**
* Get a CompoundTag of the contents of a block's inventory (chest, furnace, etc.).
*
* @deprecated in favour of using WorldEdit methods for obtaining NBT, specifically by obtaining a
* {@link com.sk89q.worldedit.world.block.BaseBlock} and then using {@link com.sk89q.worldedit.world.block.BaseBlock#getNbtData()}
*/
@Deprecated(forRemoval = true, since = "6.9.0")
public CompoundTag getTag() {
if (this.tag != null) {
return this.tag;
}
if (this.state instanceof InventoryHolder inv) {
ItemStack[] contents = inv.getInventory().getContents();
Map<String, Tag> values = new HashMap<>();
values.put("Items", new ListTag(CompoundTag.class, serializeInventory(contents)));
return new CompoundTag(values);
}
return null;
}
public String getId() {
String tileid = this.tag.getString("id").toLowerCase();
if (tileid.startsWith("minecraft:")) {
tileid = tileid.replace("minecraft:", "");
}
return tileid;
}
public List<CompoundTag> serializeInventory(ItemStack[] items) {
List<CompoundTag> tags = new ArrayList<>();
for (int i = 0; i < items.length; ++i) {
if (items[i] != null) {
Map<String, Tag> tagData = serializeItem(items[i]);
tagData.put("Slot", new ByteTag((byte) i));
tags.add(new CompoundTag(tagData));
}
}
return tags;
}
public Map<String, Tag> serializeItem(ItemStack item) {
Map<String, Tag> data = new HashMap<>();
data.put("id", new StringTag(item.getType().name()));
data.put("Damage", new ShortTag(item.getDurability()));
data.put("Count", new ByteTag((byte) item.getAmount()));
if (!item.getEnchantments().isEmpty()) {
List<CompoundTag> enchantmentList = new ArrayList<>();
for (Entry<Enchantment, Integer> entry : item.getEnchantments().entrySet()) {
Map<String, Tag> enchantment = new HashMap<>();
enchantment.put("id", new StringTag(entry.getKey().toString()));
enchantment.put("lvl", new ShortTag(entry.getValue().shortValue()));
enchantmentList.add(new CompoundTag(enchantment));
}
Map<String, Tag> auxData = new HashMap<>();
auxData.put("ench", new ListTag(CompoundTag.class, enchantmentList));
data.put("tag", new CompoundTag(auxData));
}
return data;
}
}

View File

@ -1,36 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.util;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.world.block.BlockState;
import org.bukkit.Material;
import org.bukkit.block.Block;
public class BukkitBlockUtil {
public static BlockState get(Block block) {
return get(block.getType());
}
public static BlockState get(Material material) {
return BukkitAdapter.asBlockType(material).getDefaultState();
}
}

View File

@ -1,44 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.util;
import com.google.inject.Singleton;
import com.plotsquared.core.util.ChunkManager;
import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.regions.CuboidRegion;
import io.papermc.lib.PaperLib;
import java.util.concurrent.CompletableFuture;
@Singleton
public class BukkitChunkManager extends ChunkManager {
public static boolean isIn(CuboidRegion region, int x, int z) {
return x >= region.getMinimumPoint().getX() && x <= region.getMaximumPoint().getX() && z >= region
.getMinimumPoint()
.getZ() && z <= region
.getMaximumPoint().getZ();
}
@Override
public CompletableFuture<?> loadChunk(String world, BlockVector2 chunkLoc, boolean force) {
return PaperLib.getChunkAtAsync(BukkitUtil.getWorld(world), chunkLoc.getX(), chunkLoc.getZ(), force);
}
}

View File

@ -1,106 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.util;
import com.google.inject.Singleton;
import com.plotsquared.bukkit.player.BukkitOfflinePlayer;
import com.plotsquared.bukkit.player.BukkitPlayer;
import com.plotsquared.core.player.OfflinePlotPlayer;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.util.EconHandler;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.checkerframework.checker.nullness.qual.NonNull;
@Singleton
public class BukkitEconHandler extends EconHandler {
private Economy econ;
private static OfflinePlayer getBukkitOfflinePlayer(PlotPlayer<?> plotPlayer) {
return ((BukkitPlayer) plotPlayer).player;
}
@Override
public boolean init() {
if (this.econ == null) {
setupEconomy();
}
return this.econ != null;
}
private void setupEconomy() {
if (Bukkit.getServer().getPluginManager().getPlugin("Vault") == null) {
return;
}
RegisteredServiceProvider<Economy> economyProvider =
Bukkit.getServer().getServicesManager().getRegistration(Economy.class);
if (economyProvider != null) {
this.econ = economyProvider.getProvider();
}
}
@Override
public double getMoney(PlotPlayer<?> player) {
double bal = super.getMoney(player);
if (Double.isNaN(bal)) {
return this.econ.getBalance(getBukkitOfflinePlayer(player));
}
return bal;
}
@Override
public void withdrawMoney(PlotPlayer<?> player, double amount) {
this.econ.withdrawPlayer(getBukkitOfflinePlayer(player), amount);
}
@Override
public void depositMoney(PlotPlayer<?> player, double amount) {
this.econ.depositPlayer(getBukkitOfflinePlayer(player), amount);
}
@Override
public void depositMoney(OfflinePlotPlayer player, double amount) {
this.econ.depositPlayer(((BukkitOfflinePlayer) player).player, amount);
}
@Override
public boolean isEnabled(PlotArea plotArea) {
return plotArea.useEconomy();
}
@Override
public @NonNull String format(double balance) {
return this.econ.format(balance);
}
@Override
public boolean isSupported() {
return true;
}
@Override
public double getBalance(PlotPlayer<?> player) {
return this.econ.getBalance(getBukkitOfflinePlayer(player));
}
}

View File

@ -1,376 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.util;
import com.plotsquared.bukkit.player.BukkitPlayer;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.configuration.caption.TranslatableCaption;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.permissions.Permission;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.flag.implementations.AnimalAttackFlag;
import com.plotsquared.core.plot.flag.implementations.AnimalCapFlag;
import com.plotsquared.core.plot.flag.implementations.DoneFlag;
import com.plotsquared.core.plot.flag.implementations.EntityCapFlag;
import com.plotsquared.core.plot.flag.implementations.HangingBreakFlag;
import com.plotsquared.core.plot.flag.implementations.HostileAttackFlag;
import com.plotsquared.core.plot.flag.implementations.HostileCapFlag;
import com.plotsquared.core.plot.flag.implementations.MiscBreakFlag;
import com.plotsquared.core.plot.flag.implementations.MiscCapFlag;
import com.plotsquared.core.plot.flag.implementations.MobCapFlag;
import com.plotsquared.core.plot.flag.implementations.PveFlag;
import com.plotsquared.core.plot.flag.implementations.PvpFlag;
import com.plotsquared.core.plot.flag.implementations.TamedAttackFlag;
import com.plotsquared.core.plot.flag.implementations.VehicleCapFlag;
import com.plotsquared.core.util.EntityUtil;
import com.plotsquared.core.util.entity.EntityCategories;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import net.kyori.adventure.text.minimessage.Template;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Creature;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.projectiles.BlockProjectileSource;
import org.bukkit.projectiles.ProjectileSource;
import java.util.Objects;
public class BukkitEntityUtil {
public static final com.sk89q.worldedit.world.entity.EntityType FAKE_ENTITY_TYPE =
new com.sk89q.worldedit.world.entity.EntityType("plotsquared:fake");
public static boolean entityDamage(Entity damager, Entity victim) {
return entityDamage(damager, victim, null);
}
public static boolean entityDamage(Entity damager, Entity victim, EntityDamageEvent.DamageCause cause) {
Location dloc = BukkitUtil.adapt(damager.getLocation());
Location vloc = BukkitUtil.adapt(victim.getLocation());
PlotArea dArea = dloc.getPlotArea();
PlotArea vArea;
if (dArea != null && dArea.contains(vloc.getX(), vloc.getZ())) {
vArea = dArea;
} else {
vArea = vloc.getPlotArea();
}
if (dArea == null && vArea == null) {
return true;
}
Plot dplot;
if (dArea != null) {
dplot = dArea.getPlot(dloc);
} else {
dplot = null;
}
Plot vplot;
if (vArea != null) {
vplot = vArea.getPlot(vloc);
} else {
vplot = null;
}
Plot plot;
String stub;
boolean isPlot = true;
if (dplot == null && vplot == null) {
if (dArea == null) {
return true;
}
plot = null;
stub = "road";
isPlot = false;
} else {
// Prioritize plots for close to seamless pvp zones
if (victim.getTicksLived() > damager.getTicksLived()) {
if (dplot == null || !(victim instanceof Player)) {
if (vplot == null) {
plot = dplot;
} else {
plot = vplot;
}
} else {
plot = dplot;
}
} else if (dplot == null || !(victim instanceof Player)) {
if (vplot == null) {
plot = dplot;
} else {
plot = vplot;
}
} else if (vplot == null) {
plot = dplot;
} else {
plot = vplot;
}
if (plot.hasOwner()) {
stub = "other";
} else {
stub = "unowned";
}
}
boolean roadFlags = vArea != null ? vArea.isRoadFlags() : dArea.isRoadFlags();
PlotArea area = vArea != null ? vArea : dArea;
Player player;
if (damager instanceof Player) { // attacker is player
player = (Player) damager;
} else if (damager instanceof Projectile projectile) {
ProjectileSource shooter = projectile.getShooter();
if (shooter instanceof Player) { // shooter is player
player = (Player) shooter;
} else { // shooter is not player
if (shooter instanceof BlockProjectileSource) {
Location sLoc = BukkitUtil
.adapt(((BlockProjectileSource) shooter).getBlock().getLocation());
dplot = dArea.getPlot(sLoc);
}
player = null;
}
} else { // Attacker is not player
player = null;
}
if (player != null) {
BukkitPlayer plotPlayer = BukkitUtil.adapt(player);
final com.sk89q.worldedit.world.entity.EntityType entityType;
// Create a fake entity type if the type does not have a name
if (victim.getType().getName() == null) {
entityType = FAKE_ENTITY_TYPE;
} else {
entityType = BukkitAdapter.adapt(victim.getType());
}
if (EntityCategories.HANGING.contains(entityType)) { // hanging
if (plot != null && (plot.getFlag(HangingBreakFlag.class) || plot
.isAdded(plotPlayer.getUUID()))) {
if (Settings.Done.RESTRICT_BUILDING && DoneFlag.isDone(plot)) {
if (!plotPlayer.hasPermission(Permission.PERMISSION_ADMIN_BUILD_OTHER)) {
plotPlayer.sendMessage(
TranslatableCaption.of("done.building_restricted")
);
return false;
}
}
return true;
}
if (!plotPlayer.hasPermission(Permission.PERMISSION_ADMIN_DESTROY + "." + stub)) {
plotPlayer.sendMessage(
TranslatableCaption.of("permission.no_permission_event"),
Template.of("node", Permission.PERMISSION_ADMIN_DESTROY + "." + stub)
);
return false;
}
} else if (victim.getType() == EntityType.ARMOR_STAND) {
if (plot != null && (plot.getFlag(MiscBreakFlag.class) || plot
.isAdded(plotPlayer.getUUID()))) {
return true;
}
if (!plotPlayer.hasPermission(Permission.PERMISSION_ADMIN_DESTROY + "." + stub)) {
plotPlayer.sendMessage(
TranslatableCaption.of("permission.no_permission_event"),
Template.of("node", Permission.PERMISSION_ADMIN_DESTROY + "." + stub)
);
if (plot != null) {
plot.debug(player.getName()
+ " could not break armor stand because misc-break = false");
}
return false;
}
} else if (EntityCategories.HOSTILE.contains(entityType)) {
if (isPlot) {
if (plot.getFlag(HostileAttackFlag.class) || plot.getFlag(PveFlag.class) || plot
.isAdded(plotPlayer.getUUID())) {
return true;
}
} else if (roadFlags && (area.getRoadFlag(HostileAttackFlag.class) || area
.getFlag(PveFlag.class))) {
return true;
}
if (!plotPlayer.hasPermission(Permission.PERMISSION_ADMIN_PVE + "." + stub)) {
plotPlayer.sendMessage(
TranslatableCaption.of("permission.no_permission_event"),
Template.of("node", Permission.PERMISSION_ADMIN_PVE + "." + stub)
);
if (plot != null) {
plot.debug(player.getName() + " could not attack " + entityType
+ " because pve = false OR hostile-attack = false");
}
return false;
}
} else if (EntityCategories.TAMEABLE.contains(entityType)) { // victim is tameable
if (isPlot) {
if (plot.getFlag(TamedAttackFlag.class) || plot.getFlag(PveFlag.class) || plot
.isAdded(plotPlayer.getUUID())) {
return true;
}
} else if (roadFlags && (area.getRoadFlag(TamedAttackFlag.class) || area
.getFlag(PveFlag.class))) {
return true;
}
if (!plotPlayer.hasPermission(Permission.PERMISSION_ADMIN_PVE + "." + stub)) {
plotPlayer.sendMessage(
TranslatableCaption.of("permission.no_permission_event"),
Template.of("node", Permission.PERMISSION_ADMIN_PVE + "." + stub)
);
if (plot != null) {
plot.debug(player.getName() + " could not attack " + entityType
+ " because pve = false OR tamed-attack = false");
}
return false;
}
} else if (EntityCategories.PLAYER.contains(entityType)) {
if (isPlot) {
if (!plot.getFlag(PvpFlag.class) && !plotPlayer.hasPermission(Permission.PERMISSION_ADMIN_PVP + "." + stub)) {
plotPlayer.sendMessage(
TranslatableCaption.of("permission.no_permission_event"),
Template.of("node", Permission.PERMISSION_ADMIN_PVP + "." + stub)
);
plot.debug(player.getName() + " could not attack " + entityType
+ " because pve = false");
return false;
} else {
return true;
}
} else if (roadFlags && area.getRoadFlag(PvpFlag.class)) {
return true;
}
if (!plotPlayer.hasPermission(Permission.PERMISSION_ADMIN_PVP + "." + stub)) {
plotPlayer.sendMessage(
TranslatableCaption.of("permission.no_permission_event"),
Template.of("node", Permission.PERMISSION_ADMIN_PVP + "." + stub)
);
return false;
}
} else if (EntityCategories.ANIMAL.contains(entityType)) { // victim is animal
if (isPlot) {
if (plot.getFlag(AnimalAttackFlag.class) || plot.getFlag(PveFlag.class) || plot
.isAdded(plotPlayer.getUUID())) {
return true;
}
} else if (roadFlags && (area.getRoadFlag(AnimalAttackFlag.class) || area
.getFlag(PveFlag.class))) {
return true;
}
if (!plotPlayer.hasPermission(Permission.PERMISSION_ADMIN_PVE + "." + stub)) {
plotPlayer.sendMessage(
TranslatableCaption.of("permission.no_permission_event"),
Template.of("node", Permission.PERMISSION_ADMIN_PVE + "." + stub)
);
if (plot != null) {
plot.debug(player.getName() + " could not attack " + entityType
+ " because pve = false OR animal-attack = false");
}
return false;
}
} else if (EntityCategories.VEHICLE
.contains(entityType)) { // Vehicles are managed in vehicle destroy event
return true;
} else { // victim is something else
if (isPlot) {
if (plot.getFlag(PveFlag.class) || plot.isAdded(plotPlayer.getUUID())) {
return true;
}
} else if (roadFlags && area.getRoadFlag(PveFlag.class)) {
return true;
}
if (!plotPlayer.hasPermission(Permission.PERMISSION_ADMIN_PVE + "." + stub)) {
plotPlayer.sendMessage(
TranslatableCaption.of("permission.no_permission_event"),
Template.of("node", Permission.PERMISSION_ADMIN_PVE + "." + stub)
);
if (plot != null) {
plot.debug(player.getName() + " could not attack " + entityType
+ " because pve = false");
}
return false;
}
}
return true;
} else if (dplot != null && (!dplot.equals(vplot) || Objects
.equals(dplot.getOwnerAbs(), vplot.getOwnerAbs()))) {
return vplot != null && vplot.getFlag(PveFlag.class);
}
//disable the firework damage. too much of a headache to support at the moment.
if (vplot != null) {
if (EntityDamageEvent.DamageCause.ENTITY_EXPLOSION == cause
&& damager.getType() == EntityType.FIREWORK) {
return false;
}
}
if (vplot == null && roadFlags && area.getRoadFlag(PveFlag.class)) {
return true;
}
return ((vplot != null && vplot.getFlag(PveFlag.class)) || !(damager instanceof Arrow
&& !(victim instanceof Creature)));
}
public static boolean checkEntity(Entity entity, Plot plot) {
if (plot == null || !plot.hasOwner() || plot.getFlags().isEmpty() && plot.getArea()
.getFlagContainer().getFlagMap().isEmpty()) {
return false;
}
final com.sk89q.worldedit.world.entity.EntityType entityType =
BukkitAdapter.adapt(entity.getType());
if (EntityCategories.PLAYER.contains(entityType)) {
return false;
}
if (EntityCategories.PROJECTILE.contains(entityType) || EntityCategories.OTHER
.contains(entityType) || EntityCategories.HANGING.contains(entityType)) {
return EntityUtil.checkEntity(plot, EntityCapFlag.ENTITY_CAP_UNLIMITED,
MiscCapFlag.MISC_CAP_UNLIMITED
);
}
// Has to go go before vehicle as horses are both
// animals and vehicles
if (EntityCategories.ANIMAL.contains(entityType) || EntityCategories.VILLAGER
.contains(entityType) || EntityCategories.TAMEABLE.contains(entityType)) {
return EntityUtil
.checkEntity(plot, EntityCapFlag.ENTITY_CAP_UNLIMITED, MobCapFlag.MOB_CAP_UNLIMITED,
AnimalCapFlag.ANIMAL_CAP_UNLIMITED
);
}
if (EntityCategories.HOSTILE.contains(entityType)) {
return EntityUtil
.checkEntity(plot, EntityCapFlag.ENTITY_CAP_UNLIMITED, MobCapFlag.MOB_CAP_UNLIMITED,
HostileCapFlag.HOSTILE_CAP_UNLIMITED
);
}
if (EntityCategories.VEHICLE.contains(entityType)) {
return EntityUtil.checkEntity(plot, EntityCapFlag.ENTITY_CAP_UNLIMITED,
VehicleCapFlag.VEHICLE_CAP_UNLIMITED
);
}
return EntityUtil.checkEntity(plot, EntityCapFlag.ENTITY_CAP_UNLIMITED);
}
}

View File

@ -1,169 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.util;
import com.google.inject.Singleton;
import com.plotsquared.bukkit.player.BukkitPlayer;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.PlotInventory;
import com.plotsquared.core.plot.PlotItemStack;
import com.plotsquared.core.util.InventoryUtil;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryView;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.ItemMeta;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
@Singleton
public class BukkitInventoryUtil extends InventoryUtil {
private static @Nullable ItemStack getItem(PlotItemStack item) {
if (item == null) {
return null;
}
Material material = BukkitAdapter.adapt(item.getType());
if (material == null) {
return null;
}
ItemStack stack = new ItemStack(material, item.getAmount());
ItemMeta meta = null;
if (item.getName() != null) {
meta = stack.getItemMeta();
Component nameComponent = BukkitUtil.MINI_MESSAGE.parse(item.getName());
meta.setDisplayName(BukkitUtil.LEGACY_COMPONENT_SERIALIZER.serialize(nameComponent));
}
if (item.getLore() != null) {
if (meta == null) {
meta = stack.getItemMeta();
}
List<String> lore = new ArrayList<>();
for (String entry : item.getLore()) {
lore.add(BukkitUtil.LEGACY_COMPONENT_SERIALIZER.serialize(BukkitUtil.MINI_MESSAGE.deserialize(entry)));
}
meta.setLore(lore);
}
if (meta != null) {
stack.setItemMeta(meta);
}
return stack;
}
@SuppressWarnings("deprecation") // Paper deprecation
@Override
public void open(PlotInventory inv) {
BukkitPlayer bp = (BukkitPlayer) inv.getPlayer();
Inventory inventory = Bukkit.createInventory(null, inv.getLines() * 9,
ChatColor.translateAlternateColorCodes('&', inv.getTitle())
);
PlotItemStack[] items = inv.getItems();
for (int i = 0; i < inv.getLines() * 9; i++) {
PlotItemStack item = items[i];
if (item != null) {
inventory.setItem(i, getItem(item));
}
}
bp.player.openInventory(inventory);
}
@Override
public void close(PlotInventory inv) {
if (!inv.isOpen()) {
return;
}
BukkitPlayer bp = (BukkitPlayer) inv.getPlayer();
bp.player.closeInventory();
}
@Override
public boolean setItemChecked(PlotInventory inv, int index, PlotItemStack item) {
BukkitPlayer bp = (BukkitPlayer) inv.getPlayer();
InventoryView opened = bp.player.getOpenInventory();
ItemStack stack = getItem(item);
if (stack == null) {
return false;
}
if (!inv.isOpen()) {
return true;
}
opened.setItem(index, stack);
bp.player.updateInventory();
return true;
}
@SuppressWarnings("deprecation") // Paper deprecation
public PlotItemStack getItem(ItemStack item) {
if (item == null) {
return null;
}
// int id = item.getTypeId();
Material id = item.getType();
ItemMeta meta = item.getItemMeta();
int amount = item.getAmount();
String name = null;
String[] lore = null;
if (item.hasItemMeta()) {
assert meta != null;
if (meta.hasDisplayName()) {
name = meta.getDisplayName();
}
if (meta.hasLore()) {
List<String> itemLore = meta.getLore();
assert itemLore != null;
lore = itemLore.toArray(new String[0]);
}
}
return new PlotItemStack(id.name(), amount, name, lore);
}
@Override
public PlotItemStack[] getItems(PlotPlayer<?> player) {
BukkitPlayer bp = (BukkitPlayer) player;
PlayerInventory inv = bp.player.getInventory();
return IntStream.range(0, 36).mapToObj(i -> getItem(inv.getItem(i)))
.toArray(PlotItemStack[]::new);
}
@SuppressWarnings("deprecation") // #getTitle is needed for Spigot compatibility
@Override
public boolean isOpen(PlotInventory plotInventory) {
if (!plotInventory.isOpen()) {
return false;
}
BukkitPlayer bp = (BukkitPlayer) plotInventory.getPlayer();
InventoryView opened = bp.player.getOpenInventory();
if (plotInventory.isOpen()) {
if (opened.getType() == InventoryType.CRAFTING) {
opened.getTitle();
}
}
return false;
}
}

View File

@ -1,346 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.util;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.plotsquared.core.generator.AugmentedUtils;
import com.plotsquared.core.inject.factory.ProgressSubscriberFactory;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.location.PlotLoc;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.PlotManager;
import com.plotsquared.core.queue.GlobalBlockQueue;
import com.plotsquared.core.queue.QueueCoordinator;
import com.plotsquared.core.queue.ScopedQueueCoordinator;
import com.plotsquared.core.util.ChunkManager;
import com.plotsquared.core.util.RegionManager;
import com.plotsquared.core.util.WorldUtil;
import com.plotsquared.core.util.entity.EntityCategories;
import com.plotsquared.core.util.task.RunnableVal;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.bukkit.BukkitWorld;
import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockTypes;
import io.papermc.lib.PaperLib;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static com.plotsquared.core.util.entity.EntityCategories.CAP_ANIMAL;
import static com.plotsquared.core.util.entity.EntityCategories.CAP_ENTITY;
import static com.plotsquared.core.util.entity.EntityCategories.CAP_MISC;
import static com.plotsquared.core.util.entity.EntityCategories.CAP_MOB;
import static com.plotsquared.core.util.entity.EntityCategories.CAP_MONSTER;
import static com.plotsquared.core.util.entity.EntityCategories.CAP_VEHICLE;
@Singleton
public class BukkitRegionManager extends RegionManager {
private final GlobalBlockQueue blockQueue;
@Inject
public BukkitRegionManager(
@NonNull WorldUtil worldUtil, @NonNull GlobalBlockQueue blockQueue, @NonNull
ProgressSubscriberFactory subscriberFactory
) {
super(worldUtil, blockQueue, subscriberFactory);
this.blockQueue = blockQueue;
}
@Override
public boolean handleClear(
@NonNull Plot plot,
@Nullable Runnable whenDone,
@NonNull PlotManager manager,
@Nullable PlotPlayer<?> player
) {
return false;
}
@Override
public int[] countEntities(@NonNull Plot plot) {
int[] existing = (int[]) plot.getMeta("EntityCount");
if (existing != null && (System.currentTimeMillis() - (long) plot.getMeta("EntityCountTime") < 1000)) {
return existing;
}
PlotArea area = plot.getArea();
World world = BukkitUtil.getWorld(area.getWorldName());
Location bot = plot.getBottomAbs();
Location top = plot.getTopAbs();
int bx = bot.getX() >> 4;
int bz = bot.getZ() >> 4;
int tx = top.getX() >> 4;
int tz = top.getZ() >> 4;
int size = tx - bx << 4;
Set<Chunk> chunks = new HashSet<>();
for (int X = bx; X <= tx; X++) {
for (int Z = bz; Z <= tz; Z++) {
if (world.isChunkLoaded(X, Z)) {
chunks.add(world.getChunkAt(X, Z));
}
}
}
boolean doWhole = false;
List<Entity> entities = null;
if (size > 200 && chunks.size() > 200) {
entities = world.getEntities();
if (entities.size() < 16 + size / 8) {
doWhole = true;
}
}
int[] count = new int[6];
if (doWhole) {
for (Entity entity : entities) {
org.bukkit.Location location = entity.getLocation();
PaperLib.getChunkAtAsync(location).thenAccept(chunk -> {
if (chunks.contains(chunk)) {
int X = chunk.getX();
int Z = chunk.getZ();
if (X > bx && X < tx && Z > bz && Z < tz) {
count(count, entity);
} else {
Plot other = area.getPlot(BukkitUtil.adapt(location));
if (plot.equals(other)) {
count(count, entity);
}
}
}
});
}
} else {
for (Chunk chunk : chunks) {
int X = chunk.getX();
int Z = chunk.getZ();
Entity[] entities1 = chunk.getEntities();
for (Entity entity : entities1) {
if (X == bx || X == tx || Z == bz || Z == tz) {
Plot other = area.getPlot(BukkitUtil.adapt(entity.getLocation()));
if (plot.equals(other)) {
count(count, entity);
}
} else {
count(count, entity);
}
}
}
}
return count;
}
@Override
public boolean regenerateRegion(
final @NonNull Location pos1,
final @NonNull Location pos2,
final boolean ignoreAugment,
final @Nullable Runnable whenDone
) {
final BukkitWorld world = (BukkitWorld) worldUtil.getWeWorld(pos1.getWorldName());
final int p1x = pos1.getX();
final int p1z = pos1.getZ();
final int p2x = pos2.getX();
final int p2z = pos2.getZ();
final int bcx = p1x >> 4;
final int bcz = p1z >> 4;
final int tcx = p2x >> 4;
final int tcz = p2z >> 4;
final QueueCoordinator queue = blockQueue.getNewQueue(world);
final QueueCoordinator regenQueue = blockQueue.getNewQueue(world);
queue.addReadChunks(new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3()).getChunks());
queue.setChunkConsumer(chunk -> {
int x = chunk.getX();
int z = chunk.getZ();
int xxb = x << 4;
int zzb = z << 4;
int xxt = xxb + 15;
int zzt = zzb + 15;
if (xxb >= p1x && xxt <= p2x && zzb >= p1z && zzt <= p2z) {
AugmentedUtils.bypass(ignoreAugment, () -> regenQueue.regenChunk(chunk.getX(), chunk.getZ()));
return;
}
boolean checkX1 = false;
int xxb2;
if (x == bcx) {
xxb2 = p1x - 1;
checkX1 = true;
} else {
xxb2 = xxb;
}
boolean checkX2 = false;
int xxt2;
if (x == tcx) {
xxt2 = p2x + 1;
checkX2 = true;
} else {
xxt2 = xxt;
}
boolean checkZ1 = false;
int zzb2;
if (z == bcz) {
zzb2 = p1z - 1;
checkZ1 = true;
} else {
zzb2 = zzb;
}
boolean checkZ2 = false;
int zzt2;
if (z == tcz) {
zzt2 = p2z + 1;
checkZ2 = true;
} else {
zzt2 = zzt;
}
final ContentMap map = new ContentMap();
if (checkX1) {
map.saveRegion(world, xxb, xxb2, zzb2, zzt2); //
}
if (checkX2) {
map.saveRegion(world, xxt2, xxt, zzb2, zzt2); //
}
if (checkZ1) {
map.saveRegion(world, xxb2, xxt2, zzb, zzb2); //
}
if (checkZ2) {
map.saveRegion(world, xxb2, xxt2, zzt2, zzt); //
}
if (checkX1 && checkZ1) {
map.saveRegion(world, xxb, xxb2, zzb, zzb2); //
}
if (checkX2 && checkZ1) {
map.saveRegion(world, xxt2, xxt, zzb, zzb2); // ?
}
if (checkX1 && checkZ2) {
map.saveRegion(world, xxb, xxb2, zzt2, zzt); // ?
}
if (checkX2 && checkZ2) {
map.saveRegion(world, xxt2, xxt, zzt2, zzt); //
}
CuboidRegion currentPlotClear = new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3());
map.saveEntitiesOut(Bukkit.getWorld(world.getName()).getChunkAt(x, z), currentPlotClear);
AugmentedUtils.bypass(
ignoreAugment,
() -> ChunkManager.setChunkInPlotArea(null, new RunnableVal<ScopedQueueCoordinator>() {
@Override
public void run(ScopedQueueCoordinator value) {
Location min = value.getMin();
int bx = min.getX();
int bz = min.getZ();
for (int x1 = 0; x1 < 16; x1++) {
for (int z1 = 0; z1 < 16; z1++) {
PlotLoc plotLoc = new PlotLoc(bx + x1, bz + z1);
BaseBlock[] ids = map.allBlocks.get(plotLoc);
if (ids != null) {
int minY = value.getMin().getY();
for (int yIndex = 0; yIndex < ids.length; yIndex++) {
int y = yIndex + minY;
BaseBlock id = ids[yIndex];
if (id != null) {
value.setBlock(x1, y, z1, id);
} else {
value.setBlock(x1, y, z1, BlockTypes.AIR.getDefaultState());
}
}
}
}
}
}
}, world.getName(), chunk)
);
//map.restoreBlocks(worldObj, 0, 0);
map.restoreEntities(Bukkit.getWorld(world.getName()));
});
regenQueue.setCompleteTask(whenDone);
queue.setCompleteTask(regenQueue::enqueue);
queue.enqueue();
return true;
}
@Override
public void clearAllEntities(@NonNull Location pos1, @NonNull Location pos2) {
String world = pos1.getWorldName();
final World bukkitWorld = BukkitUtil.getWorld(world);
final List<Entity> entities;
if (bukkitWorld != null) {
entities = new ArrayList<>(bukkitWorld.getEntities());
} else {
entities = new ArrayList<>();
}
int bx = pos1.getX();
int bz = pos1.getZ();
int tx = pos2.getX();
int tz = pos2.getZ();
for (Entity entity : entities) {
if (!(entity instanceof Player)) {
org.bukkit.Location location = entity.getLocation();
if (location.getX() >= bx && location.getX() <= tx && location.getZ() >= bz && location.getZ() <= tz) {
if (entity.hasMetadata("ps-tmp-teleport")) {
continue;
}
entity.remove();
}
}
}
}
private void count(int[] count, @NonNull Entity entity) {
final com.sk89q.worldedit.world.entity.EntityType entityType = BukkitAdapter.adapt(entity.getType());
if (EntityCategories.PLAYER.contains(entityType)) {
return;
} else if (EntityCategories.PROJECTILE.contains(entityType) || EntityCategories.OTHER.contains(entityType) || EntityCategories.HANGING
.contains(entityType)) {
count[CAP_MISC]++;
} else if (EntityCategories.ANIMAL.contains(entityType) || EntityCategories.VILLAGER.contains(entityType) || EntityCategories.TAMEABLE
.contains(entityType)) {
count[CAP_MOB]++;
count[CAP_ANIMAL]++;
} else if (EntityCategories.VEHICLE.contains(entityType)) {
count[CAP_VEHICLE]++;
} else if (EntityCategories.HOSTILE.contains(entityType)) {
count[CAP_MOB]++;
count[CAP_MONSTER]++;
}
count[CAP_ENTITY]++;
}
}

View File

@ -1,256 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.util;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.plotsquared.bukkit.generator.BukkitPlotGenerator;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.ConfigurationNode;
import com.plotsquared.core.configuration.ConfigurationSection;
import com.plotsquared.core.configuration.file.YamlConfiguration;
import com.plotsquared.core.generator.GeneratorWrapper;
import com.plotsquared.core.inject.annotations.WorldConfig;
import com.plotsquared.core.inject.annotations.WorldFile;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.PlotAreaType;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.setup.PlotAreaBuilder;
import com.plotsquared.core.util.SetupUtils;
import com.plotsquared.core.util.task.TaskManager;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.plugin.Plugin;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Objects;
@Singleton
public class BukkitSetupUtils extends SetupUtils {
private final PlotAreaManager plotAreaManager;
private final YamlConfiguration worldConfiguration;
private final File worldFile;
@Inject
public BukkitSetupUtils(
final @NonNull PlotAreaManager plotAreaManager,
@WorldConfig final @NonNull YamlConfiguration worldConfiguration,
@WorldFile final @NonNull File worldFile
) {
this.plotAreaManager = plotAreaManager;
this.worldConfiguration = worldConfiguration;
this.worldFile = worldFile;
}
@Override
public void updateGenerators(final boolean force) {
if (loaded && !SetupUtils.generators.isEmpty() && !force) {
return;
}
String testWorld = "CheckingPlotSquaredGenerator";
for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
try {
if (plugin.isEnabled()) {
ChunkGenerator generator = plugin.getDefaultWorldGenerator(testWorld, "");
if (generator != null) {
PlotSquared.get().removePlotAreas(testWorld);
String name = plugin.getDescription().getName();
GeneratorWrapper<?> wrapped;
if (generator instanceof GeneratorWrapper<?>) {
wrapped = (GeneratorWrapper<?>) generator;
} else {
wrapped = new BukkitPlotGenerator(testWorld, generator, this.plotAreaManager);
}
SetupUtils.generators.put(name, wrapped);
}
}
} catch (Throwable e) { // Recover from third party generator error
e.printStackTrace();
}
}
loaded = true;
}
@Override
public void unload(String worldName, boolean save) {
TaskManager.runTask(() -> {
World world = Bukkit.getWorld(worldName);
if (world == null) {
return;
}
Location location = Bukkit.getWorlds().get(0).getSpawnLocation();
for (Player player : world.getPlayers()) {
player.teleport(location);
}
if (save) {
for (Chunk chunk : world.getLoadedChunks()) {
chunk.unload(true);
}
} else {
for (Chunk chunk : world.getLoadedChunks()) {
chunk.unload(false);
}
}
Bukkit.unloadWorld(world, false);
});
}
@Override
public String setupWorld(PlotAreaBuilder builder) {
this.updateGenerators(false);
ConfigurationNode[] steps = builder.settingsNodesWrapper() == null ?
new ConfigurationNode[0] : builder.settingsNodesWrapper().getSettingsNodes();
String world = builder.worldName();
PlotAreaType type = builder.plotAreaType();
String worldPath = "worlds." + builder.worldName();
switch (type) {
case PARTIAL -> {
if (builder.areaName() != null) {
if (!this.worldConfiguration.contains(worldPath)) {
this.worldConfiguration.createSection(worldPath);
}
ConfigurationSection worldSection =
this.worldConfiguration.getConfigurationSection(worldPath);
String areaName = builder.areaName() + "-" + builder.minimumId() + "-" + builder.maximumId();
String areaPath = "areas." + areaName;
if (!worldSection.contains(areaPath)) {
worldSection.createSection(areaPath);
}
ConfigurationSection areaSection =
worldSection.getConfigurationSection(areaPath);
HashMap<String, Object> options = new HashMap<>();
for (ConfigurationNode step : steps) {
options.put(step.getConstant(), step.getValue());
}
options.put("generator.type", builder.plotAreaType().toString());
options.put("generator.terrain", builder.terrainType().toString());
options.put("generator.plugin", builder.plotManager());
if (builder.generatorName() != null && !builder.generatorName()
.equals(builder.plotManager())) {
options.put("generator.init", builder.generatorName());
}
for (Entry<String, Object> entry : options.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (worldSection.contains(key)) {
Object current = worldSection.get(key);
if (!Objects.equals(value, current)) {
areaSection.set(key, value);
}
} else {
worldSection.set(key, value);
}
}
}
GeneratorWrapper<?> gen = SetupUtils.generators.get(builder.generatorName());
if (gen != null && gen.isFull()) {
builder.generatorName(null);
}
}
case AUGMENTED -> {
if (!builder.plotManager().endsWith(":single")) {
if (!this.worldConfiguration.contains(worldPath)) {
this.worldConfiguration.createSection(worldPath);
}
if (steps.length != 0) {
ConfigurationSection worldSection =
this.worldConfiguration.getConfigurationSection(worldPath);
for (ConfigurationNode step : steps) {
worldSection.set(step.getConstant(), step.getValue());
}
}
this.worldConfiguration
.set("worlds." + world + ".generator.type", builder.plotAreaType().toString());
this.worldConfiguration
.set("worlds." + world + ".generator.terrain", builder.terrainType().toString());
this.worldConfiguration
.set("worlds." + world + ".generator.plugin", builder.plotManager());
if (builder.generatorName() != null && !builder.generatorName()
.equals(builder.plotManager())) {
this.worldConfiguration
.set("worlds." + world + ".generator.init", builder.generatorName());
}
}
GeneratorWrapper<?> gen = SetupUtils.generators.get(builder.generatorName());
if (gen != null && gen.isFull()) {
builder.generatorName(null);
}
}
case NORMAL -> {
if (steps.length != 0) {
if (!this.worldConfiguration.contains(worldPath)) {
this.worldConfiguration.createSection(worldPath);
}
ConfigurationSection worldSection =
this.worldConfiguration.getConfigurationSection(worldPath);
for (ConfigurationNode step : steps) {
worldSection.set(step.getConstant(), step.getValue());
}
}
}
}
try {
this.worldConfiguration.save(this.worldFile);
} catch (IOException e) {
e.printStackTrace();
}
Objects.requireNonNull(PlotSquared.platform()).worldManager()
.handleWorldCreation(builder.worldName(), builder.generatorName());
if (Bukkit.getWorld(world) != null) {
return world;
}
return builder.worldName();
}
@Override
public String getGenerator(PlotArea plotArea) {
if (SetupUtils.generators.isEmpty()) {
updateGenerators(false);
}
World world = Bukkit.getWorld(plotArea.getWorldName());
if (world == null) {
return null;
}
ChunkGenerator generator = world.getGenerator();
if (!(generator instanceof BukkitPlotGenerator)) {
return null;
}
for (Entry<String, GeneratorWrapper<?>> entry : SetupUtils.generators.entrySet()) {
GeneratorWrapper<?> current = entry.getValue();
if (current.equals(generator)) {
return entry.getKey();
}
}
return null;
}
}

View File

@ -1,580 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.util;
import com.google.inject.Singleton;
import com.plotsquared.bukkit.BukkitPlatform;
import com.plotsquared.bukkit.player.BukkitPlayer;
import com.plotsquared.bukkit.player.BukkitPlayerManager;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.caption.Caption;
import com.plotsquared.core.configuration.caption.LocaleHolder;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.util.BlockUtil;
import com.plotsquared.core.util.MathMan;
import com.plotsquared.core.util.PlayerManager;
import com.plotsquared.core.util.StringComparison;
import com.plotsquared.core.util.WorldUtil;
import com.plotsquared.core.util.task.TaskManager;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.bukkit.BukkitWorld;
import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BlockCategories;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockType;
import com.sk89q.worldedit.world.block.BlockTypes;
import io.papermc.lib.PaperLib;
import net.kyori.adventure.platform.bukkit.BukkitAudiences;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.Template;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.Sign;
import org.bukkit.block.data.Directional;
import org.bukkit.block.data.type.WallSign;
import org.bukkit.entity.Allay;
import org.bukkit.entity.Ambient;
import org.bukkit.entity.Animals;
import org.bukkit.entity.AreaEffectCloud;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Boss;
import org.bukkit.entity.EnderCrystal;
import org.bukkit.entity.EnderSignal;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.EvokerFangs;
import org.bukkit.entity.ExperienceOrb;
import org.bukkit.entity.Explosive;
import org.bukkit.entity.FallingBlock;
import org.bukkit.entity.Firework;
import org.bukkit.entity.Ghast;
import org.bukkit.entity.Hanging;
import org.bukkit.entity.IronGolem;
import org.bukkit.entity.Item;
import org.bukkit.entity.LightningStrike;
import org.bukkit.entity.Monster;
import org.bukkit.entity.NPC;
import org.bukkit.entity.Phantom;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.Shulker;
import org.bukkit.entity.Slime;
import org.bukkit.entity.Snowman;
import org.bukkit.entity.Tameable;
import org.bukkit.entity.Vehicle;
import org.bukkit.entity.WaterMob;
import org.checkerframework.checker.index.qual.NonNegative;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.function.Consumer;
import java.util.function.IntConsumer;
import java.util.stream.Stream;
@SuppressWarnings({"unused", "WeakerAccess"})
@Singleton
public class BukkitUtil extends WorldUtil {
public static final BukkitAudiences BUKKIT_AUDIENCES = BukkitAudiences.create(BukkitPlatform.getPlugin(BukkitPlatform.class));
public static final LegacyComponentSerializer LEGACY_COMPONENT_SERIALIZER = LegacyComponentSerializer.legacySection();
public static final MiniMessage MINI_MESSAGE = MiniMessage.builder().build();
private static final Logger LOGGER = LogManager.getLogger("PlotSquared/" + BukkitUtil.class.getSimpleName());
private final Collection<BlockType> tileEntityTypes = new HashSet<>();
/**
* Turn a Bukkit {@link Player} into a PlotSquared {@link PlotPlayer}
*
* @param player Bukkit player
* @return PlotSquared player
*/
public static @NonNull BukkitPlayer adapt(final @NonNull Player player) {
final PlayerManager<?, ?> playerManager = PlotSquared.platform().playerManager();
return ((BukkitPlayerManager) playerManager).getPlayer(player);
}
/**
* Turn a Bukkit {@link org.bukkit.Location} into a PlotSquared {@link Location}.
* This only copies the 4-tuple (world,x,y,z) and does not include the yaw and the pitch
*
* @param location Bukkit location
* @return PlotSquared location
*/
public static @NonNull Location adapt(final org.bukkit.@NonNull Location location) {
return Location
.at(
com.plotsquared.bukkit.util.BukkitWorld.of(location.getWorld()),
MathMan.roundInt(location.getX()),
MathMan.roundInt(location.getY()),
MathMan.roundInt(location.getZ())
);
}
/**
* Turn a Bukkit {@link org.bukkit.Location} into a PlotSquared {@link Location}.
* This copies the entire 6-tuple (world,x,y,z,yaw,pitch).
*
* @param location Bukkit location
* @return PlotSquared location
*/
public static @NonNull Location adaptComplete(final org.bukkit.@NonNull Location location) {
return Location
.at(
com.plotsquared.bukkit.util.BukkitWorld.of(location.getWorld()),
MathMan.roundInt(location.getX()),
MathMan.roundInt(location.getY()),
MathMan.roundInt(location.getZ()),
location.getYaw(),
location.getPitch()
);
}
/**
* Turn a PlotSquared {@link Location} into a Bukkit {@link org.bukkit.Location}.
* This only copies the 4-tuple (world,x,y,z) and does not include the yaw and the pitch
*
* @param location PlotSquared location
* @return Bukkit location
*/
public static org.bukkit.@NonNull Location adapt(final @NonNull Location location) {
return new org.bukkit.Location(
(World) location.getWorld().getPlatformWorld(),
location.getX(),
location.getY(),
location.getZ()
);
}
/**
* Get a Bukkit {@link World} from its name
*
* @param string World name
* @return World if it exists, or {@code null}
*/
public static @Nullable World getWorld(final @NonNull String string) {
return Bukkit.getWorld(string);
}
private static void ensureLoaded(
final @NonNull String world,
final int x,
final int z,
final @NonNull Consumer<Chunk> chunkConsumer
) {
PaperLib.getChunkAtAsync(Objects.requireNonNull(getWorld(world)), x >> 4, z >> 4, true)
.thenAccept(chunk -> ensureMainThread(chunkConsumer, chunk));
}
private static void ensureLoaded(final @NonNull Location location, final @NonNull Consumer<Chunk> chunkConsumer) {
PaperLib.getChunkAtAsync(adapt(location), true).thenAccept(chunk -> ensureMainThread(chunkConsumer, chunk));
}
private static <T> void ensureMainThread(final @NonNull Consumer<T> consumer, final @NonNull T value) {
if (Bukkit.isPrimaryThread()) {
consumer.accept(value);
} else {
Bukkit.getScheduler().runTask(BukkitPlatform.getPlugin(BukkitPlatform.class), () -> consumer.accept(value));
}
}
@Override
public boolean isBlockSame(final @NonNull BlockState block1, final @NonNull BlockState block2) {
if (block1.equals(block2)) {
return true;
}
final Material mat1 = BukkitAdapter.adapt(block1.getBlockType());
final Material mat2 = BukkitAdapter.adapt(block2.getBlockType());
return mat1 == mat2;
}
@Override
public boolean isWorld(final @NonNull String worldName) {
return getWorld(worldName) != null;
}
@Override
public void getBiome(final @NonNull String world, final int x, final int z, final @NonNull Consumer<BiomeType> result) {
ensureLoaded(world, x, z, chunk -> result.accept(BukkitAdapter.adapt(getWorld(world).getBiome(x, z))));
}
@Override
public @NonNull BiomeType getBiomeSynchronous(final @NonNull String world, final int x, final int z) {
return BukkitAdapter.adapt(Objects.requireNonNull(getWorld(world)).getBiome(x, z));
}
@Override
public void getHighestBlock(final @NonNull String world, final int x, final int z, final @NonNull IntConsumer result) {
ensureLoaded(world, x, z, chunk -> {
final World bukkitWorld = Objects.requireNonNull(getWorld(world));
// Skip top and bottom block
int air = 1;
int maxY = com.plotsquared.bukkit.util.BukkitWorld.getMaxWorldHeight(bukkitWorld);
int minY = com.plotsquared.bukkit.util.BukkitWorld.getMinWorldHeight(bukkitWorld);
for (int y = maxY - 1; y >= minY; y--) {
Block block = bukkitWorld.getBlockAt(x, y, z);
Material type = block.getType();
if (type.isSolid()) {
if (air > 1) {
result.accept(y);
return;
}
air = 0;
} else {
if (block.isLiquid()) {
result.accept(y);
return;
}
air++;
}
}
result.accept(bukkitWorld.getMaxHeight() - 1);
});
}
@Override
@NonNegative
public int getHighestBlockSynchronous(final @NonNull String world, final int x, final int z) {
final World bukkitWorld = Objects.requireNonNull(getWorld(world));
// Skip top and bottom block
int air = 1;
int maxY = com.plotsquared.bukkit.util.BukkitWorld.getMaxWorldHeight(bukkitWorld);
int minY = com.plotsquared.bukkit.util.BukkitWorld.getMinWorldHeight(bukkitWorld);
for (int y = maxY - 1; y >= minY; y--) {
Block block = bukkitWorld.getBlockAt(x, y, z);
Material type = block.getType();
if (type.isSolid()) {
if (air > 1) {
return y;
}
air = 0;
} else {
if (block.isLiquid()) {
return y;
}
air++;
}
}
return bukkitWorld.getMaxHeight() - 1;
}
@Override
public @NonNull String[] getSignSynchronous(final @NonNull Location location) {
Block block = Objects.requireNonNull(getWorld(location.getWorldName())).getBlockAt(
location.getX(),
location.getY(),
location.getZ()
);
try {
return TaskManager.getPlatformImplementation().sync(() -> {
if (block.getState() instanceof Sign sign) {
return sign.getLines();
}
return new String[0];
});
} catch (final Exception e) {
e.printStackTrace();
}
return new String[0];
}
@Override
public @NonNull Location getSpawn(final @NonNull String world) {
final org.bukkit.Location temp = getWorld(world).getSpawnLocation();
return Location.at(world, temp.getBlockX(), temp.getBlockY(), temp.getBlockZ(), temp.getYaw(), temp.getPitch());
}
@Override
public void setSpawn(final @NonNull Location location) {
final World world = getWorld(location.getWorldName());
if (world != null) {
world.setSpawnLocation(location.getX(), location.getY(), location.getZ());
}
}
@Override
public void saveWorld(final @NonNull String worldName) {
final World world = getWorld(worldName);
if (world != null) {
world.save();
}
}
@Override
@SuppressWarnings("deprecation")
public void setSign(
final @NonNull Location location, final @NonNull Caption[] lines,
final @NonNull Template... replacements
) {
ensureLoaded(location.getWorldName(), location.getX(), location.getZ(), chunk -> {
PlotArea area = location.getPlotArea();
final World world = getWorld(location.getWorldName());
final Block block = world.getBlockAt(location.getX(), location.getY(), location.getZ());
final Material type = block.getType();
if (type != Material.LEGACY_SIGN && type != Material.LEGACY_WALL_SIGN) {
BlockFace facing = BlockFace.NORTH;
if (!world.getBlockAt(location.getX(), location.getY(), location.getZ() + 1).getType().isSolid()) {
if (world.getBlockAt(location.getX() - 1, location.getY(), location.getZ()).getType().isSolid()) {
facing = BlockFace.EAST;
} else if (world.getBlockAt(location.getX() + 1, location.getY(), location.getZ()).getType().isSolid()) {
facing = BlockFace.WEST;
} else if (world.getBlockAt(location.getX(), location.getY(), location.getZ() - 1).getType().isSolid()) {
facing = BlockFace.SOUTH;
}
}
if (PlotSquared.platform().serverVersion()[1] == 13) {
block.setType(Material.valueOf(area.legacySignMaterial()), false);
} else {
block.setType(Material.valueOf(area.signMaterial()), false);
}
if (!(block.getBlockData() instanceof WallSign)) {
throw new RuntimeException("Something went wrong generating a sign");
}
final Directional sign = (Directional) block.getBlockData();
sign.setFacing(facing);
block.setBlockData(sign, false);
}
final org.bukkit.block.BlockState blockstate = block.getState();
if (blockstate instanceof final Sign sign) {
for (int i = 0; i < lines.length; i++) {
sign.setLine(i, LEGACY_COMPONENT_SERIALIZER
.serialize(MINI_MESSAGE.parse(lines[i].getComponent(LocaleHolder.console()), replacements)));
}
sign.update(true, false);
}
});
}
@Override
public @NonNull StringComparison<BlockState>.ComparisonResult getClosestBlock(@NonNull String name) {
BlockState state = BlockUtil.get(name);
return new StringComparison<BlockState>().new ComparisonResult(1, state);
}
@Override
public com.sk89q.worldedit.world.@NonNull World getWeWorld(final @NonNull String world) {
return new BukkitWorld(Bukkit.getWorld(world));
}
@Override
public void refreshChunk(int x, int z, String world) {
Bukkit.getWorld(world).refreshChunk(x, z);
}
@Override
public void getBlock(final @NonNull Location location, final @NonNull Consumer<BlockState> result) {
ensureLoaded(location, chunk -> {
final World world = getWorld(location.getWorldName());
final Block block = Objects.requireNonNull(world).getBlockAt(location.getX(), location.getY(), location.getZ());
result.accept(Objects.requireNonNull(BukkitAdapter.asBlockType(block.getType())).getDefaultState());
});
}
@Override
public @NonNull BlockState getBlockSynchronous(final @NonNull Location location) {
final World world = getWorld(location.getWorldName());
final Block block = Objects.requireNonNull(world).getBlockAt(location.getX(), location.getY(), location.getZ());
return Objects.requireNonNull(BukkitAdapter.asBlockType(block.getType())).getDefaultState();
}
@Override
@NonNegative
public double getHealth(final @NonNull PlotPlayer<?> player) {
return Objects.requireNonNull(Bukkit.getPlayer(player.getUUID())).getHealth();
}
@Override
@NonNegative
public int getFoodLevel(final @NonNull PlotPlayer<?> player) {
return Objects.requireNonNull(Bukkit.getPlayer(player.getUUID())).getFoodLevel();
}
@Override
public void setHealth(final @NonNull PlotPlayer<?> player, @NonNegative final double health) {
Objects.requireNonNull(Bukkit.getPlayer(player.getUUID())).setHealth(health);
}
@Override
public void setFoodLevel(final @NonNull PlotPlayer<?> player, @NonNegative final int foodLevel) {
Bukkit.getPlayer(player.getUUID()).setFoodLevel(foodLevel);
}
@Override
public @NonNull Set<com.sk89q.worldedit.world.entity.EntityType> getTypesInCategory(final @NonNull String category) {
final Collection<Class<?>> allowedInterfaces = new HashSet<>();
switch (category) {
case "animal" -> {
allowedInterfaces.add(IronGolem.class);
allowedInterfaces.add(Snowman.class);
allowedInterfaces.add(Animals.class);
allowedInterfaces.add(WaterMob.class);
allowedInterfaces.add(Ambient.class);
if (PlotSquared.platform().serverVersion()[1] >= 19) {
allowedInterfaces.add(Allay.class);
}
}
case "tameable" -> allowedInterfaces.add(Tameable.class);
case "vehicle" -> allowedInterfaces.add(Vehicle.class);
case "hostile" -> {
allowedInterfaces.add(Shulker.class);
allowedInterfaces.add(Monster.class);
allowedInterfaces.add(Boss.class);
allowedInterfaces.add(Slime.class);
allowedInterfaces.add(Ghast.class);
allowedInterfaces.add(Phantom.class);
allowedInterfaces.add(EnderCrystal.class);
}
case "hanging" -> allowedInterfaces.add(Hanging.class);
case "villager" -> allowedInterfaces.add(NPC.class);
case "projectile" -> allowedInterfaces.add(Projectile.class);
case "other" -> {
allowedInterfaces.add(ArmorStand.class);
allowedInterfaces.add(FallingBlock.class);
allowedInterfaces.add(Item.class);
allowedInterfaces.add(Explosive.class);
allowedInterfaces.add(AreaEffectCloud.class);
allowedInterfaces.add(EvokerFangs.class);
allowedInterfaces.add(LightningStrike.class);
allowedInterfaces.add(ExperienceOrb.class);
allowedInterfaces.add(EnderSignal.class);
allowedInterfaces.add(Firework.class);
}
case "player" -> allowedInterfaces.add(Player.class);
default -> LOGGER.error("Unknown entity category requested: {}", category);
}
final Set<com.sk89q.worldedit.world.entity.EntityType> types = new HashSet<>();
outer:
for (final EntityType bukkitType : EntityType.values()) {
final Class<? extends Entity> entityClass = bukkitType.getEntityClass();
if (entityClass == null) {
continue;
}
for (final Class<?> allowedInterface : allowedInterfaces) {
if (allowedInterface.isAssignableFrom(entityClass)) {
types.add(BukkitAdapter.adapt(bukkitType));
continue outer;
}
}
}
return types;
}
@Override
public @NonNull Collection<BlockType> getTileEntityTypes() {
if (this.tileEntityTypes.isEmpty()) {
// Categories
tileEntityTypes.addAll(BlockCategories.BANNERS.getAll());
tileEntityTypes.addAll(BlockCategories.SIGNS.getAll());
tileEntityTypes.addAll(BlockCategories.BEDS.getAll());
tileEntityTypes.addAll(BlockCategories.FLOWER_POTS.getAll());
// Individual Types
// Add these from strings
Stream.of(
"barrel",
"beacon",
"beehive",
"bee_nest",
"bell",
"blast_furnace",
"brewing_stand",
"campfire",
"chest",
"ender_chest",
"trapped_chest",
"command_block",
"end_gateway",
"hopper",
"jigsaw",
"jubekox",
"lectern",
"note_block",
"black_shulker_box",
"blue_shulker_box",
"brown_shulker_box",
"cyan_shulker_box",
"gray_shulker_box",
"green_shulker_box",
"light_blue_shulker_box",
"light_gray_shulker_box",
"lime_shulker_box",
"magenta_shulker_box",
"orange_shulker_box",
"pink_shulker_box",
"purple_shulker_box",
"red_shulker_box",
"shulker_box",
"white_shulker_box",
"yellow_shulker_box",
"smoker",
"structure_block",
"structure_void"
)
.map(BlockTypes::get).filter(Objects::nonNull).forEach(tileEntityTypes::add);
}
return this.tileEntityTypes;
}
@Override
@NonNegative
public int getTileEntityCount(final @NonNull String world, final @NonNull BlockVector2 chunk) {
return Objects.requireNonNull(getWorld(world)).
getChunkAt(chunk.getBlockX(), chunk.getBlockZ()).getTileEntities().length;
}
@Override
public Set<BlockVector2> getChunkChunks(String world) {
Set<BlockVector2> chunks = super.getChunkChunks(world);
if (Bukkit.isPrimaryThread()) {
for (Chunk chunk : Objects.requireNonNull(Bukkit.getWorld(world)).getLoadedChunks()) {
BlockVector2 loc = BlockVector2.at(chunk.getX() >> 5, chunk.getZ() >> 5);
chunks.add(loc);
}
} else {
final Semaphore semaphore = new Semaphore(1);
try {
semaphore.acquire();
Bukkit.getScheduler().runTask(BukkitPlatform.getPlugin(BukkitPlatform.class), () -> {
for (Chunk chunk : Objects.requireNonNull(Bukkit.getWorld(world)).getLoadedChunks()) {
BlockVector2 loc = BlockVector2.at(chunk.getX() >> 5, chunk.getZ() >> 5);
chunks.add(loc);
}
semaphore.release();
});
semaphore.acquireUninterruptibly();
} catch (final Exception e) {
e.printStackTrace();
}
}
return chunks;
}
}

View File

@ -1,147 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.util;
import com.google.common.collect.Maps;
import com.plotsquared.core.location.World;
import org.bukkit.Bukkit;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.Map;
public class BukkitWorld implements World<org.bukkit.World> {
private static final Map<String, BukkitWorld> worldMap = Maps.newHashMap();
private static final boolean HAS_MIN_Y;
static {
boolean temp;
try {
org.bukkit.World.class.getMethod("getMinHeight");
temp = true;
} catch (NoSuchMethodException e) {
temp = false;
}
HAS_MIN_Y = temp;
}
private final org.bukkit.World world;
private BukkitWorld(final org.bukkit.World world) {
this.world = world;
}
/**
* Get a new {@link BukkitWorld} from a world name
*
* @param worldName World name
* @return World instance
*/
public static @NonNull BukkitWorld of(final @NonNull String worldName) {
final org.bukkit.World bukkitWorld = Bukkit.getWorld(worldName);
if (bukkitWorld == null) {
throw new IllegalArgumentException(String.format("There is no world with the name '%s'", worldName));
}
return of(bukkitWorld);
}
/**
* Get a new {@link BukkitWorld} from a Bukkit world
*
* @param world Bukkit world
* @return World instance
*/
public static @NonNull BukkitWorld of(final org.bukkit.World world) {
BukkitWorld bukkitWorld = worldMap.get(world.getName());
if (bukkitWorld != null && bukkitWorld.getPlatformWorld().equals(world)) {
return bukkitWorld;
}
bukkitWorld = new BukkitWorld(world);
worldMap.put(world.getName(), bukkitWorld);
return bukkitWorld;
}
/**
* Get the min world height from a Bukkit {@link org.bukkit.World}. Inclusive
*
* @since 6.6.0
*/
public static int getMinWorldHeight(org.bukkit.World world) {
return HAS_MIN_Y ? world.getMinHeight() : 0;
}
/**
* Get the max world height from a Bukkit {@link org.bukkit.World}. Exclusive
*
* @since 6.6.0
*/
public static int getMaxWorldHeight(org.bukkit.World world) {
return HAS_MIN_Y ? world.getMaxHeight() : 256;
}
@Override
public org.bukkit.World getPlatformWorld() {
return this.world;
}
@Override
public @NonNull String getName() {
return this.world.getName();
}
@Override
public int getMinHeight() {
return getMinWorldHeight(world);
}
@Override
public int getMaxHeight() {
return getMaxWorldHeight(world) - 1;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final BukkitWorld that = (BukkitWorld) o;
return world.equals(that.world);
}
@Override
public int hashCode() {
return world.hashCode();
}
/**
* @deprecated This method is not meant to be invoked or overridden, with no replacement.
*/
@Deprecated(forRemoval = true, since = "6.6.0")
protected boolean canEqual(final Object other) {
return other instanceof BukkitWorld;
}
public String toString() {
return "BukkitWorld(world=" + this.world + ")";
}
}

View File

@ -1,131 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.util;
import com.plotsquared.bukkit.entity.EntityWrapper;
import com.plotsquared.bukkit.entity.ReplicatingEntityWrapper;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.location.PlotLoc;
import com.sk89q.worldedit.bukkit.BukkitWorld;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.world.block.BaseBlock;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class ContentMap {
private static final Logger LOGGER = LogManager.getLogger("PlotSquared/" + ContentMap.class.getSimpleName());
final Set<EntityWrapper> entities;
final Map<PlotLoc, BaseBlock[]> allBlocks;
ContentMap() {
this.entities = new HashSet<>();
this.allBlocks = new HashMap<>();
}
public void saveRegion(BukkitWorld world, int x1, int x2, int z1, int z2) {
if (z1 > z2) {
int tmp = z1;
z1 = z2;
z2 = tmp;
}
if (x1 > x2) {
int tmp = x1;
x1 = x2;
x2 = tmp;
}
for (int x = x1; x <= x2; x++) {
for (int z = z1; z <= z2; z++) {
saveBlocks(world, x, z);
}
}
}
void saveEntitiesOut(Chunk chunk, CuboidRegion region) {
for (Entity entity : chunk.getEntities()) {
Location location = BukkitUtil.adapt(entity.getLocation());
int x = location.getX();
int z = location.getZ();
if (BukkitChunkManager.isIn(region, x, z)) {
continue;
}
if (entity.getVehicle() != null) {
continue;
}
EntityWrapper wrap = new ReplicatingEntityWrapper(entity, (short) 2);
wrap.saveEntity();
this.entities.add(wrap);
}
}
void saveEntitiesIn(Chunk chunk, CuboidRegion region, boolean delete) {
for (Entity entity : chunk.getEntities()) {
Location location = BukkitUtil.adapt(entity.getLocation());
int x = location.getX();
int z = location.getZ();
if (!BukkitChunkManager.isIn(region, x, z)) {
continue;
}
if (entity.getVehicle() != null) {
continue;
}
EntityWrapper wrap = new ReplicatingEntityWrapper(entity, (short) 2);
wrap.saveEntity();
this.entities.add(wrap);
if (delete) {
if (!(entity instanceof Player)) {
entity.remove();
}
}
}
}
void restoreEntities(World world) {
for (EntityWrapper entity : this.entities) {
try {
entity.spawn(world, 0, 0);
} catch (Exception e) {
LOGGER.error("Failed to restore entity", e);
}
}
this.entities.clear();
}
private void saveBlocks(BukkitWorld world, int x, int z) {
BaseBlock[] ids = new BaseBlock[world.getMaxY() - world.getMinY() + 1];
for (short yIndex = 0; yIndex <= world.getMaxY() - world.getMinY(); yIndex++) {
BaseBlock block = world.getFullBlock(BlockVector3.at(x, yIndex + world.getMinY(), z));
ids[yIndex] = block;
}
PlotLoc loc = new PlotLoc(x, z);
this.allBlocks.put(loc, ids);
}
}

View File

@ -1,71 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.util;
import com.plotsquared.bukkit.generator.BukkitAugmentedGenerator;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.generator.GeneratorWrapper;
import com.plotsquared.core.util.SetupUtils;
import org.bukkit.World;
import org.bukkit.generator.ChunkGenerator;
import java.lang.reflect.Field;
import java.util.ArrayList;
public class SetGenCB {
public static void setGenerator(World world) throws Exception {
PlotSquared.platform().setupUtils().updateGenerators(false);
PlotSquared.get().removePlotAreas(world.getName());
ChunkGenerator gen = world.getGenerator();
if (gen == null) {
return;
}
String name = gen.getClass().getCanonicalName();
boolean set = false;
for (GeneratorWrapper<?> wrapper : SetupUtils.generators.values()) {
ChunkGenerator newGen = (ChunkGenerator) wrapper.getPlatformGenerator();
if (newGen == null) {
newGen = (ChunkGenerator) wrapper;
}
if (newGen.getClass().getCanonicalName().equals(name)) {
// set generator
Field generator = world.getClass().getDeclaredField("generator");
Field populators = world.getClass().getDeclaredField("populators");
generator.setAccessible(true);
populators.setAccessible(true);
// Set populators (just in case)
populators.set(world, new ArrayList<>());
// Set generator
generator.set(world, newGen);
populators.set(world, newGen.getDefaultPopulators(world));
// end
set = true;
break;
}
}
if (!set) {
world.getPopulators()
.removeIf(blockPopulator -> blockPopulator instanceof BukkitAugmentedGenerator);
}
PlotSquared.get()
.loadWorld(world.getName(), PlotSquared.platform().getGenerator(world.getName(), null));
}
}

View File

@ -1,95 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.util;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;
import com.google.inject.Inject;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.PlotVersion;
import com.plotsquared.core.configuration.Settings;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bukkit.Bukkit;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;
import javax.net.ssl.HttpsURLConnection;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class UpdateUtility implements Listener {
private static final Logger LOGGER = LogManager.getLogger("PlotSquared/" + UpdateUtility.class.getSimpleName());
public static PlotVersion internalVersion;
public static String spigotVersion;
public static boolean hasUpdate;
private static BukkitTask task;
public final JavaPlugin javaPlugin;
private boolean notify = true;
@Inject
public UpdateUtility(final JavaPlugin javaPlugin) {
this.javaPlugin = javaPlugin;
internalVersion = PlotSquared.get().getVersion();
}
@SuppressWarnings({"deprecation", "DefaultCharset"}) // Suppress Json deprecation, we can't use features from gson 2.8.1 and newer yet
public void updateChecker() {
task = Bukkit.getScheduler().runTaskTimerAsynchronously(this.javaPlugin, () -> {
try {
HttpsURLConnection connection = (HttpsURLConnection) new URL(
"https://api.spigotmc.org/simple/0.1/index.php?action=getResource&id=77506")
.openConnection();
connection.setRequestMethod("GET");
JsonObject result = new JsonParser()
.parse(new JsonReader(new InputStreamReader(connection.getInputStream())))
.getAsJsonObject();
spigotVersion = result.get("current_version").getAsString();
} catch (IOException e) {
LOGGER.error("Unable to check for updates. Error: {}", e.getMessage());
return;
}
if (internalVersion.isLaterVersion(spigotVersion)) {
LOGGER.info("There appears to be a PlotSquared update available!");
LOGGER.info("You are running version {}, the latest version is {}",
internalVersion.versionString(), spigotVersion
);
LOGGER.info("https://www.spigotmc.org/resources/77506/updates");
hasUpdate = true;
if (Settings.UpdateChecker.NOTIFY_ONCE) {
cancelTask();
}
} else if (notify) {
notify = false;
LOGGER.info("Congratulations! You are running the latest PlotSquared version");
}
}, 0L, (long) Settings.UpdateChecker.POLL_RATE * 60 * 20);
}
private void cancelTask() {
Bukkit.getScheduler().runTaskLater(javaPlugin, () -> task.cancel(), 20L);
}
}

View File

@ -1,123 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.util.fawe;
import com.fastasyncworldedit.bukkit.regions.plotsquared.FaweDelegateRegionManager;
import com.google.inject.Inject;
import com.plotsquared.bukkit.util.BukkitRegionManager;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.generator.HybridPlotManager;
import com.plotsquared.core.inject.factory.ProgressSubscriberFactory;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.PlotManager;
import com.plotsquared.core.queue.GlobalBlockQueue;
import com.plotsquared.core.queue.QueueCoordinator;
import com.plotsquared.core.util.WorldUtil;
import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.world.biome.BiomeType;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.Set;
public class FaweRegionManager extends BukkitRegionManager {
private final FaweDelegateRegionManager delegate = new FaweDelegateRegionManager();
@Inject
public FaweRegionManager(WorldUtil worldUtil, GlobalBlockQueue blockQueue, ProgressSubscriberFactory subscriberFactory) {
super(worldUtil, blockQueue, subscriberFactory);
}
@Override
public boolean setCuboids(
final @NonNull PlotArea area,
final @NonNull Set<CuboidRegion> regions,
final @NonNull Pattern blocks,
int minY,
int maxY,
@Nullable PlotPlayer<?> actor,
@Nullable QueueCoordinator queue
) {
return delegate.setCuboids(area, regions, blocks, minY, maxY, queue.getCompleteTask());
}
@Override
public boolean notifyClear(PlotManager manager) {
if (!Settings.FAWE_Components.CLEAR || !(manager instanceof HybridPlotManager)) {
return false;
}
return delegate.notifyClear(manager);
}
@Override
public boolean handleClear(
@NonNull Plot plot,
@Nullable Runnable whenDone,
@NonNull PlotManager manager,
final @Nullable PlotPlayer<?> player
) {
if (!Settings.FAWE_Components.CLEAR || !(manager instanceof HybridPlotManager)) {
return false;
}
return delegate.handleClear(plot, whenDone, manager);
}
@Override
public void swap(
Location pos1,
Location pos2,
Location swapPos,
final @Nullable PlotPlayer<?> player,
final Runnable whenDone
) {
delegate.swap(pos1, pos2, swapPos, whenDone);
}
@Override
public void setBiome(CuboidRegion region, int extendBiome, BiomeType biome, String world, Runnable whenDone) {
delegate.setBiome(region, extendBiome, biome, world, whenDone);
}
@Override
public void setBiome(CuboidRegion region, int extendBiome, BiomeType biome, PlotArea area, Runnable whenDone) {
delegate.setBiome(region, extendBiome, biome, area.getWorldName(), whenDone);
}
@Override
public boolean copyRegion(
final @NonNull Location pos1,
final @NonNull Location pos2,
final @NonNull Location pos3,
final @Nullable PlotPlayer<?> player,
final @NonNull Runnable whenDone
) {
return delegate.copyRegion(pos1, pos2, pos3, whenDone);
}
@Override
public boolean regenerateRegion(final Location pos1, final Location pos2, boolean ignore, final Runnable whenDone) {
return delegate.regenerateRegion(pos1, pos2, ignore, whenDone);
}
}

View File

@ -1,82 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.util.fawe;
import com.fastasyncworldedit.bukkit.regions.plotsquared.FaweDelegateSchematicHandler;
import com.google.inject.Inject;
import com.plotsquared.core.inject.factory.ProgressSubscriberFactory;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.schematic.Schematic;
import com.plotsquared.core.queue.QueueCoordinator;
import com.plotsquared.core.util.SchematicHandler;
import com.plotsquared.core.util.WorldUtil;
import com.plotsquared.core.util.task.RunnableVal;
import com.sk89q.jnbt.CompoundTag;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.io.InputStream;
import java.net.URL;
import java.util.UUID;
public class FaweSchematicHandler extends SchematicHandler {
private final FaweDelegateSchematicHandler delegate = new FaweDelegateSchematicHandler();
@Inject
public FaweSchematicHandler(WorldUtil worldUtil, ProgressSubscriberFactory subscriberFactory) {
super(worldUtil, subscriberFactory);
}
@Override
public boolean restoreTile(QueueCoordinator queue, CompoundTag tag, int x, int y, int z) {
return false;
}
@Override
public void paste(
final Schematic schematic,
final Plot plot,
final int xOffset,
final int yOffset,
final int zOffset,
final boolean autoHeight,
final PlotPlayer<?> actor,
final RunnableVal<Boolean> whenDone
) {
delegate.paste(schematic, plot, xOffset, yOffset, zOffset, autoHeight, actor, whenDone);
}
@Override
public boolean save(CompoundTag tag, String path) {
return delegate.save(tag, path);
}
@SuppressWarnings("removal") // Just the override
@Override
public void upload(final CompoundTag tag, final UUID uuid, final String file, final RunnableVal<URL> whenDone) {
delegate.upload(tag, uuid, file, whenDone);
}
@Override
public Schematic getSchematic(@NonNull InputStream is) {
return delegate.getSchematic(is);
}
}

View File

@ -1,42 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.util.task;
import com.plotsquared.core.util.task.PlotSquaredTask;
import org.bukkit.scheduler.BukkitRunnable;
import org.checkerframework.checker.nullness.qual.NonNull;
/**
* Bukkit implementation of {@link PlotSquaredTask}
*/
public final class BukkitPlotSquaredTask extends BukkitRunnable implements PlotSquaredTask {
@NonNull
private final Runnable runnable;
public BukkitPlotSquaredTask(final @NonNull Runnable runnable) {
this.runnable = runnable;
}
@Override
public void runTask() {
this.runnable.run();
}
}

View File

@ -1,121 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.util.task;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.plotsquared.bukkit.BukkitPlatform;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.util.task.PlotSquaredTask;
import com.plotsquared.core.util.task.TaskManager;
import com.plotsquared.core.util.task.TaskTime;
import org.bukkit.Bukkit;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
* Bukkit implementation of {@link TaskManager} using
* by {@link org.bukkit.scheduler.BukkitScheduler} and {@link BukkitPlotSquaredTask}
*/
@Singleton
public class BukkitTaskManager extends TaskManager {
private final BukkitPlatform bukkitMain;
private final TaskTime.TimeConverter timeConverter;
@Inject
public BukkitTaskManager(
final @NonNull BukkitPlatform bukkitMain,
final TaskTime.@NonNull TimeConverter timeConverter
) {
this.bukkitMain = bukkitMain;
this.timeConverter = timeConverter;
}
@Override
public PlotSquaredTask taskRepeat(
final @NonNull Runnable runnable,
final @NonNull TaskTime taskTime
) {
final long ticks = this.timeConverter.toTicks(taskTime);
final BukkitPlotSquaredTask bukkitPlotSquaredTask = new BukkitPlotSquaredTask(runnable);
bukkitPlotSquaredTask.runTaskTimer(this.bukkitMain, ticks, ticks);
return bukkitPlotSquaredTask;
}
@Override
public PlotSquaredTask taskRepeatAsync(
final @NonNull Runnable runnable,
final @NonNull TaskTime taskTime
) {
final long ticks = this.timeConverter.toTicks(taskTime);
final BukkitPlotSquaredTask bukkitPlotSquaredTask = new BukkitPlotSquaredTask(runnable);
bukkitPlotSquaredTask.runTaskTimerAsynchronously(this.bukkitMain, ticks, ticks);
return bukkitPlotSquaredTask;
}
@Override
public void taskAsync(final @NonNull Runnable runnable) {
if (this.bukkitMain.isEnabled()) {
new BukkitPlotSquaredTask(runnable).runTaskAsynchronously(this.bukkitMain);
} else {
runnable.run();
}
}
@Override
public <T> T sync(final @NonNull Callable<T> function, final int timeout) throws Exception {
if (PlotSquared.get().isMainThread(Thread.currentThread())) {
return function.call();
}
return this.callMethodSync(function).get(timeout, TimeUnit.MILLISECONDS);
}
@Override
public <T> Future<T> callMethodSync(final @NonNull Callable<T> method) {
return Bukkit.getScheduler().callSyncMethod(this.bukkitMain, method);
}
@Override
public void task(final @NonNull Runnable runnable) {
new BukkitPlotSquaredTask(runnable).runTask(this.bukkitMain);
}
@Override
public void taskLater(
final @NonNull Runnable runnable,
final @NonNull TaskTime taskTime
) {
final long delay = this.timeConverter.toTicks(taskTime);
new BukkitPlotSquaredTask(runnable).runTaskLater(this.bukkitMain, delay);
}
@Override
public void taskLaterAsync(
final @NonNull Runnable runnable,
final @NonNull TaskTime taskTime
) {
final long delay = this.timeConverter.toTicks(taskTime);
new BukkitPlotSquaredTask(runnable).runTaskLaterAsynchronously(this.bukkitMain, delay);
}
}

View File

@ -1,43 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.util.task;
import com.plotsquared.core.util.task.TaskTime;
import org.bukkit.Bukkit;
import org.checkerframework.checker.index.qual.NonNegative;
/**
* Time converter that uses the server MSPT count to convert between
* different time units
*/
public final class PaperTimeConverter implements TaskTime.TimeConverter {
private static final long MIN_MS_PER_TICKS = 50L;
@Override
public long msToTicks(@NonNegative final long ms) {
return Math.max(1L, (long) (ms / Math.max(MIN_MS_PER_TICKS, Bukkit.getAverageTickTime())));
}
@Override
public long ticksToMs(@NonNegative final long ticks) {
return Math.max(1L, (long) (ticks * Math.max(MIN_MS_PER_TICKS, Bukkit.getAverageTickTime())));
}
}

View File

@ -1,41 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.util.task;
import com.plotsquared.core.util.task.TaskTime;
import org.checkerframework.checker.index.qual.NonNegative;
/**
* Naive time converter that assumes that all ticks are 50 milliseconds
*/
public final class SpigotTimeConverter implements TaskTime.TimeConverter {
private static final long MS_PER_TICKS = 50L;
@Override
public long msToTicks(@NonNegative final long ms) {
return Math.max(1L, ms / MS_PER_TICKS);
}
@Override
public long ticksToMs(@NonNegative final long ticks) {
return Math.max(1L, ticks * MS_PER_TICKS);
}
}

View File

@ -1,66 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.uuid;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import com.plotsquared.core.uuid.UUIDMapping;
import com.plotsquared.core.uuid.UUIDService;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
/**
* UUID service using the EssentialsX API
*/
public class EssentialsUUIDService implements UUIDService {
private final Essentials essentials;
public EssentialsUUIDService() {
this.essentials = Essentials.getPlugin(Essentials.class);
}
@Override
public @NonNull List<UUIDMapping> getNames(final @NonNull List<UUID> uuids) {
return Collections.emptyList();
}
@Override
public @NonNull List<UUIDMapping> getUUIDs(final @NonNull List<String> usernames) {
final List<UUIDMapping> mappings = new ArrayList<>(usernames.size());
for (final String username : usernames) {
try {
final User user = essentials.getUser(username);
if (user != null) {
final UUID uuid = user.getConfigUUID();
if (uuid != null) {
mappings.add(new UUIDMapping(uuid, username));
}
}
} catch (final Exception ignored) {
}
}
return mappings;
}
}

View File

@ -1,81 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.uuid;
import com.plotsquared.core.uuid.UUIDMapping;
import com.plotsquared.core.uuid.UUIDService;
import net.luckperms.api.LuckPerms;
import net.luckperms.api.model.user.UserManager;
import org.bukkit.Bukkit;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* UUID service that uses the LuckPerms API
*/
public class LuckPermsUUIDService implements UUIDService {
private final LuckPerms luckPerms;
public LuckPermsUUIDService() {
final RegisteredServiceProvider<LuckPerms> provider = Bukkit.getServicesManager().getRegistration(LuckPerms.class);
if (provider != null) {
this.luckPerms = provider.getProvider();
} else {
throw new IllegalStateException("LuckPerms not available");
}
}
@Override
public @NonNull List<UUIDMapping> getNames(final @NonNull List<UUID> uuids) {
final List<UUIDMapping> mappings = new ArrayList<>(uuids.size());
final UserManager userManager = this.luckPerms.getUserManager();
for (final UUID uuid : uuids) {
try {
final String username = userManager.lookupUsername(uuid).get();
if (username != null) {
mappings.add(new UUIDMapping(uuid, username));
}
} catch (final Exception ignored) {
}
}
return mappings;
}
@Override
public @NonNull List<UUIDMapping> getUUIDs(final @NonNull List<String> usernames) {
final List<UUIDMapping> mappings = new ArrayList<>(usernames.size());
final UserManager userManager = this.luckPerms.getUserManager();
for (final String username : usernames) {
try {
final UUID uuid = userManager.lookupUniqueId(username).get();
if (username != null) {
mappings.add(new UUIDMapping(uuid, username));
}
} catch (final Exception ignored) {
}
}
return mappings;
}
}

View File

@ -1,81 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.uuid;
import com.google.common.base.Charsets;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.uuid.UUIDMapping;
import com.plotsquared.core.uuid.UUIDService;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
/**
* UUID service that use {@link org.bukkit.OfflinePlayer offline players}
*/
public class OfflinePlayerUUIDService implements UUIDService {
@Override
public @NonNull List<UUIDMapping> getNames(final @NonNull List<UUID> uuids) {
if (Settings.UUID.FORCE_LOWERCASE || Bukkit.getWorlds().isEmpty()) {
return Collections.emptyList(); // This is useless now
}
final List<UUIDMapping> wrappers = new ArrayList<>(uuids.size());
for (final UUID uuid : uuids) {
final OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(uuid);
try {
if (offlinePlayer.hasPlayedBefore()) {
wrappers.add(new UUIDMapping(uuid, offlinePlayer.getName()));
}
} catch (final Exception ignored) {
} /* This can be safely ignored. If this happens, it is
probably because it's called before the worlds have
been loaded. This is bad, but does not break anything */
}
return wrappers;
}
@Override
public @NonNull List<UUIDMapping> getUUIDs(final @NonNull List<String> usernames) {
final List<UUIDMapping> wrappers = new ArrayList<>(usernames.size());
for (final String username : usernames) {
if (Settings.UUID.OFFLINE) {
if (Settings.UUID.FORCE_LOWERCASE) {
wrappers.add(new UUIDMapping(UUID.nameUUIDFromBytes(("OfflinePlayer:" +
username.toLowerCase()).getBytes(Charsets.UTF_8)), username));
} else {
wrappers.add(new UUIDMapping(UUID.nameUUIDFromBytes(("OfflinePlayer:" +
username).getBytes(Charsets.UTF_8)), username));
}
} else {
final OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(username);
if (offlinePlayer.hasPlayedBefore()) {
wrappers.add(new UUIDMapping(offlinePlayer.getUniqueId(), offlinePlayer.getName()));
}
}
}
return wrappers;
}
}

View File

@ -1,60 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.uuid;
import com.destroystokyo.paper.profile.PlayerProfile;
import com.plotsquared.core.uuid.UUIDMapping;
import com.plotsquared.core.uuid.UUIDService;
import org.bukkit.Bukkit;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* UUID service that uses the Paper profile API
*/
public class PaperUUIDService implements UUIDService {
@Override
public @NonNull List<UUIDMapping> getNames(final @NonNull List<UUID> uuids) {
final List<UUIDMapping> mappings = new ArrayList<>(uuids.size());
for (final UUID uuid : uuids) {
final PlayerProfile playerProfile = Bukkit.createProfile(uuid);
if ((playerProfile.isComplete() || playerProfile.completeFromCache()) && playerProfile.getId() != null) {
mappings.add(new UUIDMapping(playerProfile.getId(), playerProfile.getName()));
}
}
return mappings;
}
@Override
public @NonNull List<UUIDMapping> getUUIDs(final @NonNull List<String> usernames) {
final List<UUIDMapping> mappings = new ArrayList<>(usernames.size());
for (final String username : usernames) {
final PlayerProfile playerProfile = Bukkit.createProfile(username);
if ((playerProfile.isComplete() || playerProfile.completeFromCache()) && playerProfile.getId() != null) {
mappings.add(new UUIDMapping(playerProfile.getId(), playerProfile.getName()));
}
}
return mappings;
}
}

View File

@ -1,143 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.uuid;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.database.SQLite;
import com.plotsquared.core.util.FileUtils;
import com.plotsquared.core.uuid.UUIDMapping;
import com.plotsquared.core.uuid.UUIDService;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import java.util.function.Consumer;
/**
* UUID service that uses the (legacy) SQL UUID cache
*/
public class SQLiteUUIDService implements UUIDService, Consumer<List<UUIDMapping>> {
private final SQLite sqlite;
public SQLiteUUIDService(final String fileName) {
this.sqlite =
new SQLite(FileUtils.getFile(PlotSquared.platform().getDirectory(), fileName));
try {
this.sqlite.openConnection();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
try (PreparedStatement stmt = getConnection().prepareStatement(
"CREATE TABLE IF NOT EXISTS `usercache` (uuid VARCHAR(32) NOT NULL, username VARCHAR(32) NOT NULL, PRIMARY KEY (uuid))")) {
stmt.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
private Connection getConnection() {
synchronized (this.sqlite) {
return this.sqlite.getConnection();
}
}
@Override
public @NonNull List<UUIDMapping> getNames(final @NonNull List<UUID> uuids) {
final List<UUIDMapping> mappings = new ArrayList<>(uuids.size());
try (final PreparedStatement statement = getConnection()
.prepareStatement("SELECT `username` FROM `usercache` WHERE `uuid` = ?")) {
for (final UUID uuid : uuids) {
statement.setString(1, uuid.toString());
try (final ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
mappings.add(new UUIDMapping(uuid, resultSet.getString("username")));
}
}
}
} catch (final Exception e) {
e.printStackTrace();
}
return mappings;
}
@Override
public @NonNull List<UUIDMapping> getUUIDs(@NonNull List<String> usernames) {
final List<UUIDMapping> mappings = new ArrayList<>(usernames.size());
try (final PreparedStatement statement = getConnection()
.prepareStatement("SELECT `uuid` FROM `usercache` WHERE `username` = ?")) {
for (final String username : usernames) {
statement.setString(1, username);
try (final ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
mappings.add(new UUIDMapping(
UUID.fromString(resultSet.getString("uuid")),
username
));
}
}
}
} catch (final Exception e) {
e.printStackTrace();
}
return mappings;
}
@Override
public void accept(final List<UUIDMapping> uuidWrappers) {
try (final PreparedStatement statement = getConnection()
.prepareStatement("INSERT OR REPLACE INTO `usercache` (`uuid`, `username`) VALUES(?, ?)")) {
for (final UUIDMapping mapping : uuidWrappers) {
statement.setString(1, mapping.getUuid().toString());
statement.setString(2, mapping.getUsername());
statement.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Read the entire cache at once
*
* @return All read mappings
*/
public @NonNull List<UUIDMapping> getAll() {
final List<UUIDMapping> mappings = new LinkedList<>();
try (final PreparedStatement statement = getConnection().prepareStatement("SELECT * FROM `usercache`")) {
try (final ResultSet resultSet = statement.executeQuery()) {
while (resultSet.next()) {
mappings.add(new UUIDMapping(UUID.fromString(resultSet.getString("uuid")), resultSet.getString("username")));
}
}
} catch (final Exception e) {
e.printStackTrace();
}
return mappings;
}
}

View File

@ -1,112 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.uuid;
import com.google.common.util.concurrent.RateLimiter;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.uuid.UUIDMapping;
import com.plotsquared.core.uuid.UUIDService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.enginehub.squirrelid.Profile;
import org.enginehub.squirrelid.resolver.HttpRepositoryService;
import org.enginehub.squirrelid.resolver.ProfileService;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
/**
* UUID service using SquirrelID
*/
@SuppressWarnings("UnstableApiUsage")
public class SquirrelIdUUIDService implements UUIDService {
private static final Logger LOGGER = LogManager.getLogger("PlotSquared/" + SquirrelIdUUIDService.class.getSimpleName());
private final ProfileService profileService;
private final RateLimiter rateLimiter;
/**
* Create a new SquirrelID UUID service
*
* @param rateLimit Mojangs rate limit is 600 requests per 10 minutes.
* This parameter specifies how many of those requests
* we can use before our internal rate limit kicks in.
*/
public SquirrelIdUUIDService(final int rateLimit) {
this.profileService = HttpRepositoryService.forMinecraft();
// RateLimiter uses request per seconds. The constructor
// parameter rateLimit is requests per 600 seconds
this.rateLimiter = RateLimiter.create(rateLimit / 600.0D);
}
@Override
public @NonNull List<UUIDMapping> getNames(final @NonNull List<UUID> uuids) {
final List<UUIDMapping> results = new ArrayList<>(uuids.size());
this.rateLimiter.acquire(uuids.size());
try {
try {
for (final Profile profile : this.profileService.findAllByUuid(uuids)) {
results.add(new UUIDMapping(profile.getUniqueId(), profile.getName()));
}
} catch (final IllegalArgumentException illegalArgumentException) {
//
// This means that the UUID was invalid for whatever reason, we'll try to
// go through them one by one
//
if (uuids.size() >= 2) {
if (Settings.DEBUG) {
LOGGER.info("(UUID) Found invalid UUID in batch. Will try each UUID individually.");
}
for (final UUID uuid : uuids) {
final List<UUIDMapping> result = this.getNames(Collections.singletonList(uuid));
if (result.isEmpty()) {
continue;
}
results.add(result.get(0));
}
} else if (uuids.size() == 1 && Settings.DEBUG) {
LOGGER.info("(UUID) Found invalid UUID: {}", uuids.get(0));
}
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return results;
}
@Override
public @NonNull List<UUIDMapping> getUUIDs(final @NonNull List<String> usernames) {
final List<UUIDMapping> results = new ArrayList<>(usernames.size());
this.rateLimiter.acquire(usernames.size());
try {
for (final Profile profile : this.profileService.findAllByName(usernames)) {
results.add(new UUIDMapping(profile.getUniqueId(), profile.getName()));
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return results;
}
}

View File

@ -1,422 +0,0 @@
name: PlotSquared
main: com.plotsquared.bukkit.BukkitPlatform
api-version: "1.13"
version: "${version}"
load: STARTUP
description: "Easy, yet powerful Plot World generation and management."
authors: [Citymonstret, Empire92, MattBDev, dordsor21, NotMyFault, SirYwell]
website: https://www.spigotmc.org/resources/77506/
softdepend: [Vault, PlaceholderAPI, Essentials, LuckPerms, BungeePerms, MVdWPlaceholderAPI]
loadbefore: [MultiWorld, Multiverse-Core]
depend: [WorldEdit]
database: false
commands:
plots:
description: Plot command.
aliases: [p,plot,ps,plotsquared,p2,2,plotme]
permission: plots.use
permission-message: "You are lacking the permission node 'plots.use'"
permissions:
plots.use:
default: true
plots.projectile.unowned:
default: op
plots.projectile.other:
default: op
plots.toggle.titles:
default: op
plots.toggle.chat:
default: op
plots.toggle.time:
default: op
plots.merge.other:
default: op
plots.merge.keeproad.denied:
default: op
plots.trust.everyone:
default: op
plots.area.create:
default: op
plots.area.info:
default: op
plots.area.list:
default: op
plots.area.regen:
default: op
plots.area.tp:
default: op
plots.auto.mega:
default: op
plots.continue:
default: op
plots.cluster.list:
default: op
plots.cluster.create:
default: op
plots.cluster.create.other:
default: op
plots.cluster.size:
default: op
plots.cluster.delete.other:
default: op
plots.cluster.resize:
default: op
plots.cluster.resize.other:
default: op
plots.cluster.resize.shrink:
default: op
plots.cluster.resize.expand:
default: op
plots.cluster:
default: op
plots.cluster.invite:
default: op
plots.cluster.invite.other:
default: op
plots.cluster.kick:
default: op
plots.cluster.kick.other:
default: op
plots.cluster.leave:
default: op
plots.cluster.tp:
default: op
plots.cluster.tp.other:
default: op
plots.cluster.sethome:
default: op
plots.cluster.sethome.other:
default: op
plots.cluster.command.continue:
default: op
plots.deny.everyone:
default: op
plots.download.world:
default: op
plots.set.flag.other:
default: op
plots.set:
default: op
plots.set.biome:
default: op
plots.set.alias:
default: op
plots.set.home:
default: op
plots.set.main:
default: op
plots.set.floor:
default: op
plots.set.air:
default: op
plots.set.all:
default: op
plots.set.border:
default: op
plots.set.wall:
default: op
plots.set.outline:
default: op
plots.set.middle:
default: op
plots.set.flag:
default: op
plots.flag.remove:
default: op
plots.flag.list:
default: op
plots.list.forsale:
default: op
plots.list.mine:
default: op
plots.list.shared:
default: op
plots.target:
default: op
plots.list.world:
default: op
plots.list.top:
default: op
plots.list.all:
default: op
plots.list.unowned:
default: op
plots.list.player:
default: op
plots.list.done:
default: op
plots.list.expired:
default: op
plots.list.fuzzy:
default: op
plots.list.area:
default: op
plots.comment:
default: op
plots.schematic.paste:
default: op
plots.schematic.list:
default: op
plots.schematic.save:
default: op
plots.visit.shared:
default: op
plots.visit.unowned:
default: op
plots.visit.owned:
default: op
plots.visit.other:
default: op
plots.visit.denied:
default: op
plots.home:
default: op
plots.alias.remove:
default: op
plots.backup:
default: op
plots.backup.save:
default: op
plots.backup.list:
default: op
plots.backup.load:
default: op
plots.rate:
default: op
plots.template.export:
default: op
plots.template.import:
default: op
plots.template:
default: op
plots.components:
default: op
plots.admin:
default: false
children:
plots.admin.command.continue: true
plots.admin.command.delete: true
plots.admin.command.deny: true
plots.admin.command.done: true
plots.admin.command.download: true
plots.admin.command.kick: true
plots.admin.command.load: true
plots.admin.command.merge: true
plots.admin.command.setowner: true
plots.admin.command.remove: true
plots.admin.command.save: true
plots.admin.command.schematic.paste: true
plots.admin.command.schematic.save: true
plots.admin.command.unlink: true
plots.admin.alias.set: true
plots.admin.alias.remove: true
plots.admin.chat.bypass: true
plots.admin.backup.other: true
plots.admin.unsafe: true
plots.admin.debug.other: true
plots.admin.area.sudo: true
plots.admin.interact.blockedcommands: true
plots.admin.update.notify: true
plots.admin.exit.denied: true
plots.admin.entry.denied: true
plots.admin.visit.untrusted: true
plots.admin.entry.forcefield: true
plots.admin.command.chatspy: true
plots.admin.caps.other: true
plots.admin.music.other: true
plots.admin.destroy.unowned: true
plots.admin.destroy.groundlevel: true
plots.admin.destroy.other: true
plots.admin.destroy.road: true
plots.admin.build.road: true
plots.admin.build.unowned: true
plots.admin.build.other: true
plots.admin.interact.road: true
plots.admin.interact.unowned: true
plots.admin.interact.other: true
plots.admin.build.heightlimit: true
plots.admin.command.purge.ratings: true
plots.admin.command.trust: true
plots.admin.command.add: true
plots.admin.info.force: true
plots.admin.command.schematic: true
plots.admin.command.clear: true
plots.admin.flight: true
plots.admin.command.blocked-cmds.shared: true
plots.admin.command.blocked-cmds.road: true
plots.admin.components.other: true
plots.admin.vehicle.break.unowned: true
plots.admin.pve.unowned: true
plots.admin.border.bypass: true
plots.teleport.delay.bypass:
default: op
plots.admin.border.bypass:
default: op
plots.worldedit.bypass:
default: op
plots.gamemode.bypass:
default: op
plots.confirm.bypass:
default: op
plots.flag.notify-enter.bypass:
default: op
plots.flag.notify-leave.bypass:
default: op
plots.permpack.basicflags:
default: false
children:
plots.set.flag: true
plots.flag: true
plots.flag.add: true
plots.flag.remove: true
plots.flag.list: true
plots.flag.info: true
plots.set.flag.titles: true
plots.set.flag.titles.*: true
plots.set.flag.description: true
plots.set.flag.greeting: true
plots.set.flag.farewell: true
plots.set.flag.notify-enter: true
plots.set.flag.notify-enter.*: true
plots.set.flag.notify-leave: true
plots.set.flag.notify-leave.*: true
plots.set.flag.feed: true
plots.set.flag.feed.*: true
plots.set.flag.heal: true
plots.set.flag.heal.*: true
plots.set.flag.invincible: true
plots.set.flag.invincible.*: true
plots.set.flag.instabreak: true
plots.set.flag.instabreak.*: true
plots.set.flag.fly: true
plots.set.flag.fly.*: true
plots.set.flag.gamemode: true
plots.set.flag.gamemode.creative: true
plots.set.flag.gamemode.survival: true
plots.set.flag.gamemode.adventure: true
plots.set.flag.time: true
plots.set.flag.weather: true
plots.set.flag.weather.*: true
plots.set.flag.music: true
plots.set.flag.music.*: true
plots.set.flag.disable-physics: true
plots.set.flag.disable-physics.*: true
plots.set.flag.pve: true
plots.set.flag.pve.*: true
plots.set.flag.pvp: true
plots.set.flag.pvp.*: true
plots.set.flag.explosion: true
plots.set.flag.explosion.*: true
plots.set.flag.hostile-interact: true
plots.set.flag.hostile-interact.*: true
plots.set.flag.hostile-attack: true
plots.set.flag.hostile-attack.*: true
plots.set.flag.player-interact: true
plots.set.flag.player-interact.*: true
plots.set.flag.animal-interact: true
plots.set.flag.animal-interact.*: true
plots.set.flag.animal-attack: true
plots.set.flag.animal-attack.*: true
plots.set.flag.tamed-interact: true
plots.set.flag.tamed-interact.*: true
plots.set.flag.tamed-attack: true
plots.set.flag.tamed-attack.*: true
plots.set.flag.misc-interact: true
plots.set.flag.misc-interact.*: true
plots.set.flag.hanging-place: true
plots.set.flag.hanging-place.*: true
plots.set.flag.hanging-break: true
plots.set.flag.hanging-break.*: true
plots.set.flag.vehicle-use: true
plots.set.flag.vehicle-use.*: true
plots.set.flag.vehicle-place: true
plots.set.flag.vehicle-place.*: true
plots.set.flag.vehicle-break: true
plots.set.flag.vehicle-break.*: true
plots.set.flag.place: true
plots.set.flag.place.*: true
plots.set.flag.break: true
plots.set.flag.break.*: true
plots.set.flag.use: true
plots.set.flag.use.*: true
plots.set.flag.forcefield: true
plots.set.flag.forcefield.*: true
plots.set.flag.price: true
plots.set.flag.no-worldedit: true
plots.set.flag.no-worldedit.*: true
plots.set.flag.titleflag.*: true
plots.permpack.basicinbox:
default: false
children:
plots.inbox.read.public: true
plots.inbox.modify.public: true
plots.inbox.write.public: true
plots.inbox.read.report: true
plots.inbox.write.report: true
plots.inbox.read.owner: true
plots.inbox.modify.owner: true
plots.inbox.write.owner: true
plots.comment: true
plots.inbox: true
plots.permpack.basic:
default: false
children:
plots.use: true
plots.info: true
plots.claim: true
plots.auto: true
plots.home: true
plots.clear: true
plots.delete: true
plots.music: true
plots.list: true
plots.list.mine: true
plots.list.shared: true
plots.list.world: true
plots.list.all: true
plots.list.forsale: true
plots.list.unowned: true
plots.set: true
plots.visit: true
plots.visit.owned: true
plots.visit.shared: true
plots.set.flag: true
plots.flag.add: true
plots.flag.remove: true
plots.flag.list: true
plots.flag.info: true
plots.flag: true
plots.buy: true
plots.chat: true
plots.confirm: true
plots.toggle: true
plots.toggle.titles: true
plots.toggle.chat: true
plots.toggle.time: true
plots.set.biome: true
plots.set.home: true
plots.alias.set: true
plots.alias.remove: true
plots.set.description: true
plots.description: true
plots.alias: true
plots.merge: true
plots.merge.other: true
plots.merge.4: true
plots.unlink: true
plots.denied: true
plots.add: true
plots.trust: true
plots.deny: true
plots.remove: true
plots.untrust: true
plots.undeny: true
plots.kick: true
plots.download: true
plots.save: true
plots.done: true
plots.continue: true
plots.middle: true

View File

@ -1,76 +0,0 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at contact<at>intellectualsites.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq

View File

@ -1,82 +0,0 @@
import java.time.format.DateTimeFormatter
dependencies {
// Expected everywhere.
compileOnlyApi("org.checkerframework:checker-qual")
// Minecraft expectations
compileOnlyApi("com.google.code.gson:gson")
compileOnly("com.google.guava:guava")
// Platform expectations
compileOnlyApi("org.yaml:snakeyaml")
// Adventure
api("net.kyori:adventure-api")
api("net.kyori:adventure-text-minimessage")
// Guice
api(libs.guice) {
exclude(group = "com.google.guava")
}
api(libs.guiceassistedinject) {
exclude("com.google.inject", "guice")
}
api(libs.spotbugs)
// Plugins
compileOnly(libs.worldeditCore) {
exclude(group = "bukkit-classloader-check")
exclude(group = "mockito-core")
exclude(group = "dummypermscompat")
}
testImplementation(libs.worldeditCore)
compileOnly("com.fastasyncworldedit:FastAsyncWorldEdit-Core") { isTransitive = false }
testImplementation("com.fastasyncworldedit:FastAsyncWorldEdit-Core") { isTransitive = false }
// Logging
compileOnlyApi("org.apache.logging.log4j:log4j-api")
// Other libraries
api(libs.prtree)
api(libs.aopalliance)
api(libs.cloudServices)
api(libs.arkitektonika)
api("com.intellectualsites.paster:Paster")
api("com.intellectualsites.informative-annotations:informative-annotations")
}
tasks.processResources {
filesMatching("plugin.properties") {
expand(
"version" to project.version.toString(),
"commit" to rootProject.grgit.head().abbreviatedId,
"date" to rootProject.grgit.head().dateTime.format(DateTimeFormatter.ofPattern("yy.MM.dd"))
)
}
doLast {
copy {
from(File("$rootDir/LICENSE"))
into("$buildDir/resources/main/")
}
}
}
tasks {
withType<Javadoc> {
val isRelease = if (rootProject.version.toString().endsWith("-SNAPSHOT")) "TODO" else rootProject.version.toString()
val opt = options as StandardJavadocDocletOptions
opt.links("https://docs.enginehub.org/javadoc/com.sk89q.worldedit/worldedit-core/" + libs.worldeditCore.get().versionConstraint.toString())
opt.links("https://jd.adventure.kyori.net/api/4.9.3/")
opt.links("https://google.github.io/guice/api-docs/" + libs.guice.get().versionConstraint.toString() + "/javadoc/")
opt.links("https://checkerframework.org/api/")
opt.links("https://javadoc.io/doc/com.intellectualsites.informative-annotations/informative-annotations/latest/")
opt.isLinkSource = true
opt.bottom(File("$rootDir/javadocfooter.html").readText())
opt.isUse = true
opt.encoding("UTF-8")
opt.keyWords()
opt.addStringOption("-since", isRelease)
}
}

View File

@ -1,209 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.core;
import com.plotsquared.core.configuration.caption.Caption;
import com.plotsquared.core.configuration.caption.StaticCaption;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.player.ConsolePlayer;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.queue.GlobalBlockQueue;
import com.plotsquared.core.util.ChunkManager;
import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.SchematicHandler;
import com.plotsquared.core.util.query.PlotQuery;
import net.kyori.adventure.text.minimessage.Template;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.Collections;
import java.util.Set;
import java.util.UUID;
/**
* PlotSquared API.
*
* <p>Useful classes:
* <ul>
* <li>{@link PlotPlayer}</li>
* <li>{@link Plot}</li>
* <li>{@link Location}</li>
* <li>{@link PlotArea}</li>
* <li>{@link PlotSquared}</li>
* </ul>
*
* @version 6
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class PlotAPI {
public PlotAPI() {
}
/**
* Gets all plots.
*
* @return all plots
*/
public @NonNull Set<@NonNull Plot> getAllPlots() {
return PlotQuery.newQuery().allPlots().asSet();
}
/**
* Gets all plots for a player.
*
* @param player Player, whose plots to search for
* @return all plots that a player owns
*/
public @NonNull Set<@NonNull Plot> getPlayerPlots(final @NonNull PlotPlayer<?> player) {
return PlotQuery.newQuery().ownedBy(player).asSet();
}
/**
* Adds a plot world.
*
* @param plotArea Plot World Object
* @see PlotSquared#addPlotArea(PlotArea)
*/
public void addPlotArea(final @NonNull PlotArea plotArea) {
PlotSquared.get().addPlotArea(plotArea);
}
/**
* ChunkManager class contains several useful methods.
* <ul>
* <li>Chunk deletion</li>
* <li>Moving or copying regions</li>
* <li>Plot swapping</li>
* <li>Entity Tracking</li>
* <li>Region Regeneration</li>
* </ul>
*
* @return ChunkManager
* @see ChunkManager
*/
public @NonNull ChunkManager getChunkManager() {
return PlotSquared.platform().injector().getInstance(ChunkManager.class);
}
/**
* Gets the block/biome set queue
*
* @return GlobalBlockQueue.IMP
*/
public @NonNull GlobalBlockQueue getBlockQueue() {
return PlotSquared.platform().globalBlockQueue();
}
/**
* SchematicHandler class contains methods related to pasting, reading
* and writing schematics.
*
* @return SchematicHandler
* @see SchematicHandler
*/
public @NonNull SchematicHandler getSchematicHandler() {
return PlotSquared.platform().injector().getInstance(SchematicHandler.class);
}
/**
* Gets a list of PlotAreas in the world.
*
* @param world The world to check for plot areas
* @return A set of PlotAreas
*/
public @NonNull Set<@NonNull PlotArea> getPlotAreas(final @Nullable String world) {
if (world == null) {
return Collections.emptySet();
}
return PlotSquared.get().getPlotAreaManager().getPlotAreasSet(world);
}
/**
* Send a message to the console. The message supports color codes.
*
* @param message the message
* @param replacements Variable replacements
*/
public void sendConsoleMessage(
final @NonNull String message,
final @NonNull Template @NonNull ... replacements
) {
ConsolePlayer.getConsole().sendMessage(StaticCaption.of(message), replacements);
}
/**
* Sends a message to the console.
*
* @param caption the message
* @param replacements Variable replacements
*/
public void sendConsoleMessage(
final @NonNull Caption caption,
final @NonNull Template @NonNull ... replacements
) {
ConsolePlayer.getConsole().sendMessage(caption, replacements);
}
/**
* Gets the PlotSquared class.
*
* @return PlotSquared Class
* @see PlotSquared
*/
public @NonNull PlotSquared getPlotSquared() {
return PlotSquared.get();
}
/**
* Gets the PlotPlayer for a UUID.
*
* <p><i>Please note that PlotSquared can be configured to provide
* different UUIDs than Bukkit</i>
*
* @param uuid the uuid of the player to wrap
* @return a {@link PlotPlayer}
*/
public @Nullable PlotPlayer<?> wrapPlayer(final @NonNull UUID uuid) {
return PlotSquared.platform().playerManager().getPlayerIfExists(uuid);
}
/**
* Gets the PlotPlayer for a username.
*
* @param player the player to wrap
* @return a {@link PlotPlayer}
*/
public @Nullable PlotPlayer<?> wrapPlayer(final @NonNull String player) {
return PlotSquared.platform().playerManager().getPlayerIfExists(player);
}
/**
* Registers a listener for PlotSquared Events
*
* @param listener the listener class to register
* @see EventDispatcher#registerListener(Object)
*/
public void registerListener(final @NonNull Object listener) {
PlotSquared.get().getEventDispatcher().registerListener(listener);
}
}

View File

@ -1,379 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.core;
import cloud.commandframework.services.ServicePipeline;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import com.intellectualsites.annotations.DoNotUse;
import com.plotsquared.core.backup.BackupManager;
import com.plotsquared.core.configuration.caption.LocaleHolder;
import com.plotsquared.core.generator.GeneratorWrapper;
import com.plotsquared.core.generator.HybridUtils;
import com.plotsquared.core.generator.IndependentPlotGenerator;
import com.plotsquared.core.inject.annotations.DefaultGenerator;
import com.plotsquared.core.location.World;
import com.plotsquared.core.permissions.PermissionHandler;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.expiration.ExpireManager;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.queue.GlobalBlockQueue;
import com.plotsquared.core.util.ChunkManager;
import com.plotsquared.core.util.EconHandler;
import com.plotsquared.core.util.PlatformWorldManager;
import com.plotsquared.core.util.PlayerManager;
import com.plotsquared.core.util.RegionManager;
import com.plotsquared.core.util.SetupUtils;
import com.plotsquared.core.util.WorldUtil;
import com.plotsquared.core.util.placeholders.PlaceholderRegistry;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.io.File;
/**
* PlotSquared main utility class
*
* @param <P> Player type
*/
public interface PlotPlatform<P> extends LocaleHolder {
/**
* Gets the directory which contains PlotSquared files. The directory may not exist.
*
* @return the PlotSquared directory
*/
@NonNull File getDirectory();
/**
* Gets the folder where all world data is stored.
*
* @return the world folder
*/
@NonNull File worldContainer();
/**
* Completely shuts down the plugin.
*/
void shutdown();
/**
* Completely shuts down the server.
*/
void shutdownServer();
/**
* Get the name of the plugin
*
* @return Plugin name
*/
default @NonNull String pluginName() {
return "PlotSquared";
}
/**
* Gets the version of Minecraft that is running
*
* @return server version as array of numbers
*/
int[] serverVersion();
/**
* Gets the default minimum world height for the version of Minecraft that the server is running.
*
* @return minimum world height
* @since 6.6.0
*/
int versionMinHeight();
/**
* Gets the default maximum world height for the version of Minecraft that the server is running.
*
* @return maximum world height (inclusive)
* @since 6.6.0
*/
int versionMaxHeight();
/**
* Gets the server implementation name and version
*
* @return server implementation and version as string
*/
@NonNull String serverImplementation();
/**
* Gets the native server code package prefix.
*
* @return The package prefix
*/
@NonNull String serverNativePackage();
/**
* Start Metrics.
*/
void startMetrics();
/**
* If a world is already loaded, set the generator (use NMS if required).
*
* @param world The world to set the generator
*/
void setGenerator(@NonNull String world);
/**
* Unregisters a {@link PlotPlayer} from cache e.g. if they have logged off.
*
* @param player the player to remove
*/
void unregister(@NonNull PlotPlayer<?> player);
/**
* Gets the generator wrapper for a world (world) and generator (name).
*
* @param world The world to get the generator from
* @param name The name of the generator
* @return The generator being used for the provided world
*/
@Nullable GeneratorWrapper<?> getGenerator(
@NonNull String world,
@Nullable String name
);
/**
* Create a platform generator from a plot generator
*
* @param world World name
* @param generator Plot generator
* @return Platform generator wrapper
*/
@NonNull GeneratorWrapper<?> wrapPlotGenerator(
@NonNull String world,
@NonNull IndependentPlotGenerator generator
);
/**
* Usually HybridGen
*
* @return Default implementation generator
*/
default @NonNull IndependentPlotGenerator defaultGenerator() {
return injector().getInstance(Key.get(IndependentPlotGenerator.class, DefaultGenerator.class));
}
/**
* Get the backup manager instance
*
* @return Backup manager
*/
default @NonNull BackupManager backupManager() {
return injector().getInstance(BackupManager.class);
}
/**
* Get the platform specific world manager
*
* @return World manager
*/
default @NonNull PlatformWorldManager<?> worldManager() {
return injector().getInstance(PlatformWorldManager.class);
}
/**
* Get the player manager implementation for the platform
*
* @return Player manager
*/
default @NonNull PlayerManager<? extends PlotPlayer<P>, ? extends P> playerManager() {
return injector().getInstance(Key.get(new TypeLiteral<PlayerManager<? extends PlotPlayer<P>, ? extends P>>() {
}));
}
/**
* Get a platform world wrapper from a world name
*
* @param worldName World name
* @return Platform world wrapper
*/
@Nullable World<?> getPlatformWorld(@NonNull String worldName);
/**
* Get the {@link com.google.inject.Injector} instance used by PlotSquared
*
* @return Injector instance
*/
@NonNull Injector injector();
/**
* Get the world utility implementation
*
* @return World utility
*/
default @NonNull WorldUtil worldUtil() {
return injector().getInstance(WorldUtil.class);
}
/**
* Get the global block queue implementation
*
* @return Global block queue implementation
*/
default @NonNull GlobalBlockQueue globalBlockQueue() {
return injector().getInstance(GlobalBlockQueue.class);
}
/**
* Get the {@link HybridUtils} implementation for the platform
*
* @return Hybrid utils
*/
default @NonNull HybridUtils hybridUtils() {
return injector().getInstance(HybridUtils.class);
}
/**
* Get the {@link SetupUtils} implementation for the platform
*
* @return Setup utils
*/
default @NonNull SetupUtils setupUtils() {
return injector().getInstance(SetupUtils.class);
}
/**
* Get the {@link EconHandler} implementation for the platform
*
* @return Econ handler
*/
default @NonNull EconHandler econHandler() {
return injector().getInstance(EconHandler.class);
}
/**
* Get the {@link RegionManager} implementation for the platform
*
* @return Region manager
*/
default @NonNull RegionManager regionManager() {
return injector().getInstance(RegionManager.class);
}
/**
* Get the {@link ChunkManager} implementation for the platform
*
* @return Region manager
*/
default @NonNull ChunkManager chunkManager() {
return injector().getInstance(ChunkManager.class);
}
/**
* Get the {@link ExpireManager} implementation for the platform
*
* @return Expire manager
* @since 6.10.2
*/
default @NonNull ExpireManager expireManager() {
return injector().getInstance(ExpireManager.class);
}
/**
* Get the {@link PlotAreaManager} implementation.
*
* @return the PlotAreaManager
* @since 6.1.4
*/
@NonNull PlotAreaManager plotAreaManager();
/**
* Get the platform specific console {@link Audience}
*
* @return Console audience
*/
@NonNull Audience consoleAudience();
/**
* Get a formatted string containing all plugins on the server together
* with plugin metadata. Mainly for use in debug pastes
*
* @return Formatted string
*/
@NonNull String pluginsFormatted();
/**
* Get the kind of WorldEdit implementation
*
* @return worldedit implementations
* @since 6.3.0
*/
@DoNotUse
@NonNull String worldEditImplementations();
/**
* Load the caption maps
*/
void copyCaptionMaps();
/**
* Get the {@link PermissionHandler} implementation for the platform
*
* @return Permission handler
*/
default @NonNull PermissionHandler permissionHandler() {
return injector().getInstance(PermissionHandler.class);
}
/**
* Get the {@link ServicePipeline} implementation
*
* @return Service pipeline
*/
default @NonNull ServicePipeline servicePipeline() {
return injector().getInstance(ServicePipeline.class);
}
/**
* Get the {@link PlaceholderRegistry} implementation
*
* @return Placeholder registry
*/
default @NonNull PlaceholderRegistry placeholderRegistry() {
return injector().getInstance(PlaceholderRegistry.class);
}
/**
* Convert a component to a legacy string
*
* @param component Component to convert
* @return Converted string
*/
@NonNull String toLegacyPlatformString(@NonNull Component component);
/**
* Returns if the FastAsyncWorldEdit-PlotSquared hook is active/enabled
*
* @return status of FastAsyncWorldEdit-PlotSquared hook
*/
default boolean isFaweHooking() {
return false;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,153 +0,0 @@
/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.core;
import org.checkerframework.checker.nullness.qual.NonNull;
public final class PlotVersion {
public final int year, month, day, hash;
public final String versionString;
public final int[] version;
public final String suffix;
public PlotVersion(
final int year,
final int month,
final int day,
final int hash,
final String rawVersion
) {
String versionString = rawVersion;
this.year = year;
this.month = month;
this.day = day;
this.hash = hash;
int dash = versionString.indexOf('-');
if (dash != -1) {
suffix = versionString.substring(dash);
versionString = versionString.substring(0, dash);
} else {
suffix = "";
}
this.versionString = versionString.substring(versionString.indexOf('=') + 1);
version = new int[3];
String[] verArray = versionString.substring(versionString.indexOf('=') + 1).split("\\.");
version[0] = verArray.length > 0 ? Integer.parseInt(verArray[0]) : 0;
version[1] = verArray.length > 1 ? Integer.parseInt(verArray[1]) : 0;
version[2] = verArray.length > 2 ? Integer.parseInt(verArray[2]) : 0;
}
public PlotVersion(
final String rawVersion,
final String commit,
final String date
) {
String versionString = rawVersion;
int dash = versionString.indexOf('-');
if (dash != -1) {
suffix = versionString.substring(dash);
versionString = versionString.substring(0, dash);
} else {
suffix = "";
}
this.versionString = versionString.substring(versionString.indexOf('=') + 1);
version = new int[3];
String[] verArray = this.versionString.split("\\.");
version[0] = verArray.length > 0 ? Integer.parseInt(verArray[0]) : 0;
version[1] = verArray.length > 1 ? Integer.parseInt(verArray[1]) : 0;
version[2] = verArray.length > 2 ? Integer.parseInt(verArray[2]) : 0;
this.hash = Integer.parseInt(commit.substring(commit.indexOf('=') + 1), 16);
String[] split1 = date.substring(date.indexOf('=') + 1).split("\\.");
this.year = Integer.parseInt(split1[0]);
this.month = Integer.parseInt(split1[1]);
this.day = Integer.parseInt(split1[2]);
}
public static @NonNull PlotVersion tryParse(
final @NonNull String versionString,
final @NonNull String commit,
final @NonNull String date
) {
try {
return new PlotVersion(versionString, commit, date);
} catch (Exception e) {
e.printStackTrace();
return new PlotVersion(0, 0, 0, 0, "0");
}
}
public @NonNull String versionString() {
if (hash == 0 && versionString == null) {
return "NoVer-SNAPSHOT";
} else {
return versionString + suffix;
}
}
@Override
public String toString() {
if (hash == 0 && versionString == null) {
return "PlotSquared-NoVer-SNAPSHOT";
} else {
return "PlotSquared-" + versionString + suffix;
}
}
/**
* Compare a given version string with the one cached here.
*
* @param versionString the version to compare
* @return {@code true} if the given version is a "later" version
*/
public boolean isLaterVersion(final @NonNull String versionString) {
int dash = versionString.indexOf('-');
String[] verArray =
versionString.substring(0, dash == -1 ? versionString.length() : dash).split("\\.");
int one = Integer.parseInt(verArray[0]);
int two = Integer.parseInt(verArray[1]);
int three = Integer.parseInt(verArray[2]);
if (one > version[0]) {
return true;
} else if (one == version[0] && two > version[1]) {
return true;
} else {
return one == version[0] && two == version[1] && three > version[2];
}
}
/**
* Compare a given version with the one cached here.
*
* @param verArray the version to compare
* @return {@code true} if the given version is a "later" version
*/
public boolean isLaterVersion(int[] verArray) {
if (verArray[0] > version[0]) {
return true;
} else if (verArray[0] == version[0] && verArray[1] > version[1]) {
return true;
} else {
return verArray[0] == version[0] && verArray[1] == version[1]
&& verArray[2] > version[2];
}
}
}

Some files were not shown because too many files have changed in this diff Show More