var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => {
  __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  return value;
};

// data/system_template_esbuild/subscripts/feather_armor.ts
import {
  EntityComponentTypes,
  EquipmentSlot,
  system,
  TicksPerSecond,
  world
} from "@minecraft/server";
var ITEM_ID = "shapescape_ext:feather_";
var TAG = "shapescape_ext_feather_armor";
var INTERVAL = 0.5 * TicksPerSecond;
world.beforeEvents.itemUse.subscribe((event) => {
  const player = event.source;
  const item = event.itemStack;
  if (item.typeId === ITEM_ID) {
    checkPlayerEquipment(player);
  }
});
function checkPlayerEquipment(player) {
  const equipment = player.getComponent(
    EntityComponentTypes.Equippable
  );
  if (!equipment)
    return;
  const headSlot = equipment.getEquipmentSlot(EquipmentSlot.Head);
  const chestplateSlot = equipment.getEquipmentSlot(EquipmentSlot.Chest);
  const legsSlot = equipment.getEquipmentSlot(EquipmentSlot.Legs);
  const feetSlot = equipment.getEquipmentSlot(EquipmentSlot.Feet);
  if (!chestplateSlot || !headSlot || !legsSlot || !feetSlot)
    return;
  const headItem = headSlot.getItem();
  const chestplateItem = chestplateSlot.getItem();
  const legsItem = legsSlot.getItem();
  const feetItem = feetSlot.getItem();
  const isWearingFullSet = headItem?.typeId === ITEM_ID + "helmet" && chestplateItem?.typeId === ITEM_ID + "chestplate" && legsItem?.typeId === ITEM_ID + "leggings" && feetItem?.typeId === ITEM_ID + "boots";
  const hasTag = player.hasTag(TAG);
  if (isWearingFullSet && !hasTag) {
    applyFireResistance(player);
  } else if (!isWearingFullSet && hasTag) {
    removeFireResistance(player);
  }
}
function applyFireResistance(player) {
  player.addTag(TAG);
  player.addEffect("minecraft:fire_resistance", 999999 * TicksPerSecond, {
    amplifier: 255,
    showParticles: false
  });
}
function removeFireResistance(player) {
  player.removeTag(TAG);
  player.removeEffect("minecraft:fire_resistance");
}
system.runInterval(() => {
  for (const player of world.getAllPlayers()) {
    checkPlayerEquipment(player);
  }
}, INTERVAL);

// data/system_template_esbuild/subscripts/default_init.ts
import { world as world2 } from "@minecraft/server";
function defaultInit() {
  let scoreboard = world2.scoreboard.getObjective("shapescape_ext_tmp");
  if (scoreboard == void 0) {
    world2.getDimension("overworld").runCommandAsync("function shapescape/ext/init");
  }
}
defaultInit();

// data/system_template_esbuild/subscripts/ankylosaurus_smash_attack.ts
import {
  system as system8,
  world as world7,
  GameMode,
  EntityDamageCause
} from "@minecraft/server";

// data/node_modules/@bedrock-oss/bedrock-boost/dist/index.mjs
import { Direction } from "@minecraft/server";
import { system as system2, world as world3 } from "@minecraft/server";
import { system as system22 } from "@minecraft/server";
import { BlockPermutation, world as world22 } from "@minecraft/server";
import { world as world32 } from "@minecraft/server";
import { Player as Player2 } from "@minecraft/server";
import { system as system3 } from "@minecraft/server";
import { system as system4 } from "@minecraft/server";
import {
  system as system5,
  world as world4
} from "@minecraft/server";
import { Player as Player22, system as system6, world as world5 } from "@minecraft/server";
import {
  InputPermissionCategory
} from "@minecraft/server";
import { system as system7 } from "@minecraft/server";
import { Direction as Direction2 } from "@minecraft/server";
import { StructureSaveMode, world as world6 } from "@minecraft/server";
import { EntityEquippableComponent as EntityEquippableComponent2, EquipmentSlot as EquipmentSlot2, ItemDurabilityComponent, ItemEnchantableComponent } from "@minecraft/server";
var _a;
var ChatColor = (_a = class {
  /**
   * Class ChatColor Constructor.
   * @param code - The color code as a string.
   * @param color - The color code as a hexadecimal number. Can be undefined.
   */
  constructor(code, color) {
    __publicField(this, "r");
    __publicField(this, "g");
    __publicField(this, "b");
    this.code = code;
    this.color = color;
    if (color) {
      this.r = color >> 16 & 255;
      this.g = color >> 8 & 255;
      this.b = color & 255;
    }
  }
  /**
   * Returns the string representation of the ChatColor instance,
   * which includes the PREFIX followed by the color code.
   * @returns A string representing the ChatColor instance
   */
  toString() {
    return _a.PREFIX + this.code;
  }
  /**
   * Returns the color code of the ChatColor instance.
   * @returns The color code of this ChatColor instance.
   */
  toRGB() {
    return this.color;
  }
  /**
   * Returns the hexadecimal string representation of the color code
   * @returns {string | undefined} The hexadecimal representation of the color.
   */
  toHex() {
    return this.color?.toString(16);
  }
  /**
   * Retrieve the value of the red component.
   *
   * @returns {number | undefined} The value of the red component, or undefined if it is not set.
   */
  getRed() {
    return this.r;
  }
  /**
   * Retrieves the green value of the current color.
   *
   * @returns {number | undefined} The green value of the color, or undefined if it is not set.
   */
  getGreen() {
    return this.g;
  }
  /**
   * Retrieves the blue value of a color.
   *
   * @returns The blue value of the color.
   * @type {number | undefined}
   */
  getBlue() {
    return this.b;
  }
  /**
   * Retrieves the format code associated with the chat color.
   *
   * @returns {string} The format code of the chat color.
   */
  getCode() {
    return this.code;
  }
  /**
   * Removes color codes from the specified string
   * @param str - The string from which color codes will be removed.
   * @returns The string cleared from color codes.
   */
  static stripColor(str) {
    return str.replace(/§[0-9a-u]/g, "");
  }
  /**
   * Finds the closest ChatColor code for the given RGB values
   * @param r - Red part of the color.
   * @param g - Green part of the color.
   * @param b - Blue part of the color.
   * @returns The closest ChatColor for the given RGB values.
   */
  static findClosestColor(r, g, b) {
    let minDistance = Number.MAX_VALUE;
    let closestColor = _a.WHITE;
    for (const color of _a.ALL_COLORS) {
      if (color.r && color.g && color.b) {
        const distance = Math.sqrt(Math.pow(color.r - r, 2) + Math.pow(color.g - g, 2) + Math.pow(color.b - b, 2));
        if (distance < minDistance) {
          minDistance = distance;
          closestColor = color;
        }
      }
    }
    return closestColor;
  }
}, /**
 * Black color code. (0)
 */
__publicField(_a, "BLACK", new _a("0", 0)), /**
 * Dark blue color code. (1)
 */
__publicField(_a, "DARK_BLUE", new _a("1", 170)), /**
 * Dark green color code. (2)
 */
__publicField(_a, "DARK_GREEN", new _a("2", 43520)), /**
 * Dark aqua color code. (3)
 */
__publicField(_a, "DARK_AQUA", new _a("3", 43690)), /**
 * Dark red color code. (4)
 */
__publicField(_a, "DARK_RED", new _a("4", 11141120)), /**
 * Dark purple color code. (5)
 */
__publicField(_a, "DARK_PURPLE", new _a("5", 11141290)), /**
 * Gold color code. (6)
 */
__publicField(_a, "GOLD", new _a("6", 16755200)), /**
 * Gray color code. (7)
 */
__publicField(_a, "GRAY", new _a("7", 11184810)), /**
 * Dark gray color code. (8)
 */
__publicField(_a, "DARK_GRAY", new _a("8", 5592405)), /**
 * Blue color code. (9)
 */
__publicField(_a, "BLUE", new _a("9", 5592575)), /**
 * Green color code. (a)
 */
__publicField(_a, "GREEN", new _a("a", 5635925)), /**
 * Aqua color code. (b)
 */
__publicField(_a, "AQUA", new _a("b", 5636095)), /**
 * Red color code. (c)
 */
__publicField(_a, "RED", new _a("c", 16733525)), /**
 * Light purple color code. (d)
 */
__publicField(_a, "LIGHT_PURPLE", new _a("d", 16733695)), /**
 * Yellow color code. (e)
 */
__publicField(_a, "YELLOW", new _a("e", 16777045)), /**
 * White color code. (f)
 */
__publicField(_a, "WHITE", new _a("f", 16777215)), /**
 * MineCoin gold color code. (g)
 */
__publicField(_a, "MINECOIN_GOLD", new _a("g", 14603781)), /**
 * Material quartz color code. (h)
 */
__publicField(_a, "MATERIAL_QUARTZ", new _a("h", 14931153)), /**
 * Material iron color code. (i)
 */
__publicField(_a, "MATERIAL_IRON", new _a("i", 13552330)), /**
 * Material netherite color code. (j)
 */
__publicField(_a, "MATERIAL_NETHERITE", new _a("j", 4471355)), /**
 * Material redstone color code. (m)
 */
__publicField(_a, "MATERIAL_REDSTONE", new _a("m", 9901575)), /**
 * Material copper color code. (n)
 */
__publicField(_a, "MATERIAL_COPPER", new _a("n", 11823181)), /**
 * Material gold color code. (p)
 */
__publicField(_a, "MATERIAL_GOLD", new _a("p", 14594349)), /**
 * Material emerald color code. (q)
 */
__publicField(_a, "MATERIAL_EMERALD", new _a("q", 1155126)), /**
 * Material diamond color code. (s)
 */
__publicField(_a, "MATERIAL_DIAMOND", new _a("s", 2931368)), /**
 * Material lapis color code. (t)
 */
__publicField(_a, "MATERIAL_LAPIS", new _a("t", 2181499)), /**
 * Material amethyst color code. (u)
 */
__publicField(_a, "MATERIAL_AMETHYST", new _a("u", 10116294)), /**
 * Obfuscated color code. (k)
 */
__publicField(_a, "OBFUSCATED", new _a("k")), /**
 * Bold color code. (l)
 */
__publicField(_a, "BOLD", new _a("l")), /**
 * Italic color code. (o)
 */
__publicField(_a, "ITALIC", new _a("o")), /**
 * Reset color code. (r)
 */
__publicField(_a, "RESET", new _a("r")), /**
 * All available color codes.
 */
__publicField(_a, "VALUES", [
  _a.BLACK,
  _a.DARK_BLUE,
  _a.DARK_GREEN,
  _a.DARK_AQUA,
  _a.DARK_RED,
  _a.DARK_PURPLE,
  _a.GOLD,
  _a.GRAY,
  _a.DARK_GRAY,
  _a.BLUE,
  _a.GREEN,
  _a.AQUA,
  _a.RED,
  _a.LIGHT_PURPLE,
  _a.YELLOW,
  _a.WHITE,
  _a.MINECOIN_GOLD,
  _a.MATERIAL_QUARTZ,
  _a.MATERIAL_IRON,
  _a.MATERIAL_NETHERITE,
  _a.MATERIAL_REDSTONE,
  _a.MATERIAL_COPPER,
  _a.MATERIAL_GOLD,
  _a.MATERIAL_EMERALD,
  _a.MATERIAL_DIAMOND,
  _a.MATERIAL_LAPIS,
  _a.MATERIAL_AMETHYST,
  _a.OBFUSCATED,
  _a.BOLD,
  _a.ITALIC,
  _a.RESET
]), /**
 * All available color codes excluding the formatting codes.
 */
__publicField(_a, "ALL_COLORS", [
  _a.BLACK,
  _a.DARK_BLUE,
  _a.DARK_GREEN,
  _a.DARK_AQUA,
  _a.DARK_RED,
  _a.DARK_PURPLE,
  _a.GOLD,
  _a.GRAY,
  _a.DARK_GRAY,
  _a.BLUE,
  _a.GREEN,
  _a.AQUA,
  _a.RED,
  _a.LIGHT_PURPLE,
  _a.YELLOW,
  _a.WHITE,
  _a.MINECOIN_GOLD,
  _a.MATERIAL_QUARTZ,
  _a.MATERIAL_IRON,
  _a.MATERIAL_NETHERITE,
  _a.MATERIAL_REDSTONE,
  _a.MATERIAL_COPPER,
  _a.MATERIAL_GOLD,
  _a.MATERIAL_EMERALD,
  _a.MATERIAL_DIAMOND,
  _a.MATERIAL_LAPIS,
  _a.MATERIAL_AMETHYST
]), /**
 * PREFIX is the section sign (§) used in Minecraft color codes.
 */
__publicField(_a, "PREFIX", "\xA7"), _a);
var _a2;
var ColorJSON = (_a2 = class {
  constructor() {
    // Tokens
    __publicField(this, "OpenObject", "{");
    __publicField(this, "CloseObject", "}");
    __publicField(this, "OpenArray", "[");
    __publicField(this, "CloseArray", "]");
    __publicField(this, "Comma", ",");
    __publicField(this, "KeyValueSeparator", ":");
    __publicField(this, "StringDelimiter", '"');
    __publicField(this, "KeyDelimiter", "");
    __publicField(this, "Indent", "  ");
    __publicField(this, "NewLine", "\n");
    __publicField(this, "Space", " ");
    // Threshold for inline representation
    __publicField(this, "InlineThreshold", 60);
    // Maximum depth to which objects will be traversed
    __publicField(this, "MaxDepth", 1);
    // Whether to include class names
    __publicField(this, "IncludeClassNames", true);
    // Values
    __publicField(this, "FunctionValue", "\u0192");
    __publicField(this, "NullValue", "null");
    __publicField(this, "UndefinedValue", "undefined");
    __publicField(this, "TrueValue", "true");
    __publicField(this, "FalseValue", "false");
    __publicField(this, "CycleValue", "[...cycle...]");
    __publicField(this, "TruncatedObjectValue", "{...}");
    // Colors
    __publicField(this, "OpenCloseObjectColor", ChatColor.YELLOW);
    __publicField(this, "OpenCloseArrayColor", ChatColor.AQUA);
    __publicField(this, "NumberColor", ChatColor.DARK_AQUA);
    __publicField(this, "StringColor", ChatColor.DARK_GREEN);
    __publicField(this, "BooleanColor", ChatColor.GOLD);
    __publicField(this, "NullColor", ChatColor.GOLD);
    __publicField(this, "KeyColor", ChatColor.GRAY);
    __publicField(this, "EscapeColor", ChatColor.GOLD);
    __publicField(this, "FunctionColor", ChatColor.GRAY);
    __publicField(this, "ClassColor", ChatColor.GRAY);
    __publicField(this, "ClassStyle", ChatColor.BOLD);
    __publicField(this, "CycleColor", ChatColor.DARK_RED);
  }
  /**
   * Transforms a value into a chat-friendly, colored JSON representation.
   * @param value - The value to transform.
   */
  stringify(value) {
    return this.stringifyValue(value);
  }
  /**
   * Transforms a string into a JSON representation.
   * @param value - The string to transform.
   */
  stringifyString(value) {
    return this.StringColor + this.StringDelimiter + this.escapeString(value) + this.StringDelimiter + ChatColor.RESET;
  }
  /**
   * Transforms a number into a JSON representation.
   * @param value - The number to transform.
   */
  stringifyNumber(value) {
    return this.NumberColor + value.toString() + ChatColor.RESET;
  }
  /**
   * Transforms a boolean into a JSON representation.
   * @param value - The boolean to transform.
   */
  stringifyBoolean(value) {
    return this.BooleanColor + (value ? this.TrueValue : this.FalseValue) + ChatColor.RESET;
  }
  /**
   * Transforms a function into a JSON representation.
   * @param value - The function to transform.
   */
  // eslint-disable-next-line @typescript-eslint/ban-types
  stringifyFunction(value) {
    return this.FunctionColor + this.FunctionValue + ChatColor.RESET;
  }
  /**
   * Returns a null JSON representation.
   */
  stringifyNull() {
    return this.NullColor + this.NullValue + ChatColor.RESET;
  }
  /**
   * Returns an undefined JSON representation.
   */
  stringifyUndefined() {
    return this.NullColor + this.UndefinedValue + ChatColor.RESET;
  }
  /**
   * Returns a cycle JSON representation.
   */
  stringifyCycle() {
    return this.CycleColor + this.CycleValue + ChatColor.RESET;
  }
  /**
   * Transforms an array into a JSON representation.
   * @param value - The array to transform.
   * @param indentLevel - The indentation level for pretty-printing.
   */
  stringifyArray(value, indentLevel = 0) {
    const indentSpace = this.Indent.repeat(indentLevel);
    if (value.length === 0) {
      return this.OpenCloseArrayColor + this.OpenArray + this.CloseArray + ChatColor.RESET;
    }
    let result = this.OpenCloseArrayColor + this.OpenArray + ChatColor.RESET + this.NewLine;
    let compactResult = this.OpenCloseArrayColor + this.OpenArray + ChatColor.RESET;
    value.forEach((item, index) => {
      result += indentSpace + this.Indent + this.stringifyValue(item, indentLevel + 1);
      result += index < value.length - 1 ? this.Comma + this.NewLine : this.NewLine;
      compactResult += this.stringifyValue(item, indentLevel + 1);
      compactResult += index < value.length - 1 ? this.Comma + this.Space : "";
    });
    result += indentSpace + this.OpenCloseArrayColor + this.CloseArray + ChatColor.RESET;
    compactResult += this.OpenCloseArrayColor + this.CloseArray + ChatColor.RESET;
    if (compactResult.length < this.InlineThreshold) {
      return compactResult;
    }
    return result;
  }
  /**
   * Transforms an object into a truncated JSON representation.
   * @param value - The object to transform.
   * @param className - Class Name of the object.
   * @param indentLevel - The indentation level for pretty-printing.
   */
  stringifyTruncatedObject(value, className, indentLevel = 0) {
    return (this.IncludeClassNames ? this.ClassColor + "" + this.ClassStyle + className + ChatColor.RESET + this.Space : "") + this.TruncatedObjectValue;
  }
  /**
   * Transforms an object into a JSON representation.
   * @param value - The object to transform.
   * @param className - Class Name of the object.
   * @param entries - Entries of the object to transform.
   * @param indentLevel - The indentation level for pretty-printing.
   */
  stringifyObject(value, className, entries, indentLevel = 0) {
    const indentSpace = this.Indent.repeat(indentLevel);
    const prefix = this.IncludeClassNames && className !== "Object" ? this.ClassColor + "" + this.ClassStyle + className + ChatColor.RESET + this.Space : "";
    if (entries.length === 0) {
      return prefix + this.OpenCloseObjectColor + this.OpenObject + this.CloseObject + ChatColor.RESET;
    }
    let result = prefix + this.OpenCloseObjectColor + this.OpenObject + ChatColor.RESET + this.NewLine;
    let compactResult = prefix + this.OpenCloseObjectColor + this.OpenObject + ChatColor.RESET;
    entries.forEach(([key, val], index) => {
      const compactVal = this.stringifyValue(val, indentLevel + 1);
      result += indentSpace + this.Indent + this.KeyColor + this.KeyDelimiter + key + this.KeyDelimiter + ChatColor.RESET + this.KeyValueSeparator + this.Space + compactVal;
      result += index < entries.length - 1 ? this.Comma + this.NewLine : this.NewLine;
      compactResult += this.KeyColor + key + ChatColor.RESET + this.KeyValueSeparator + this.Space + compactVal;
      compactResult += index < entries.length - 1 ? this.Comma + this.Space : "";
    });
    result += indentSpace + this.OpenCloseObjectColor + this.CloseObject + ChatColor.RESET;
    compactResult += this.OpenCloseObjectColor + this.CloseObject + ChatColor.RESET;
    if (compactResult.length < this.InlineThreshold) {
      return compactResult;
    }
    return result;
  }
  shouldTruncateObject(value, className, indentLevel = 0) {
    return !(className === "Object" || indentLevel <= this.MaxDepth || this.MaxDepth <= 0);
  }
  /**
   * Transforms a value of any type into a JSON representation. This function is not meant to be overridden.
   * @param value - The value to transform.
   * @param indentLevel - The indentation level for pretty-printing.
   */
  stringifyValue(value, indentLevel = 0) {
    if (value === null)
      return this.stringifyNull();
    if (value === void 0)
      return this.stringifyUndefined();
    if (typeof value === "number")
      return this.stringifyNumber(value);
    if (typeof value === "string")
      return this.stringifyString(value);
    if (typeof value === "boolean")
      return this.stringifyBoolean(value);
    if (typeof value === "function")
      return this.stringifyFunction(value);
    if (this.isCycle(value)) {
      return this.stringifyCycle();
    }
    this.markCycle(value);
    if (Array.isArray(value)) {
      const result = this.stringifyArray(value, indentLevel ? indentLevel + 1 : 0);
      this.clearCycle(value);
      return result;
    }
    if (typeof value === "object") {
      const name = value.constructor.name;
      if (!this.shouldTruncateObject(value, name, indentLevel)) {
        const keySet = /* @__PURE__ */ new Set();
        let prototype = Object.getPrototypeOf(value);
        let keys = Object.keys(prototype);
        while (keys.length > 0) {
          keys.forEach((key) => keySet.add(key));
          prototype = Object.getPrototypeOf(prototype);
          keys = Object.keys(prototype);
        }
        Object.keys(value).forEach((key) => keySet.add(key));
        keySet.delete("__cycleDetection__");
        const allKeys = [...keySet].sort();
        const entries = allKeys.map((key) => {
          try {
            return [key, value[key] ?? void 0];
          } catch (e) {
            return [key, void 0];
          }
        }).filter(([, val]) => typeof val !== "function" && val !== void 0);
        const result = this.stringifyObject(value, name, entries, indentLevel);
        this.clearCycle(value);
        return result;
      } else {
        const result = this.stringifyTruncatedObject(value, name, indentLevel);
        this.clearCycle(value);
        return result;
      }
    }
    this.clearCycle(value);
    return ChatColor.RESET + value.toString();
  }
  /**
   * Escapes a string for JSON.
   * @param str - The string to escape.
   */
  escapeString(str) {
    return str.replace(/\\/g, this.EscapeColor + "\\\\" + this.StringColor).replace(/"/g, this.EscapeColor + '\\"' + this.StringColor).replace(/\n/g, this.EscapeColor + "\\n" + this.StringColor).replace(/\r/g, this.EscapeColor + "\\r" + this.StringColor).replace(/\t/g, this.EscapeColor + "\\t" + this.StringColor);
  }
  markCycle(value) {
    value.__cycleDetection__ = true;
  }
  isCycle(value) {
    return !!value.__cycleDetection__;
  }
  clearCycle(value) {
    delete value.__cycleDetection__;
  }
}, __publicField(_a2, "DEFAULT", new _a2()), _a2);
var sourceMapping = void 0;
try {
  sourceMapping = globalSourceMapping;
} catch (e) {
}
var _a3;
var LogLevel = (_a3 = class {
  /**
   * The constructor for each log level.
   *
   * @param {number} level - The numerical level for this logger.
   * @param {string} name - The string name for this logger.
   * @param {ChatColor} color - The color to use for this logger. Defaults to `ChatColor.RESET`.
   */
  constructor(level, name, color = ChatColor.RESET) {
    this.level = level;
    this.name = name;
    this.color = color;
  }
  /**
   * Return the logging level as a string.
   *
   * @returns {string} The string representation of the logging level.
   */
  toString() {
    return this.color + this.name.toUpperCase() + ChatColor.RESET;
  }
  /**
   * Parse a string to get the corresponding `LogLevel`.
   *
   * @param {string} str - The string to parse.
   * @returns {LogLevel} The corresponding `LogLevel`, or `undefined` if none was found.
   */
  static parse(str) {
    str = str.toLowerCase();
    for (const level of _a3.values) {
      if (level.name === str)
        return level;
    }
    const num = parseInt(str);
    if (!isNaN(num)) {
      for (const level of _a3.values) {
        if (level.level === num)
          return level;
      }
    }
    return void 0;
  }
}, __publicField(_a3, "All", new _a3(-2, "all")), __publicField(_a3, "Trace", new _a3(-2, "trace", ChatColor.DARK_AQUA)), __publicField(_a3, "Debug", new _a3(-1, "debug", ChatColor.AQUA)), __publicField(_a3, "Info", new _a3(0, "info", ChatColor.GREEN)), __publicField(_a3, "Warn", new _a3(1, "warn", ChatColor.GOLD)), __publicField(_a3, "Error", new _a3(2, "error", ChatColor.RED)), __publicField(_a3, "Fatal", new _a3(3, "fatal", ChatColor.DARK_RED)), __publicField(_a3, "Off", new _a3(100, "off")), /**
 * The list of all available log levels.
 */
__publicField(_a3, "values", [
  _a3.All,
  _a3.Trace,
  _a3.Debug,
  _a3.Info,
  _a3.Warn,
  _a3.Error,
  _a3.Fatal,
  _a3.Off
]), _a3);
function starMatch(pattern, str) {
  if (pattern === "*")
    return true;
  if (pattern.includes("*")) {
    if (pattern.startsWith("*")) {
      return str.endsWith(pattern.substring(1));
    }
    if (pattern.endsWith("*")) {
      return str.startsWith(pattern.substring(0, pattern.length - 1));
    }
    const regex = new RegExp(pattern.replace(/\*/g, ".*"));
    return regex.test(str);
  }
  return pattern === str;
}
var loggingSettings = {
  level: LogLevel.Info,
  filter: ["*"],
  outputTags: false,
  formatFunction: (level, logger, message, tags = void 0) => {
    const _tags = tags !== void 0 ? `\xA77${tags.map((tag) => `[${tag}]`).join("")}\xA7r` : "";
    return `[${level}][${ChatColor.MATERIAL_EMERALD}${logger.name}${ChatColor.RESET}]${_tags} ${message}`;
  },
  messagesJoinFunction: (messages) => {
    return messages.join(" ");
  },
  jsonFormatter: ColorJSON.DEFAULT,
  outputConfig: {
    [LogLevel.Trace.level]: [
      0,
      1
      /* ConsoleInfo */
    ],
    [LogLevel.Debug.level]: [
      0,
      1
      /* ConsoleInfo */
    ],
    [LogLevel.Info.level]: [
      0,
      1
      /* ConsoleInfo */
    ],
    [LogLevel.Warn.level]: [
      0,
      1,
      2
      /* ConsoleWarn */
    ],
    [LogLevel.Error.level]: [
      0,
      1,
      3
      /* ConsoleError */
    ],
    [LogLevel.Fatal.level]: [
      0,
      1,
      3
      /* ConsoleError */
    ]
  }
};
var _a4;
var Logger = (_a4 = class {
  /**
   * Construct a new Logger
   *
   * @param {string} name - The name of the Logger.
   * @param {string[]} tags - The tags for the logger as strings.
   */
  constructor(name, tags = []) {
    this.name = name;
    this.tags = tags;
  }
  /**
   *  Initialize logger class
   */
  static init() {
    LOGGING: {
      if (_a4.initialized)
        return;
      _a4.initialized = true;
      system2.afterEvents.scriptEventReceive.subscribe((ev) => {
        if (ev.id === "logging:level" || ev.id === "log:level") {
          if (!ev.message) {
            loggingSettings.level = LogLevel.Info;
            world3.sendMessage(
              `${ChatColor.AQUA}Logging level set to ${ChatColor.BOLD}${loggingSettings.level}`
            );
          } else {
            const level = LogLevel.parse(ev.message);
            if (level) {
              loggingSettings.level = level;
              world3.sendMessage(
                `${ChatColor.AQUA}Logging level set to ${ChatColor.BOLD}${loggingSettings.level}`
              );
            } else {
              world3.sendMessage(
                `${ChatColor.DARK_RED}Invalid logging level: ${ev.message}`
              );
            }
          }
        } else if (ev.id === "logging:filter" || ev.id === "log:filter") {
          if (!ev.message) {
            loggingSettings.filter = ["*"];
          } else {
            loggingSettings.filter = ev.message.split(",");
          }
          world3.sendMessage(
            `${ChatColor.AQUA}Logging filter set to ${ChatColor.BOLD}${loggingSettings.filter.join(", ")}`
          );
        }
      });
    }
  }
  /**
   * @param {LogLevel} level - The level to set.
   */
  static setLevel(level) {
    loggingSettings.level = level;
  }
  /**
   * Filter the loggers by the given tags. Tags can use the `*` wildcard.
   * @param {'*' | string[]} filter - The filter to set.
   */
  static setFilter(filter) {
    loggingSettings.filter = filter;
  }
  /**
   * Set the format function for the logger.
   * @param {function} func - The function to set.
   */
  static setFormatFunction(func) {
    loggingSettings.formatFunction = func;
  }
  /**
   * Set the function, that joins multiple messages into one for the logger.
   * @param {function} func - The function to set.
   */
  static setMessagesJoinFunction(func) {
    loggingSettings.messagesJoinFunction = func;
  }
  /**
   * Set the tag visibility for the logger. When true, tags will be printed in the log. Disabled by default.
   * @param visible
   */
  static setTagsOutputVisibility(visible) {
    loggingSettings.outputTags = visible;
  }
  /**
   * Set the JSON formatter for the logger.
   * @param {ColorJSON} formatter - The json formatter to set.
   */
  static setJsonFormatter(formatter) {
    loggingSettings.jsonFormatter = formatter;
  }
  /**
   * Get the output configuration for the logger.
   * @returns {OutputConfig} The output configuration.
   */
  static getOutputConfig() {
    return loggingSettings.outputConfig;
  }
  /**
   * Returns a new Logger.
   *
   * @param {string} name - The name of the Logger.
   * @param {string[]} tags - The tags for the Logger as strings.
   *
   * @returns {Logger} A new Logger.
   */
  static getLogger(name, ...tags) {
    LOGGING: {
      if (!_a4.initialized) {
        _a4.init();
      }
    }
    return new _a4(name, tags);
  }
  /**
   * Log messages with the level set.
   *
   * @param {LogLevel} level - The LogLevel to log the messages at.
   * @param {array} message - An array of the messages to log.
   */
  log(level, ...message) {
    LOGGING: {
      if (level.level < loggingSettings.level.level)
        return;
      if (loggingSettings.filter.length === 0 || this.tags.length === 0) {
        this.logRaw(level, ...message);
        return;
      }
      for (const filter of loggingSettings.filter) {
        if (filter.startsWith("!")) {
          if (starMatch(filter.substring(1), this.name) || this.tags.some((tag) => starMatch(filter.substring(1), tag))) {
            return;
          }
        }
        if (starMatch(filter, this.name) || this.tags.some((tag) => starMatch(filter, tag))) {
          this.logRaw(level, ...message);
          return;
        }
      }
    }
  }
  stringifyError(x) {
    let stack = x.stack ?? "";
    if (sourceMapping) {
      const stackLineRegex = /\(([^)]+\.js):(\d+)(?::(\d+))?\)/;
      stack = stack.split("\n").map((line) => {
        const match = stackLineRegex.exec(line);
        if (match) {
          const filePath = match[1];
          const lineNumber = parseInt(match[2], 10) - sourceMapping.metadata.offset;
          if (filePath.includes(sourceMapping.metadata.filePath)) {
            const mappingEntry = globalSourceMapping[lineNumber];
            if (mappingEntry) {
              const replacement = `(${mappingEntry.source}:${mappingEntry.originalLine})`;
              return line.replace(stackLineRegex, replacement);
            }
          }
        }
        return line;
      }).join("\n");
    }
    return `${ChatColor.DARK_RED}${ChatColor.BOLD}${x.message}
${ChatColor.RESET}${ChatColor.GRAY}${ChatColor.ITALIC}${stack}${ChatColor.RESET}`;
  }
  /**
   * Internal function to log messages with the level set, that bypasses the filters.
   *
   * @param {LogLevel} level - The LogLevel to log the messages at.
   * @param {array} message - An array of the messages to log.
   */
  logRaw(level, ...message) {
    LOGGING: {
      const msgs = message.map((x) => {
        if (x === void 0) {
          return ChatColor.GOLD + "undefined" + ChatColor.RESET;
        }
        if (x === null) {
          return ChatColor.GOLD + "null" + ChatColor.RESET;
        }
        if (x && x instanceof Error) {
          return this.stringifyError(x);
        }
        if (typeof x === "object" || Array.isArray(x)) {
          return loggingSettings.jsonFormatter.stringify(x) + ChatColor.RESET;
        }
        return x.toString() + ChatColor.RESET;
      });
      const formatted = loggingSettings.formatFunction(
        level,
        this,
        loggingSettings.messagesJoinFunction(msgs),
        loggingSettings.outputTags ? this.tags : void 0
      );
      const outputs = loggingSettings.outputConfig[level.level] || [
        0,
        1
        /* ConsoleInfo */
      ];
      if (outputs.includes(
        0
        /* Chat */
      )) {
        world3.sendMessage(formatted);
      }
      if (outputs.includes(
        1
        /* ConsoleInfo */
      )) {
        if (console.originalLog) {
          console.originalLog(ChatColor.stripColor(formatted));
        } else {
          console.log(ChatColor.stripColor(formatted));
        }
      }
      if (outputs.includes(
        2
        /* ConsoleWarn */
      )) {
        console.warn(formatted);
      }
      if (outputs.includes(
        3
        /* ConsoleError */
      )) {
        console.error(formatted);
      }
    }
  }
  /**
   * Logs a trace message.
   *
   * @param {...unknown} message - The message(s) to be logged.
   */
  trace(...message) {
    LOGGING:
      this.log(LogLevel.Trace, ...message);
  }
  /**
   * Logs debug message.
   *
   * @param {...unknown[]} message - The message(s) to be logged.
   */
  debug(...message) {
    LOGGING:
      this.log(LogLevel.Debug, ...message);
  }
  /**
   * Logs an informational message.
   *
   * @param {...unknown[]} message - The message(s) to be logged.
   */
  info(...message) {
    LOGGING:
      this.log(LogLevel.Info, ...message);
  }
  /**
   * Logs a warning message.
   *
   * @param {...unknown[]} message - The warning message or messages to be logged.
   */
  warn(...message) {
    LOGGING:
      this.log(LogLevel.Warn, ...message);
  }
  /**
   * Logs an error message.
   *
   * @param {...unknown[]} message - The error message(s) to log.
   */
  error(...message) {
    LOGGING:
      this.log(LogLevel.Error, ...message);
  }
  /**
   * Logs a fatal error.
   *
   * @param {unknown[]} message - The error message to log.
   */
  fatal(...message) {
    LOGGING:
      this.log(LogLevel.Fatal, ...message);
  }
}, __publicField(_a4, "initialized", false), _a4);
var _a5;
var Vec3 = (_a5 = class {
  constructor(x, y, z) {
    __publicField(this, "x");
    __publicField(this, "y");
    __publicField(this, "z");
    if (x === Direction.Down) {
      this.x = 0;
      this.y = -1;
      this.z = 0;
    } else if (x === Direction.Up) {
      this.x = 0;
      this.y = 1;
      this.z = 0;
    } else if (x === Direction.North) {
      this.x = 0;
      this.y = 0;
      this.z = -1;
    } else if (x === Direction.South) {
      this.x = 0;
      this.y = 0;
      this.z = 1;
    } else if (x === Direction.East) {
      this.x = 1;
      this.y = 0;
      this.z = 0;
    } else if (x === Direction.West) {
      this.x = -1;
      this.y = 0;
      this.z = 0;
    } else if (typeof x === "number") {
      this.x = x;
      this.y = y;
      this.z = z;
    } else if (Array.isArray(x)) {
      this.x = x[0];
      this.y = x[1];
      this.z = x[2];
    } else if (x instanceof _a5) {
      this.x = x.x;
      this.y = x.y;
      this.z = x.z;
    } else {
      if (!x || !x.x && x.x !== 0 || !x.y && x.y !== 0 || !x.z && x.z !== 0) {
        _a5.log.error(new Error("Invalid vector"), x);
        throw new Error("Invalid vector");
      }
      this.x = x.x;
      this.y = x.y;
      this.z = x.z;
    }
  }
  static from(x, y, z) {
    if (x instanceof _a5)
      return x;
    if (typeof x === "number" && y !== void 0 && z !== void 0) {
      return new _a5(x, y, z);
    }
    if (Array.isArray(x)) {
      return new _a5(x);
    }
    if (x === Direction.Down)
      return _a5.Down;
    if (x === Direction.Up)
      return _a5.Up;
    if (x === Direction.North)
      return _a5.North;
    if (x === Direction.South)
      return _a5.South;
    if (x === Direction.East)
      return _a5.East;
    if (x === Direction.West)
      return _a5.West;
    if (!x || !x.x && x.x !== 0 || !x.y && x.y !== 0 || !x.z && x.z !== 0) {
      _a5.log.error(new Error("Invalid arguments"), x, y, z);
      throw new Error("Invalid arguments");
    }
    return new _a5(
      x.x,
      x.y,
      x.z
    );
  }
  static _from(x, y, z) {
    if (x instanceof _a5)
      return x;
    if (typeof x === "number" && y !== void 0 && z !== void 0) {
      return new _a5(x, y, z);
    }
    if (Array.isArray(x)) {
      return new _a5(x);
    }
    if (x === Direction.Down)
      return _a5.Down;
    if (x === Direction.Up)
      return _a5.Up;
    if (x === Direction.North)
      return _a5.North;
    if (x === Direction.South)
      return _a5.South;
    if (x === Direction.East)
      return _a5.East;
    if (x === Direction.West)
      return _a5.West;
    if (!x || !x.x && x.x !== 0 || !x.y && x.y !== 0 || !x.z && x.z !== 0) {
      _a5.log.error(new Error("Invalid arguments"), x, y, z);
      throw new Error("Invalid arguments");
    }
    return new _a5(
      x.x,
      x.y,
      x.z
    );
  }
  /**
   * Creates a copy of the current vector.
   *
   * @returns A new vector with the same values as the current vector.
   */
  copy() {
    return new _a5(this.x, this.y, this.z);
  }
  static fromYawPitch(yawOrRotation, pitch) {
    let yaw;
    if (typeof yawOrRotation === "number") {
      yaw = yawOrRotation;
      pitch = pitch;
    } else {
      yaw = yawOrRotation.y;
      pitch = yawOrRotation.x;
    }
    const psi = yaw * (Math.PI / 180);
    const theta = pitch * (Math.PI / 180);
    const x = Math.cos(theta) * Math.sin(psi);
    const y = Math.sin(theta);
    const z = Math.cos(theta) * Math.cos(psi);
    return new _a5(x, y, z);
  }
  /**
   * Converts the normal vector to yaw and pitch values.
   *
   * @returns A Vector2 containing the yaw and pitch values.
   */
  toYawPitch() {
    if (this.isZero()) {
      _a5.log.error(
        new Error("Cannot convert zero-length vector to direction")
      );
      throw new Error("Cannot convert zero-length vector to direction");
    }
    const direction = this.normalize();
    const yaw = Math.atan2(direction.x, direction.z) * (180 / Math.PI);
    const pitch = Math.asin(direction.y) * (180 / Math.PI);
    return {
      x: pitch,
      y: yaw
    };
  }
  add(x, y, z) {
    const v = _a5._from(x, y, z);
    return _a5.from(v.x + this.x, v.y + this.y, v.z + this.z);
  }
  subtract(x, y, z) {
    const v = _a5._from(x, y, z);
    return _a5.from(this.x - v.x, this.y - v.y, this.z - v.z);
  }
  multiply(x, y, z) {
    if (typeof x === "number" && y === void 0 && z === void 0) {
      return _a5.from(this.x * x, this.y * x, this.z * x);
    }
    const v = _a5._from(x, y, z);
    return _a5.from(v.x * this.x, v.y * this.y, v.z * this.z);
  }
  /**
   * Scales the current vector by a scalar.
   *
   * @param scalar - The scalar to scale the vector by.
   * @returns The updated vector after scaling.
   */
  scale(scalar) {
    return _a5.from(this.x * scalar, this.y * scalar, this.z * scalar);
  }
  divide(x, y, z) {
    if (typeof x === "number" && y === void 0 && z === void 0) {
      if (x === 0)
        throw new Error("Cannot divide by zero");
      return _a5.from(this.x / x, this.y / x, this.z / x);
    }
    const v = _a5._from(x, y, z);
    if (v.x === 0 || v.y === 0 || v.z === 0)
      throw new Error("Cannot divide by zero");
    return _a5.from(this.x / v.x, this.y / v.y, this.z / v.z);
  }
  /**
   * Normalizes the vector to have a length (magnitude) of 1.
   * Normalized vectors are often used as a direction vectors.
   *
   * @returns The normalized vector.
   */
  normalize() {
    if (this.isZero()) {
      _a5.log.error(new Error("Cannot normalize zero-length vector"));
      throw new Error("Cannot normalize zero-length vector");
    }
    const len = this.length();
    return _a5.from(this.x / len, this.y / len, this.z / len);
  }
  /**
   * Computes the length (magnitude) of the vector.
   *
   * @returns The length of the vector.
   */
  length() {
    return Math.sqrt(this.lengthSquared());
  }
  /**
   * Computes the squared length of the vector.
   * This is faster than computing the actual length and can be useful for comparison purposes.
   *
   * @returns The squared length of the vector.
   */
  lengthSquared() {
    return this.x * this.x + this.y * this.y + this.z * this.z;
  }
  cross(x, y, z) {
    const v = _a5._from(x, y, z);
    return _a5.from(
      this.y * v.z - this.z * v.y,
      this.z * v.x - this.x * v.z,
      this.x * v.y - this.y * v.x
    );
  }
  distance(x, y, z) {
    const v = _a5._from(x, y, z);
    return Math.sqrt(this.distanceSquared(v));
  }
  distanceSquared(x, y, z) {
    const v = _a5._from(x, y, z);
    return this.subtract(v).lengthSquared();
  }
  /**
   * Computes the linear interpolation between the current vector and another vector, when t is in the range [0, 1].
   * Computes the extrapolation when t is outside this range.
   *
   * @param v - The other vector.
   * @param t - The interpolation factor.
   * @returns A new vector after performing the lerp operation.
   */
  lerp(v, t) {
    if (!v || !t)
      return _a5.from(this);
    if (t === 1)
      return _a5.from(v);
    if (t === 0)
      return _a5.from(this);
    return _a5.from(
      this.x + (v.x - this.x) * t,
      this.y + (v.y - this.y) * t,
      this.z + (v.z - this.z) * t
    );
  }
  /**
   * Computes the spherical linear interpolation between the current vector and another vector, when t is in the range [0, 1].
   * Computes the extrapolation when t is outside this range.
   *
   * @param v - The other vector.
   * @param t - The interpolation factor.
   * @returns A new vector after performing the slerp operation.
   */
  slerp(v, t) {
    if (!v || !t)
      return _a5.from(this);
    if (t === 1)
      return _a5.from(v);
    if (t === 0)
      return _a5.from(this);
    const dot = this.dot(v);
    const theta = Math.acos(dot) * t;
    const relative = _a5.from(v).subtract(this.multiply(dot)).normalize();
    return this.multiply(Math.cos(theta)).add(
      relative.multiply(Math.sin(theta))
    );
  }
  dot(x, y, z) {
    const v = _a5._from(x, y, z);
    return this.x * v.x + this.y * v.y + this.z * v.z;
  }
  angleBetween(x, y, z) {
    const v = _a5._from(x, y, z);
    const dotProduct = this.dot(v);
    const lengths = this.length() * v.length();
    if (lengths === 0) {
      return 0;
    }
    return Math.acos(dotProduct / lengths);
  }
  projectOnto(x, y, z) {
    const v = _a5._from(x, y, z);
    if (v.isZero()) {
      return _a5.Zero;
    }
    const scale = this.dot(v) / v.dot(v);
    return _a5.from(v.x * scale, v.y * scale, v.z * scale);
  }
  reflect(x, y, z) {
    const normal = _a5._from(x, y, z);
    const proj = this.projectOnto(normal);
    return this.subtract(proj.multiply(2));
  }
  /**
   * Rotates the current normalized vector by a given angle around a given axis.
   *
   * @param axis - The axis of rotation.
   * @param angle - The angle of rotation in degrees.
   * @returns The rotated vector.
   */
  rotate(axis, angle) {
    const halfAngle = angle * Math.PI / 180 / 2;
    const w = Math.cos(halfAngle);
    const x = axis.x * Math.sin(halfAngle);
    const y = axis.y * Math.sin(halfAngle);
    const z = axis.z * Math.sin(halfAngle);
    const v = this;
    const qv_x = w * w * v.x + 2 * y * w * v.z - 2 * z * w * v.y + x * x * v.x + 2 * y * x * v.y + 2 * z * x * v.z - z * z * v.x - y * y * v.x;
    const qv_y = 2 * x * y * v.x + y * y * v.y + 2 * z * y * v.z + 2 * w * z * v.x - z * z * v.y + w * w * v.y - 2 * x * w * v.z - x * x * v.y;
    const qv_z = 2 * x * z * v.x + 2 * y * z * v.y + z * z * v.z - 2 * w * y * v.x - y * y * v.z + 2 * w * x * v.y - x * x * v.z + w * w * v.z;
    return new _a5(qv_x, qv_y, qv_z);
  }
  /**
   * Updates the X, Y, and Z components of the vector.
   *
   * @param x - The function to use to update the X value.
   * @param y - The function to use to update the Y value.
   * @param z - The function to use to update the Z value.
   * @returns The updated vector with the new values.
   */
  update(x, y, z) {
    if (!x) {
      x = (value) => value;
    }
    if (!y) {
      y = (value) => value;
    }
    if (!z) {
      z = (value) => value;
    }
    return new _a5(x(this.x), y(this.y), z(this.z));
  }
  setX(value) {
    if (typeof value === "number") {
      return new _a5(value, this.y, this.z);
    }
    return new _a5(value(this.x), this.y, this.z);
  }
  setY(value) {
    if (typeof value === "number") {
      return new _a5(this.x, value, this.z);
    }
    return new _a5(this.x, value(this.y), this.z);
  }
  setZ(value) {
    if (typeof value === "number") {
      return new _a5(this.x, this.y, value);
    }
    return new _a5(this.x, this.y, value(this.z));
  }
  /**
   * Calculates the shortest distance between a point (represented by this Vector3 instance) and a line segment.
   *
   * This method finds the perpendicular projection of the point onto the line defined by the segment. If this
   * projection lies outside the line segment, then the method calculates the distance from the point to the
   * nearest segment endpoint.
   *
   * @param start - The starting point of the line segment.
   * @param end - The ending point of the line segment.
   * @returns The shortest distance between the point and the line segment.
   */
  distanceToLineSegment(start, end) {
    const lineDirection = _a5.from(end).subtract(start);
    if (lineDirection.lengthSquared() === 0) {
      return this.subtract(start).length();
    }
    const t = Math.max(
      0,
      Math.min(
        1,
        this.subtract(start).dot(lineDirection) / lineDirection.dot(lineDirection)
      )
    );
    const projection = _a5.from(start).add(lineDirection.multiply(t));
    return this.subtract(projection).length();
  }
  /**
   * Floors the X, Y, and Z components of the vector.
   * @returns A new vector with the floored components.
   */
  floor() {
    return this.update(Math.floor, Math.floor, Math.floor);
  }
  /**
   * Floors the X component of the vector.
   * @returns A new vector with the floored X component.
   */
  floorX() {
    return this.setX(Math.floor);
  }
  /**
   * Floors the Y component of the vector.
   * @returns A new vector with the floored Y component.
   */
  floorY() {
    return this.setY(Math.floor);
  }
  /**
   * Floors the Z component of the vector.
   * @returns A new vector with the floored Z component.
   */
  floorZ() {
    return this.setZ(Math.floor);
  }
  /**
   * Ceils the X, Y, and Z components of the vector.
   * @returns A new vector with the ceiled components.
   */
  ceil() {
    return new _a5(Math.ceil(this.x), Math.ceil(this.y), Math.ceil(this.z));
  }
  /**
   * Ceils the X component of the vector.
   * @returns A new vector with the ceiled X component.
   */
  ceilX() {
    return this.setX(Math.ceil);
  }
  /**
   * Ceils the Y component of the vector.
   * @returns A new vector with the ceiled Y component.
   */
  ceilY() {
    return this.setY(Math.ceil);
  }
  /**
   * Ceils the Z component of the vector.
   * @returns A new vector with the ceiled Z component.
   */
  ceilZ() {
    return this.setZ(Math.ceil);
  }
  /**
   * Rounds the X, Y, and Z components of the vector.
   * @returns A new vector with the rounded components.
   */
  round() {
    return this.update(Math.round, Math.round, Math.round);
  }
  /**
   * Rounds the X component of the vector.
   * @returns A new vector with the rounded X component.
   */
  roundX() {
    return this.setX(Math.round);
  }
  /**
   * Rounds the Y component of the vector.
   * @returns A new vector with the rounded Y component.
   */
  roundY() {
    return this.setY(Math.round);
  }
  /**
   * Rounds the Z component of the vector.
   * @returns A new vector with the rounded Z component.
   */
  roundZ() {
    return this.setZ(Math.round);
  }
  /**
   * Returns a new vector offset from the current vector up by 1 block.
   * @returns A new vector offset from the current vector up by 1 block.
   */
  up() {
    return this.add(_a5.Up);
  }
  /**
   * Returns a new vector offset from the current vector down by 1 block.
   * @returns A new vector offset from the current vector down by 1 block.
   */
  down() {
    return this.add(_a5.Down);
  }
  /**
   * Returns a new vector offset from the current vector north by 1 block.
   * @returns A new vector offset from the current vector north by 1 block.
   */
  north() {
    return this.add(_a5.North);
  }
  /**
   * Returns a new vector offset from the current vector south by 1 block.
   * @returns A new vector offset from the current vector south by 1 block.
   */
  south() {
    return this.add(_a5.South);
  }
  /**
   * Returns a new vector offset from the current vector east by 1 block.
   * @returns A new vector offset from the current vector east by 1 block.
   */
  east() {
    return this.add(_a5.East);
  }
  /**
   * Returns a new vector offset from the current vector west by 1 block.
   * @returns A new vector offset from the current vector west by 1 block.
   */
  west() {
    return this.add(_a5.West);
  }
  /**
   * Checks if the current vector is equal to the zero vector.
   * @returns true if the vector is equal to the zero vector, else returns false.
   */
  isZero() {
    return this.x === 0 && this.y === 0 && this.z === 0;
  }
  /**
   * Converts the vector to an array containing the X, Y, and Z components of the vector.
   * @returns An array containing the X, Y, and Z components of the vector.
   */
  toArray() {
    return [this.x, this.y, this.z];
  }
  /**
   * Converts the vector to a direction.
   * If the vector is not a unit vector, then it will be normalized and rounded to the nearest direction.
   */
  toDirection() {
    if (this.isZero()) {
      _a5.log.error(
        new Error("Cannot convert zero-length vector to direction")
      );
      throw new Error("Cannot convert zero-length vector to direction");
    }
    const normalized = this.normalize();
    const maxValue = Math.max(
      Math.abs(normalized.x),
      Math.abs(normalized.y),
      Math.abs(normalized.z)
    );
    if (maxValue === normalized.x)
      return Direction.East;
    if (maxValue === -normalized.x)
      return Direction.West;
    if (maxValue === normalized.y)
      return Direction.Up;
    if (maxValue === -normalized.y)
      return Direction.Down;
    if (maxValue === normalized.z)
      return Direction.South;
    if (maxValue === -normalized.z)
      return Direction.North;
    _a5.log.error(new Error("Cannot convert vector to direction"), this);
    throw new Error("Cannot convert vector to direction");
  }
  /**
   * Returns a new vector with the X, Y, and Z components rounded to the nearest block location.
   */
  toBlockLocation() {
    return _a5.from(
      (this.x << 0) - (this.x < 0 && this.x !== this.x << 0 ? 1 : 0),
      (this.y << 0) - (this.y < 0 && this.y !== this.y << 0 ? 1 : 0),
      (this.z << 0) - (this.z < 0 && this.z !== this.z << 0 ? 1 : 0)
    );
  }
  almostEqual(x, y, z, delta) {
    try {
      let other;
      if (typeof x !== "number" && z === void 0) {
        other = _a5._from(x, void 0, void 0);
        delta = y;
      } else {
        other = _a5._from(x, y, z);
      }
      return Math.abs(this.x - other.x) <= delta && Math.abs(this.y - other.y) <= delta && Math.abs(this.z - other.z) <= delta;
    } catch (e) {
      return false;
    }
  }
  equals(x, y, z) {
    try {
      const other = _a5._from(x, y, z);
      return this.x === other.x && this.y === other.y && this.z === other.z;
    } catch (e) {
      return false;
    }
  }
  /**
   * Converts the vector to a string representation.
   *
   * @param format - The format of the string representation. Defaults to "long".
   * @param separator - The separator to use between components. Defaults to ", ".
   * @returns The string representation of the vector.
   * @remarks
   * The "long" format is "Vec3(x, y, z)".
   * The "short" format is "x, y, z".
   */
  toString(format = "long", separator = ", ") {
    const result = `${this.x + separator + this.y + separator + this.z}`;
    return format === "long" ? `Vec3(${result})` : result;
  }
}, __publicField(_a5, "log", Logger.getLogger(
  "vec3",
  "vec3",
  "bedrock-boost"
)), __publicField(_a5, "Zero", new _a5(0, 0, 0)), __publicField(_a5, "Down", new _a5(Direction.Down)), __publicField(_a5, "Up", new _a5(Direction.Up)), __publicField(_a5, "North", new _a5(Direction.North)), __publicField(_a5, "South", new _a5(Direction.South)), __publicField(_a5, "East", new _a5(Direction.East)), __publicField(_a5, "West", new _a5(Direction.West)), _a5);
var _a6;
var Timings = (_a6 = class {
  /**
   * Begin measuring the time it takes to perform an operation.
   * @remarks
   * If another operation is already being measured, the measurement will be ended.
   * 
   * @param operation The name of the operation.
   */
  static begin(operation) {
    this.end();
    this.lastTime = (/* @__PURE__ */ new Date()).getTime();
    this.lastOperation = operation;
  }
  /**
   * End measuring the time it takes to perform an operation and log the result.
   * @remarks
   * If no operation is being measured, this method will do nothing.
   */
  static end() {
    const time = (/* @__PURE__ */ new Date()).getTime();
    if (this.lastTime > 0) {
      _a6.log.debug(`Operation ${this.lastOperation} took ${time - this.lastTime}ms`);
    }
    this.lastTime = -1;
  }
}, __publicField(_a6, "log", Logger.getLogger("Timings", "timings")), __publicField(_a6, "lastTime", -1), __publicField(_a6, "lastOperation", ""), _a6);
function isVersion2(entity) {
  const isValid2 = entity.isValid;
  if (isValid2 === true || isValid2 === false) {
    return true;
  }
  return false;
}
function isValid(entity) {
  const isValid2 = entity.isValid;
  if (isValid2 === true || isValid2 === false) {
    return isValid2;
  }
  return isValid2();
}
function applyImpulseNew(entity, vector) {
  const { x, y, z } = vector;
  const previousVelocity = entity.getVelocity();
  const horizontalNorm = Math.sqrt(x * x + z * z);
  let directionX = 0;
  let directionZ = 0;
  if (horizontalNorm !== 0) {
    directionX = x / horizontalNorm;
    directionZ = z / horizontalNorm;
  }
  const horizontalStrength = horizontalNorm * 2.5;
  const verticalStrength = y + previousVelocity.y * 0.9;
  if (isVersion2(entity)) {
    entity.applyKnockback(
      {
        x: horizontalStrength * directionX,
        z: horizontalStrength * directionZ
      },
      verticalStrength
    );
  } else {
    entity.applyKnockback(directionX, directionZ, horizontalStrength, verticalStrength);
  }
}
function clearVelocity(entity) {
  const { x, z } = entity.getVelocity();
  const horizontalNorm = Math.sqrt(x * x + z * z);
  let directionX = 0;
  let directionZ = 0;
  if (horizontalNorm !== 0) {
    directionX = -x / horizontalNorm;
    directionZ = -z / horizontalNorm;
  }
  if (isVersion2(entity)) {
    entity.applyKnockback(
      {
        x: horizontalNorm * directionX,
        z: horizontalNorm * directionZ
      },
      0
    );
  } else {
    entity.applyKnockback(directionX, directionZ, horizontalNorm, 0);
  }
}
function install() {
  Player2.prototype.applyImpulse = function(vector) {
    applyImpulseNew(this, vector);
  };
  Player2.prototype.clearVelocity = function() {
    clearVelocity(this);
  };
}
var _a7;
var Polyfill = (_a7 = class {
  /**
   * Installs the polyfill for the console.
   * 
   * This polyfill makes `console.log` send a message to the world chat.
   */
  static installConsole() {
    if (this._installed.get("console"))
      return;
    this._installed.set("console", true);
    console.originalLog = console.log;
    console.log = (...args) => {
      console.originalLog(...args);
      const message = args.join(" ");
      world32.sendMessage(message);
    };
  }
  /**
   * Installs the polyfill for the player.
   * 
   * This polyfill adds the following methods to the player:
   * - applyImpulse
   * - clearVelocity
   */
  static installPlayer() {
    if (this._installed.get("player"))
      return;
    this._installed.set("player", true);
    install();
  }
}, __publicField(_a7, "_installed", /* @__PURE__ */ new Map()), _a7);
var log = Logger.getLogger("jobUtils", "bedrock-boost", "jobUtils");
var _a8;
var PulseScheduler = (_a8 = class {
  /**
   * Creates a new PulseScheduler instance.
   * @param period The period of the scheduler.
   */
  constructor(processor, period) {
    __publicField(this, "items", []);
    __publicField(this, "period");
    __publicField(this, "currentTick", 0);
    __publicField(this, "runId");
    __publicField(this, "nextIndex", 0);
    __publicField(this, "executionSchedule", []);
    __publicField(this, "processor");
    if (period <= 0) {
      throw new Error("Period must be a positive integer.");
    }
    if (!processor || typeof processor !== "function") {
      throw new Error("Processor function must be defined.");
    }
    this.period = period;
    this.processor = processor;
  }
  /**
   * Adds an item to the schedule.
   * @param item The item to be added.
   * @deprecated Use `push` instead.
   */
  add(item) {
    this.push(item);
  }
  /**
    * Adds multiple items to the schedule.
    * 
    * @param items - The items to be added.
    * @deprecated Use `push` instead.
    */
  addAll(items) {
    this.push(...items);
  }
  /**
   * Removes an item from the schedule at the specified index.
   * @param index - The index of the item to remove.
   */
  remove(index) {
    if (index >= 0 && index < this.items.length) {
      this.items.splice(index, 1);
      if (index < this.nextIndex) {
        this.nextIndex--;
      }
      this.recalculateExecutionSchedule();
    }
  }
  /**
   * Removes items from the schedule that satisfy the given predicate.
   * 
   * @param predicate - The predicate function used to determine if an item should be removed.
   */
  removeIf(predicate) {
    for (let i = this.items.length - 1; i >= 0; i--) {
      if (predicate(this.items[i])) {
        this.remove(i);
      }
    }
  }
  /**
   * Returns a list of the items in the schedule.
   */
  getItems() {
    return this.items;
  }
  /**
   * Starts the schedule.
   */
  start() {
    this.stop();
    this.currentTick = 0;
    this.nextIndex = 0;
    this.runId = system4.runInterval(() => this.tick(), 1);
  }
  /**
   * Stops the schedule.
   */
  stop() {
    if (this.runId !== void 0) {
      system4.clearRun(this.runId);
      this.runId = void 0;
    }
  }
  recalculateExecutionSchedule() {
    const totalExecutions = this.items.length;
    this.executionSchedule = new Array(this.period).fill(0);
    if (totalExecutions === 0) {
      return;
    }
    const interval = this.period / totalExecutions;
    for (let i = 0; i < totalExecutions; i++) {
      this.executionSchedule[Math.round(interval * i) % this.period]++;
    }
  }
  tick() {
    if (this.items.length === 0) {
      _a8.log.trace("No items to process.");
      return;
    }
    const scheduledExecutions = this.executionSchedule[this.currentTick];
    if (scheduledExecutions === 0) {
      _a8.log.trace("No items to process this tick.");
      this.currentTick = (this.currentTick + 1) % this.period;
      if (this.currentTick === 0) {
        this.nextIndex = 0;
      }
      return;
    }
    let executed = 0;
    for (; this.nextIndex < this.items.length && executed < scheduledExecutions; this.nextIndex++) {
      try {
        this.processor(this.items[this.nextIndex]);
      } catch (e) {
        _a8.log.error("Error processing item", e);
      }
      executed++;
    }
    this.currentTick = (this.currentTick + 1) % this.period;
    if (this.currentTick === 0) {
      this.nextIndex = 0;
    }
  }
  push(...items) {
    this.items.push(...items);
    this.recalculateExecutionSchedule();
    return this.items.length;
  }
  pop() {
    const item = this.items.pop();
    this.recalculateExecutionSchedule();
    return item;
  }
  shift() {
    const item = this.items.shift();
    this.recalculateExecutionSchedule();
    return item;
  }
  unshift(...items) {
    this.items.unshift(...items);
    this.recalculateExecutionSchedule();
    return this.items.length;
  }
  splice(start, deleteCount = 0, ...items) {
    const removed = this.items.splice(start, deleteCount, ...items);
    this.recalculateExecutionSchedule();
    return removed;
  }
}, __publicField(_a8, "log", Logger.getLogger("PulseScheduler", "bedrock-boost", "pulse-scheduler")), _a8);
var _a9;
var EntityPulseScheduler = (_a9 = class extends PulseScheduler {
  /**
   * Creates a new EntityPulseScheduler instance.
   * @param period The period of the scheduler.
   * @param queryOptions The query options to use when querying for entities.
   */
  constructor(processor, period, queryOptions) {
    super((t) => {
      if (isValid(t)) {
        processor(t);
      } else {
        this.removeIf((entity) => !isValid(entity));
      }
    }, period);
    this.queryOptions = queryOptions;
    this.push(
      ...world4.getDimension("minecraft:overworld").getEntities(this.queryOptions)
    );
    this.push(
      ...world4.getDimension("minecraft:nether").getEntities(this.queryOptions)
    );
    this.push(
      ...world4.getDimension("minecraft:the_end").getEntities(this.queryOptions)
    );
  }
  compareEntities(a, b) {
    return a.id === b.id;
  }
  start() {
    world4.afterEvents.entityLoad.subscribe((event) => {
      this.addIfMatchesWithRetry(event.entity);
    });
    world4.afterEvents.entitySpawn.subscribe((event) => {
      this.addIfMatchesWithRetry(event.entity);
    });
    world4.afterEvents.entityRemove.subscribe((event) => {
      this.removeIf(
        (entity) => !isValid(entity) || entity.id === event.removedEntityId
      );
    });
    super.start();
  }
  /**
   * Adds an entity to the scheduler if it matches the query options. In case the entity is not valid, it will retry a tick later.
   * @param entity The entity to add.
   */
  addIfMatchesWithRetry(entity) {
    try {
      if (!entity) {
        return;
      }
      if (!isValid(entity)) {
        system5.runInterval(() => {
          if (isValid(entity) && entity.matches(this.queryOptions)) {
            this.push(entity);
          }
        }, 1);
      } else if (entity.matches(this.queryOptions)) {
        this.push(entity);
      }
    } catch (e) {
      _a9.logger.debug(
        "Failed to push entity to scheduler.",
        e
      );
    }
  }
  push(...items) {
    const filtered = items.filter(
      (item) => isValid(item) && !this.items.some(
        (existingItem) => this.compareEntities(existingItem, item)
      )
    );
    return super.push(...filtered);
  }
  unshift(...items) {
    const filtered = items.filter(
      (item) => isValid(item) && !this.items.some(
        (existingItem) => this.compareEntities(existingItem, item)
      )
    );
    return super.unshift(...filtered);
  }
  splice(start, deleteCount, ...items) {
    if (deleteCount === void 0) {
      return super.splice(start);
    }
    const filtered = items.filter(
      (item) => !this.items.some(
        (existingItem) => this.compareEntities(existingItem, item)
      )
    );
    return super.splice(start, deleteCount, ...filtered);
  }
}, __publicField(_a9, "logger", Logger.getLogger(
  "EntityPulseScheduler",
  "bedrock-boost",
  "entity-pulse-scheduler"
)), _a9);
var _a10;
var PlayerPulseScheduler = (_a10 = class extends PulseScheduler {
  /**
   * Creates a new PlayerPulseScheduler instance.
   * @param period The period of the scheduler.
   */
  constructor(processor, period) {
    super((t) => {
      if (isValid(t)) {
        processor(t);
      } else {
        this.removeIf((entity) => !isValid(entity));
      }
    }, period);
    this.push(...world5.getAllPlayers());
  }
  compareEntities(a, b) {
    return a.id === b.id;
  }
  start() {
    world5.afterEvents.playerJoin.subscribe((event) => {
      let attempts = 0;
      const pushPlayer = () => {
        attempts++;
        if (attempts > 10) {
          _a10.logger.debug("Failed to push player to scheduler after 10 attempts.");
          return;
        }
        try {
          const player = world5.getEntity(event.playerId);
          if (player === void 0) {
            system6.runTimeout(pushPlayer, 1);
          }
          if (player instanceof Player22) {
            this.push(player);
          }
        } catch (e) {
          _a10.logger.debug("Failed to push player to scheduler.", e);
          system6.runTimeout(pushPlayer, 1);
        }
      };
      pushPlayer();
    });
    world5.afterEvents.playerLeave.subscribe((event) => {
      this.removeIf((entity) => !isValid(entity) || entity.id === event.playerId);
    });
    super.start();
  }
  push(...items) {
    const filtered = items.filter((item) => isValid(item) && !this.items.some((existingItem) => this.compareEntities(existingItem, item)));
    return super.push(...filtered);
  }
  unshift(...items) {
    const filtered = items.filter((item) => isValid(item) && !this.items.some((existingItem) => this.compareEntities(existingItem, item)));
    return super.unshift(...filtered);
  }
  splice(start, deleteCount, ...items) {
    if (deleteCount === void 0) {
      return super.splice(start);
    }
    const filtered = items.filter((item) => !this.items.some((existingItem) => this.compareEntities(existingItem, item)));
    return super.splice(start, deleteCount, ...filtered);
  }
}, __publicField(_a10, "logger", Logger.getLogger("PlayerPulseScheduler", "bedrock-boost", "player-pulse-scheduler")), _a10);
var _a11;
var DirectionUtils = (_a11 = class {
}, /**
 * The opposite directions of the given directions.
 */
__publicField(_a11, "Opposites", {
  [Direction2.Down]: Direction2.Up,
  [Direction2.Up]: Direction2.Down,
  [Direction2.North]: Direction2.South,
  [Direction2.South]: Direction2.North,
  [Direction2.East]: Direction2.West,
  [Direction2.West]: Direction2.East
}), /**
 * The positive perpendicular directions of the given directions.
 */
__publicField(_a11, "PositivePerpendiculars", {
  [Direction2.Down]: [Direction2.East, Direction2.North],
  [Direction2.Up]: [Direction2.East, Direction2.North],
  [Direction2.North]: [Direction2.East, Direction2.Up],
  [Direction2.South]: [Direction2.East, Direction2.Up],
  [Direction2.East]: [Direction2.North, Direction2.Up],
  [Direction2.West]: [Direction2.North, Direction2.Up]
}), /**
 * The negative perpendicular directions of the given directions.
 */
__publicField(_a11, "NegativePerpendiculars", {
  [Direction2.Down]: [Direction2.West, Direction2.South],
  [Direction2.Up]: [Direction2.West, Direction2.South],
  [Direction2.North]: [Direction2.West, Direction2.Down],
  [Direction2.South]: [Direction2.West, Direction2.Down],
  [Direction2.East]: [Direction2.South, Direction2.Down],
  [Direction2.West]: [Direction2.South, Direction2.Down]
}), /**
 * All directions.
 */
__publicField(_a11, "Values", [
  Direction2.Down,
  Direction2.Up,
  Direction2.North,
  Direction2.South,
  Direction2.East,
  Direction2.West
]), _a11);
var log2 = Logger.getLogger("itemUtils", "bedrock-boost", "itemUtils");

// data/system_template_esbuild/local-modules/core_silent_explosion.ts
Polyfill.installPlayer();
function lerp(a, b, t) {
  return a + (b - a) * t;
}
function getCenterLocation(entity) {
  return Vec3.from(entity.location).add(entity.getHeadLocation()).divide(2);
}
function hasLineOfSight(position, entity, dimension, maxDistance, minDistanceForChecking) {
  let position2 = getCenterLocation(entity);
  let raycastOptions = { maxDistance: maxDistance - minDistanceForChecking };
  let raycastDirection = position2.subtract(position);
  if (raycastDirection.length() <= minDistanceForChecking) {
    return true;
  }
  const raycastStart = Vec3.from(position).add(
    raycastDirection.normalize().multiply(minDistanceForChecking)
  );
  let entitiesHit = dimension.getEntitiesFromRay(
    raycastStart,
    raycastDirection,
    raycastOptions
  );
  let entityHitDistance = void 0;
  for (let entityHit of entitiesHit) {
    if (entityHit.entity.id == entity.id) {
      entityHitDistance = entityHit.distance;
      break;
    }
  }
  if (entityHitDistance === void 0) {
    return false;
  }
  let blockHit = dimension.getBlockFromRay(
    raycastStart,
    raycastDirection,
    raycastOptions
  );
  if (blockHit !== void 0) {
    let blockHitDistance = Vec3.from(blockHit.block).distance(position);
    return entityHitDistance < blockHitDistance;
  }
  return true;
}
function createSilentExplosion(payload) {
  const {
    dimension,
    radius,
    playerTargetSelector,
    entityTargetSelector,
    explosionDamage,
    knockbackStrength,
    knockbackUpBias,
    damageOptions
  } = payload;
  if (playerTargetSelector === void 0 && entityTargetSelector === void 0) {
    return;
  }
  const position = Vec3.from(payload.position);
  const [minExplosionDamage, maxExplosionDamage] = explosionDamage;
  const [minKnockbackStrength, maxKnockbackStrength] = knockbackStrength;
  let entities2 = [];
  if (playerTargetSelector !== void 0) {
    entities2 = [
      ...entities2,
      ...dimension.getPlayers({
        ...playerTargetSelector,
        location: position,
        maxDistance: radius
      })
    ];
  }
  if (entityTargetSelector !== void 0) {
    entities2 = [
      ...entities2,
      ...dimension.getEntities({
        ...entityTargetSelector,
        location: position,
        maxDistance: radius
      })
    ];
  }
  let excludedEntityIds = payload.excludedEntityIds ?? [];
  for (let entity of entities2) {
    if (excludedEntityIds.includes(entity.id)) {
      continue;
    }
    if (!hasLineOfSight(
      position,
      entity,
      dimension,
      radius,
      payload.wallBangRadius ?? 1e-3
    )) {
      continue;
    }
    let lerpVal = position.distance(entity.location) / radius;
    let damage = lerp(maxExplosionDamage, minExplosionDamage, lerpVal);
    let knockbackStrength2 = lerp(
      maxKnockbackStrength,
      minKnockbackStrength,
      lerpVal
    );
    let knockbackDirection = Vec3.from(entity.location).subtract(position);
    if (knockbackDirection.length() <= 1e-4) {
      knockbackDirection = Vec3.Up;
    }
    knockbackDirection = knockbackDirection.normalize().add(0, knockbackUpBias, 0).normalize();
    try {
      entity.applyDamage(damage, damageOptions);
      entity.applyImpulse(knockbackDirection.multiply(knockbackStrength2));
    } catch {
    }
    if (payload.onEntityHit !== void 0) {
      payload.onEntityHit(entity);
    }
  }
}

// data/system_template_esbuild/subscripts/ankylosaurus_smash_attack.ts
var excludedBlocks = [
  "minecraft:water",
  "minecraft:lava",
  "minecraft:flowing_water",
  "minecraft:flowing_lava",
  "minecraft:bedrock",
  "minecraft:command_block",
  "minecraft:light_block",
  "minecraft:structure_block",
  "minecraft:structure_void",
  "minecraft:chain_command_block",
  "minecraft:repeating_command_block",
  "minecraft:barrier",
  "minecraft:border_block",
  "minecraft:jigsaw",
  "minecraft:allow",
  "minecraft:deny",
  "minecraft:bedrock",
  "minecraft:end_portal_frame",
  "minecraft:reinforced_deepslate",
  "minecraft:chest",
  "minecraft:trapped_chest",
  "minecraft:ender_chest",
  "minecraft:barrel",
  "minecraft:coal_ore",
  "minecraft:copper_ore",
  "minecraft:deepslate_coal_ore",
  "minecraft:deepslate_copper_ore",
  "minecraft:deepslate_diamond_ore",
  "minecraft:deepslate_emerald_ore",
  "minecraft:deepslate_gold_ore",
  "minecraft:deepslate_iron_ore",
  "minecraft:deepslate_lapis_ore",
  "minecraft:deepslate_redstone_ore",
  "minecraft:diamond_ore",
  "minecraft:emerald_ore",
  "minecraft:iron_ore",
  "minecraft:gold_ore",
  "minecraft:lapis_ore",
  "minecraft:redstone_ore",
  "minecraft:nether_gold_ore",
  "minecraft:quartz_ore",
  "minecraft:black_shulker_box",
  "minecraft:blue_shulker_box",
  "minecraft:brown_shulker_box",
  "minecraft:cyan_shulker_box",
  "minecraft:gray_shulker_box",
  "minecraft:green_shulker_box",
  "minecraft:light_blue_shulker_box",
  "minecraft:light_gray_shulker_box",
  "minecraft:lime_shulker_box",
  "minecraft:magenta_shulker_box",
  "minecraft:orange_shulker_box",
  "minecraft:pink_shulker_box",
  "minecraft:purple_shulker_box",
  "minecraft:red_shulker_box",
  "minecraft:undyed_shulker_box",
  "minecraft:white_shulker_box",
  "minecraft:yellow_shulker_box"
];
system8.afterEvents.scriptEventReceive.subscribe((event) => {
  const { sourceEntity } = event;
  if (event.id !== "shapescape_ext:ankylosaurus_smash_attack" || sourceEntity == void 0 || !sourceEntity.isValid() || sourceEntity.typeId !== "shapescape_ext:ankylosaurus") {
    return;
  }
  smashAttack(sourceEntity);
});
function smashAttack(entity) {
  entity.setProperty("shapescape_ext:smash_attack", false);
  const dimension = entity.dimension;
  const radius = 3;
  const rotation = entity.getRotation();
  const angle = (rotation.y + 180) * Math.PI / 180;
  const location = entity.location;
  const attackLocation = {
    x: entity.location.x + 2 * Math.sin(angle),
    // Front of the entity
    y: entity.location.y,
    z: entity.location.z - 2 * Math.cos(angle)
    // Front of the entity
  };
  const ownerName = getOwnerName(entity);
  const riderName = getRider(entity);
  system8.runTimeout(() => {
    const explosion = {
      entityTargetSelector: {
        excludeTypes: [
          "minecraft:item",
          "minecraft:arrow",
          "shapescape_ext:ankylosaurus"
        ],
        excludeFamilies: ["inanimate"],
        excludeNames: [ownerName]
      },
      playerTargetSelector: {
        excludeGameModes: [GameMode.creative, GameMode.spectator],
        excludeNames: [ownerName, riderName]
      },
      dimension,
      radius,
      explosionDamage: [15, 20],
      knockbackStrength: [0.7, 0.8],
      knockbackUpBias: 0.8,
      position: {
        x: attackLocation.x,
        y: attackLocation.y + 1,
        z: attackLocation.z
      },
      wallBangRadius: 1,
      damageOptions: {
        damagingEntity: entity,
        cause: EntityDamageCause.entityExplosion
      }
    };
    createSilentExplosion(explosion);
    destroyBlocks(Vec3.from(attackLocation), dimension, entity.getRotation().y);
  }, 20 * 0.4);
  system8.runTimeout(() => {
    entity.triggerEvent("shapescape_ext:movement");
  }, 20 * 1.75);
}
function destroyBlocks(location, dimension, yRotation) {
  const forwardAngle = (yRotation + 180) * Math.PI / 180;
  const forward = {
    x: Math.sin(forwardAngle),
    z: -Math.cos(forwardAngle)
  };
  const rightAngle = (yRotation + 90) * Math.PI / 180;
  const right = {
    x: Math.sin(rightAngle),
    z: -Math.cos(rightAngle)
  };
  const halfWidth = 1;
  const heightStart = 0;
  const heightEnd = 4;
  const tunnelDepth = 4;
  for (let dx = -halfWidth; dx <= halfWidth; dx++) {
    for (let dy = heightStart; dy <= heightEnd; dy++) {
      for (let dz = 0; dz < tunnelDepth; dz++) {
        const blockX = Math.floor(location.x + dx * right.x + dz * forward.x);
        const blockY = Math.floor(location.y + dy);
        const blockZ = Math.floor(location.z + dx * right.z + dz * forward.z);
        const blockLocation = {
          x: blockX,
          y: blockY,
          z: blockZ
        };
        const block = dimension.getBlock(blockLocation);
        if (block && !excludedBlocks.includes(block.typeId)) {
          block.dimension.runCommandAsync(
            `fill ${block.x} ${block.y} ${block.z} ${block.x} ${block.y} ${block.z}  air [] destroy`
          );
        }
      }
    }
  }
}
function getOwnerName(entity) {
  const tameable = entity.getComponent(
    "minecraft:tameable"
  );
  if (tameable && tameable.tamedToPlayer) {
    const players = world7.getAllPlayers();
    const owner = players.find(
      (player) => player.id === tameable.tamedToPlayerId
    );
    return owner ? owner.name : "Unknown";
  }
  return "Unknown";
}
function getRider(entity) {
  const rideableComp = entity.getComponent(
    "minecraft:rideable"
  );
  if (rideableComp === void 0)
    return "Unknown";
  if (rideableComp.getRiders().length > 0) {
    const players = world7.getAllPlayers();
    const rider = players.find(
      (player) => player.id === rideableComp.getRiders()[0].id
    );
    return rider ? rider.name : "Unknown";
  }
  return "Unknown";
}

// data/system_template_esbuild/subscripts/ankylosaurus_eating.ts
import { world as world8, system as system9 } from "@minecraft/server";
var TAG2 = "shapescape_ext_ankylosaurus_eating";
world8.afterEvents.playerInteractWithEntity.subscribe((event) => {
  const player = event.player;
  const itemStack = event.beforeItemStack;
  const entity = event.target;
  if (!itemStack || !player || !entity || entity.typeId !== "shapescape_ext:ankylosaurus" || itemStack.typeId !== "minecraft:spider_eye")
    return;
  const baby = entity.getComponent(
    "minecraft:is_baby"
  );
  if (!entity.hasTag(TAG2)) {
    entity.addTag(TAG2);
    if (baby) {
      entity.playAnimation(
        "animation.shapescape_ext.ankylosaurus_baby.chewing_layer",
        {
          blendOutTime: 0.2
        }
      );
    } else {
      entity.playAnimation("animation.shapescape_ext.ankylosaurus.chewing_layer", {
        blendOutTime: 0.2
      });
    }
    system9.runTimeout(() => {
      entity.removeTag(TAG2);
    }, 20 * 1.5);
  }
});

// data/system_template_esbuild/subscripts/bloomdodo_fertilizer.ts
import { system as system11 } from "@minecraft/server";

// data/node_modules/@shapescape-software/shapescriptapi/dist/index.mjs
import { system as system10 } from "@minecraft/server";
import { EntityInventoryComponent } from "@minecraft/server";
import {
  EntityTameableComponent as EntityTameableComponent2
} from "@minecraft/server";
import { world as world9 } from "@minecraft/server";
function randInt(min, max) {
  return Math.floor(uniform(min, max + 1));
}
function uniform(min, max) {
  return Math.random() * (max - min) + min;
}

// data/system_template_esbuild/subscripts/bloomdodo_fertilizer.ts
var flowerBlocks = [
  "minecraft:orange_tulip",
  "minecraft:pink_tulip",
  "minecraft:white_tulip",
  "minecraft:red_tulip",
  "minecraft:blue_orchid",
  "minecraft:allium",
  "minecraft:azure_bluet",
  "minecraft:cornflower",
  "minecraft:dandelion",
  "minecraft:lily_of_the_valley",
  "minecraft:oxeye_daisy",
  "minecraft:poppy",
  "minecraft:short_grass"
];
var blocksAllowToPlaceFlower = [
  "minecraft:grass_block",
  "minecraft:dirt",
  "minecraft:coarse_dirt",
  "minecraft:podzol",
  "minecraft:farmland",
  "minecraft:mycelium"
];
function fertilizer(entity) {
  const location = entity.location;
  const radius = 2;
  for (let dx = -radius; dx <= radius; dx++) {
    for (let dz = -radius; dz <= radius; dz++) {
      for (let dy = -1; dy <= 1; dy++) {
        const targetLocation = {
          x: Math.floor(location.x + dx),
          y: Math.floor(location.y + dy - 1),
          // Adjusted to check the correct height
          z: Math.floor(location.z + dz)
        };
        const block = entity.dimension.getBlock(targetLocation);
        const flowerLocation = {
          x: targetLocation.x,
          y: targetLocation.y + 1,
          z: targetLocation.z
        };
        const aboveBlock = entity.dimension.getBlock(flowerLocation);
        if (block && aboveBlock && blocksAllowToPlaceFlower.includes(block.typeId) && aboveBlock.typeId === "minecraft:air") {
          const useShortGrass = uniform(0, 100) < 70;
          const randomFlower = useShortGrass ? "minecraft:short_grass" : flowerBlocks[Math.floor(uniform(0, flowerBlocks.length - 1))];
          system11.run(() => {
            entity.dimension.setBlockType(flowerLocation, `${randomFlower}`);
          });
        }
      }
    }
  }
}
system11.afterEvents.scriptEventReceive.subscribe((event) => {
  const sourceEntity = event.sourceEntity;
  if (event.id !== "shapescape_ext:replace_flowers" || sourceEntity == void 0 || !sourceEntity.isValid() || sourceEntity.typeId != "shapescape_ext:bloomdodo_fertilizer") {
    return;
  }
  fertilizer(sourceEntity);
});

// data/system_template_esbuild/subscripts/bloomdodo.ts
import {
  system as system12
} from "@minecraft/server";
var CROPS = [
  "minecraft:wheat",
  "minecraft:carrots",
  "minecraft:potatoes",
  "minecraft:beetroot",
  "minecraft:melon_stem",
  "minecraft:pumpkin_stem",
  "minecraft:sweet_berry_bush",
  "minecraft:cocoa",
  "minecraft:pink_petals",
  "minecraft:mangrove_propagule"
];
var SAPLINGS = [
  "minecraft:acacia_sapling",
  "minecraft:birch_sapling",
  "minecraft:cherry_sapling",
  "minecraft:dark_oak_sapling",
  "minecraft:jungle_sapling",
  "minecraft:oak_sapling",
  "minecraft:pale_oak_sapling",
  "minecraft:spruce_sapling"
];
var VERTICAL_PLANTS_UP = [
  "minecraft:reeds",
  "minecraft:bamboo_sapling",
  "minecraft:bamboo",
  "minecraft:kelp",
  "minecraft:twisting_vines"
];
var GROW_FRUITS = ["minecraft:cave_vines"];
var VERTICAL_PLANTS_DOWN = ["minecraft:weeping_vines"];
system12.afterEvents.scriptEventReceive.subscribe((event) => {
  const sourceEntity = event.sourceEntity;
  if (event.id !== "shapescape_ext:growth_boost" || sourceEntity == void 0 || !sourceEntity.isValid() || sourceEntity.typeId != "shapescape_ext:bloomdodo") {
    return;
  }
  sourceEntity.playAnimation("animation.shapescape_ext.bloomdodo.shake_layer");
  growth_boost(sourceEntity);
  system12.runInterval(() => {
    if (!sourceEntity.isValid())
      return;
    try {
      sourceEntity.runCommandAsync(
        `event entity @s shapescape_ext:check_distance_to_player`
      );
    } catch {
    }
  }, 20 * 5);
});
function growth_boost(entity) {
  const location = entity.location;
  const dimension = entity.dimension;
  const block = entity.dimension.getBlock(location);
  const locationsToGrow = [];
  if (!block)
    return;
  locationsToGrow.push(block.location);
  locationsToGrow.push(block.north(1)?.location);
  locationsToGrow.push(block.south(1)?.location);
  locationsToGrow.push(block.north(1)?.east(1)?.location);
  locationsToGrow.push(block.north(1)?.west(1)?.location);
  locationsToGrow.push(block.south(1)?.east(1)?.location);
  locationsToGrow.push(block.south(1)?.west(1)?.location);
  locationsToGrow.push(block.east(1)?.location);
  locationsToGrow.push(block.west(1)?.location);
  locationsToGrow.push(block.above(1)?.location);
  locationsToGrow.push(block.above(1)?.north(1)?.location);
  locationsToGrow.push(block.above(1)?.south(1)?.location);
  locationsToGrow.push(block.above(1)?.north(1)?.east(1)?.location);
  locationsToGrow.push(block.above(1)?.north(1)?.west(1)?.location);
  locationsToGrow.push(block.above(1)?.south(1)?.east(1)?.location);
  locationsToGrow.push(block.above(1)?.south(1)?.west(1)?.location);
  locationsToGrow.push(block.above(1)?.east(1)?.location);
  locationsToGrow.push(block.above(1)?.west(1)?.location);
  locationsToGrow.push(block.below(1)?.location);
  locationsToGrow.push(block.below(1)?.north(1)?.location);
  locationsToGrow.push(block.below(1)?.south(1)?.location);
  locationsToGrow.push(block.below(1)?.north(1)?.east(1)?.location);
  locationsToGrow.push(block.below(1)?.north(1)?.west(1)?.location);
  locationsToGrow.push(block.below(1)?.south(1)?.east(1)?.location);
  locationsToGrow.push(block.below(1)?.south(1)?.west(1)?.location);
  locationsToGrow.push(block.below(1)?.east(1)?.location);
  locationsToGrow.push(block.below(1)?.west(1)?.location);
  system12.run(() => {
    for (const location2 of locationsToGrow) {
      if (!location2)
        continue;
      let block2;
      try {
        block2 = dimension.getBlock(location2);
      } catch {
      }
      if (!block2)
        continue;
      if (CROPS.includes(block2.typeId)) {
        try {
          growVanillaCrops(block2);
        } catch {
        }
        continue;
      }
      if (SAPLINGS.includes(block2.typeId)) {
        growVanillaSaplings(block2);
        continue;
      }
      if (VERTICAL_PLANTS_UP.includes(block2.typeId)) {
        growVerticalPlantsUp(block2);
        continue;
      }
      if (VERTICAL_PLANTS_DOWN.includes(block2.typeId)) {
        growVerticalPlantsDown(block2);
        continue;
      }
      if (GROW_FRUITS.includes(block2.typeId)) {
        growFruits(block2);
        continue;
      }
      if (block2.typeId.includes("dripleaf") && block2.typeId.includes("minecraft:")) {
        dripleaf(block2);
        continue;
      }
      if (block2.typeId.includes("minecraft:dirt_with_roots")) {
        rootedDirt(block2);
        continue;
      }
      if (block2.typeId.includes("minecraft:mangrove_leaves")) {
        mangroveLeaves(block2);
        continue;
      }
      if (block2.typeId.includes("minecraft:torchflower") || block2.typeId.includes("minecraft:pitcher")) {
        snifferPlants(block2);
        continue;
      }
    }
  });
}
function snifferPlants(block) {
  const dimension = block.dimension;
  const { x, y, z } = block.location;
  const permutations = block.permutation.getAllStates();
  for (const permutation of Object.keys(permutations)) {
    if (permutation !== "growth")
      continue;
    const oldvalue = block.permutation.getState(permutation);
    let newPermutation;
    newPermutation = block.permutation.withState(permutation, oldvalue + 1);
    block.dimension.setBlockPermutation(block.location, newPermutation);
    if (block.permutation.getState(permutation) === 0) {
      newPermutation = block.permutation.withState(permutation, oldvalue);
      block.dimension.setBlockPermutation(block.location, newPermutation);
    } else if (oldvalue + 1 > 1 && block.typeId.includes("torchflower")) {
      block.setType("minecraft:torchflower");
    } else if (oldvalue + 1 > 2 && block.typeId.includes("pitcher") && block.permutation.getState("upper_block_bit") === false) {
      const blockAbove = dimension.getBlock({ x, y: y + 1, z });
      if (!blockAbove)
        return;
      if (blockAbove.isAir) {
        blockAbove.setType("minecraft:pitcher_crop");
        blockAbove.setPermutation(
          blockAbove.permutation.withState("upper_block_bit", true)
        );
        blockAbove.setPermutation(
          blockAbove.permutation.withState("growth", 2)
        );
      }
    }
    VFX(block);
  }
}
function rootedDirt(block) {
  const dimension = block.dimension;
  const { x, y, z } = block.location;
  try {
    const blockAbove = dimension.getBlock({ x, y: y + 1, z });
    const blockBelow = dimension.getBlock({ x, y: y - 1, z });
    if (!blockBelow || !blockAbove)
      return;
    VFX(blockAbove);
    if (blockBelow.isAir) {
      blockBelow.setType("minecraft:hanging_roots");
    }
  } catch {
  }
}
function mangroveLeaves(block) {
  const dimension = block.dimension;
  const { x, y, z } = block.location;
  try {
    const blockAbove = dimension.getBlock({ x, y: y + 1, z });
    const blockBelow = dimension.getBlock({ x, y: y - 1, z });
    if (!blockBelow || !blockAbove)
      return;
    VFX(blockAbove);
    if (blockBelow.isAir) {
      blockBelow.setType("minecraft:mangrove_propagule");
      blockBelow.setPermutation(
        blockBelow.permutation.withState("hanging", true)
      );
    }
  } catch {
  }
}
function dripleaf(block) {
  VFX(block);
  const dimension = block.dimension;
  const { x, y, z } = block.location;
  if (block.typeId.includes("big")) {
    try {
      for (let i = 0; i < 384; i++) {
        const blockAbove = dimension.getBlock({ x, y: y + i, z });
        if (!blockAbove)
          continue;
        if (blockAbove.isAir || y + i == 320) {
          blockAbove.setType("minecraft:big_dripleaf");
          break;
        }
      }
    } catch {
    }
  } else {
    const upperBlockBit = block.permutation.getState("upper_block_bit");
    if (!upperBlockBit) {
      const blockAbove = dimension.getBlock({ x, y: y + 1, z });
      if (!blockAbove)
        return;
      block.setType("minecraft:big_dripleaf");
      blockAbove.setType("minecraft:big_dripleaf");
    }
  }
}
function growFruits(block) {
  VFX(block);
  const dimension = block.dimension;
  const { x, y, z } = block.location;
  if (block.typeId === "minecraft:cave_vines") {
    try {
      const blockBelow = dimension.getBlock({ x, y: y - 1, z });
      if (!blockBelow)
        return;
      if (blockBelow.typeId.includes("cave_vines")) {
        block.setType("minecraft:cave_vines_body_with_berries");
      } else {
        block.setType("minecraft:cave_vines_head_with_berries");
      }
    } catch {
    }
  }
}
function growVerticalPlantsDown(block) {
  VFX(block);
  const HEIGHT_TO_GROW = Math.round(16 * Math.random() / 2);
  let blockingBlockLocation;
  blockingBlockLocation = block.dimension.getBlockFromRay(
    block.location,
    { x: 0, y: -1, z: 0 },
    {
      maxDistance: HEIGHT_TO_GROW,
      includePassableBlocks: true,
      includeLiquidBlocks: true
    }
  )?.block.location;
  if (!blockingBlockLocation) {
    blockingBlockLocation = {
      x: block.location.x,
      y: block.location.y - HEIGHT_TO_GROW,
      z: block.location.z
    };
  }
  block.dimension.runCommandAsync(
    `fill ${block.x} ${block.y} ${block.z} ${blockingBlockLocation.x} ${blockingBlockLocation.y} ${blockingBlockLocation.z} ${block.typeId} [] replace air []`
  );
}
function growVerticalPlantsUp(block) {
  VFX(block);
  const dimension = block.dimension;
  const { x, y, z } = block.location;
  const HEIGHT = block.typeId.includes("bamboo") || block.typeId.includes("kelp") || block.typeId.includes("twisting_vines") ? 16 : 3;
  let currentHeight = 0;
  for (let i = 1; i < HEIGHT; i++) {
    let blockToCheck;
    try {
      blockToCheck = dimension.getBlock({ x, y: y - i, z });
    } catch {
    }
    if (!blockToCheck)
      continue;
    if (!VERTICAL_PLANTS_UP.includes(blockToCheck.typeId)) {
      currentHeight = i;
      break;
    }
    currentHeight = HEIGHT;
  }
  const HEIGHT_TO_GROW = block.typeId.includes("bamboo") || block.typeId.includes("kelp") || block.typeId.includes("twisting_vines") ? Math.round((16 - currentHeight) * Math.random()) : 3 - currentHeight;
  let blockTypeID = block.typeId.replace("_sapling", "");
  let blockingBlockLocation;
  if (blockTypeID.includes("kelp")) {
    blockingBlockLocation = block.dimension.getBlockFromRay(
      block.location,
      { x: 0, y: 1, z: 0 },
      {
        maxDistance: HEIGHT_TO_GROW,
        includePassableBlocks: false,
        includeLiquidBlocks: false
      }
    )?.block.location;
  } else {
    blockingBlockLocation = block.dimension.getBlockFromRay(
      block.location,
      { x: 0, y: 1, z: 0 },
      {
        maxDistance: HEIGHT_TO_GROW,
        includePassableBlocks: true,
        includeLiquidBlocks: false
      }
    )?.block.location;
  }
  if (!blockingBlockLocation) {
    blockingBlockLocation = {
      x: block.location.x,
      y: block.location.y + HEIGHT_TO_GROW,
      z: block.location.z
    };
  }
  if (blockTypeID.includes("kelp")) {
    block.dimension.runCommandAsync(
      `fill ${block.x} ${block.y} ${block.z} ${blockingBlockLocation.x} ${blockingBlockLocation.y} ${blockingBlockLocation.z} ${blockTypeID} [] replace water []`
    );
    block.dimension.runCommandAsync(
      `fill ${block.x} ${block.y} ${block.z} ${blockingBlockLocation.x} ${blockingBlockLocation.y} ${blockingBlockLocation.z} ${blockTypeID} [] replace flowing_water []`
    );
  } else {
    block.dimension.runCommandAsync(
      `fill ${block.x} ${block.y} ${block.z} ${blockingBlockLocation.x} ${blockingBlockLocation.y} ${blockingBlockLocation.z} ${blockTypeID} [] replace air []`
    );
  }
}
function growVanillaCrops(block) {
  const permutations = block.permutation.getAllStates();
  for (const permutation of Object.keys(permutations)) {
    if (permutation !== "growth" && permutation !== "age" && permutation !== "propagule_stage")
      continue;
    const oldvalue = block.permutation.getState(permutation);
    let newPermutation;
    if (block.typeId === "minecraft:pink_petals" && oldvalue > 2) {
    } else {
      newPermutation = block.permutation.withState(permutation, oldvalue + 1);
      block.dimension.setBlockPermutation(block.location, newPermutation);
      if (block.permutation.getState(permutation) === 0) {
        newPermutation = block.permutation.withState(permutation, oldvalue);
        block.dimension.setBlockPermutation(block.location, newPermutation);
      }
    }
    VFX(block);
  }
}
function growVanillaSaplings(block) {
  const permutations = block.permutation.getAllStates();
  for (const permutation of Object.keys(permutations)) {
    if (permutation !== "age_bit")
      continue;
    let newPermutation;
    newPermutation = block.permutation.withState(permutation, true);
    block.dimension.setBlockPermutation(block.location, newPermutation);
    VFX(block);
  }
}
function VFX(block) {
  block.dimension.spawnParticle(
    "minecraft:crop_growth_emitter",
    block.center()
  );
  block.dimension.playSound("item.bone_meal.use", block.center());
}

// data/system_template_esbuild/subscripts/bloomdodo_egg.ts
import { GameMode as GameMode2, world as world12 } from "@minecraft/server";
var projectileType = "shapescape_ext:bloomdodo_egg_item";
function shootEgg(player) {
  player.playSound("mob.snowgolem.shoot", { volume: 1, pitch: 0.8 });
  if (player.getGameMode() !== GameMode2.creative) {
    player.runCommand(`/clear @s shapescape_ext:bloomdodo_egg_item 0 1`);
  }
  const playerViewDirection = Vec3.from(player.getViewDirection());
  const spawnLocation = playerViewDirection.multiply(1.25).add(player.getHeadLocation());
  const bloomdodoEgg = player.dimension.spawnEntity(
    "shapescape_ext:bloomdodo_egg_item",
    spawnLocation
  );
  bloomdodoEgg.applyImpulse(playerViewDirection.multiply(1.75));
}
world12.afterEvents.itemUse.subscribe((event) => {
  let player = event.source;
  let item = event.itemStack;
  if (item.typeId === projectileType) {
    shootEgg(player);
  }
});

// data/system_template_esbuild/subscripts/bloomdodo_eating.ts
import { world as world13, system as system13 } from "@minecraft/server";
var TAG3 = "shapescape_ext_bloomdodo_eating";
world13.afterEvents.playerInteractWithEntity.subscribe((event) => {
  const player = event.player;
  const itemStack = event.beforeItemStack;
  const entity = event.target;
  if (!itemStack || !player || !entity || entity.typeId !== "shapescape_ext:bloomdodo" || itemStack.typeId !== "minecraft:wildflowers")
    return;
  const baby = entity.getComponent(
    "minecraft:is_baby"
  );
  if (!entity.hasTag(TAG3)) {
    entity.addTag(TAG3);
    if (baby) {
      entity.playAnimation(
        "animation.shapescape_ext.bloomdodo_baby.chewing_layer",
        {
          blendOutTime: 0.2
        }
      );
    } else {
      entity.playAnimation("animation.shapescape_ext.bloomdodo.chewing_layer", {
        blendOutTime: 0.2
      });
    }
    system13.runTimeout(() => {
      entity.removeTag(TAG3);
    }, 20 * 1.2);
  }
});

// data/system_template_esbuild/subscripts/carnotaurus.ts
import {
  system as system14,
  world as world14,
  BlockVolume as BlockVolume2,
  GameMode as GameMode3
} from "@minecraft/server";
Polyfill.installPlayer();
var BLOCKS_TO_EXCLUDE = /* @__PURE__ */ new Set([
  "minecraft:light_block",
  "minecraft:barrier",
  "minecraft:border_block",
  "minecraft:water",
  "minecraft:flowing_water",
  "minecraft:lava",
  "minecraft:flowing_lava"
]);
var BLOCKS_TO_EXCLUDE_DESTROY = /* @__PURE__ */ new Set([
  "minecraft:bedrock",
  "minecraft:command_block",
  "minecraft:light_block",
  "minecraft:structure_block",
  "minecraft:structure_void",
  "minecraft:chain_command_block",
  "minecraft:repeating_command_block",
  "minecraft:barrier",
  "minecraft:border_block",
  "minecraft:jigsaw",
  "minecraft:allow",
  "minecraft:deny",
  "minecraft:end_portal_frame",
  "minecraft:reinforced_deepslate",
  "minecraft:water",
  "minecraft:flowing_water",
  "minecraft:lava",
  "minecraft:flowing_lava",
  "shapescape_ext:thorncrest_fence_bottom",
  "shapescape_ext:thorncrest_fence_top",
  "shapescape_ext:thorncrest_fence_stone_bottom",
  "shapescape_ext:thorncrest_fence_stone_top",
  "shapescape_ext:thorncrest_gate",
  "shapescape_ext:thorncrest_gate_extension",
  "shapescape_ext:thorncrest_gate_stone",
  "shapescape_ext:thorncrest_gate_stone_extension"
]);
system14.afterEvents.scriptEventReceive.subscribe((event) => {
  const message = event.message;
  const messageID = event.id;
  const entity = event.sourceEntity;
  if (entity && messageID === "shapescape_ext:carnotaurus" && message === "charge") {
    entity.triggerEvent("shapescape_ext:charge");
    charge(entity);
  }
});
world14.afterEvents.entityHitEntity.subscribe((event) => {
  const { damagingEntity, hitEntity } = event;
  if (damagingEntity.typeId === "shapescape_ext:carnotaurus") {
    hitEntity.setOnFire(5, true);
  }
});
function charge(damagerEntity) {
  const dimension = damagerEntity.dimension;
  const target = dimension.getEntities({
    type: "minecraft:player",
    excludeGameModes: [GameMode3.creative, GameMode3.spectator],
    location: damagerEntity.location,
    maxDistance: 20,
    closest: 1
  })[0];
  if (!target) {
    damagerEntity.triggerEvent("shapescape_ext:stroll");
    return;
  }
  const targetLocation = target.location;
  damagerEntity.teleport(damagerEntity.location, {
    facingLocation: targetLocation
  });
  const rotationTowardsTarget = damagerEntity.getRotation();
  let targetLocationDirection = Vec3.from(target.location).subtract(damagerEntity.location).normalize();
  targetLocationDirection = targetLocationDirection.setY(
    clamp(targetLocationDirection.y, -0.05, 0.05)
  );
  let runIntervalID = system14.runInterval(() => {
    if (!damagerEntity.isValid() || !target.isValid()) {
      return;
    }
    let volume = new BlockVolume2(
      {
        x: damagerEntity.location.x - 1,
        y: damagerEntity.location.y + 1.5,
        z: damagerEntity.location.z - 1
      },
      {
        x: damagerEntity.location.x + 1,
        y: damagerEntity.location.y + 3,
        z: damagerEntity.location.z + 1
      }
    );
    let blocksToCheck = damagerEntity.dimension.getBlocks(
      volume,
      {
        excludeTypes: Array.from(BLOCKS_TO_EXCLUDE)
      },
      true
    ).getBlockLocationIterator();
    for (const location of blocksToCheck) {
      let block;
      try {
        block = damagerEntity.dimension.getBlock(location);
      } catch {
        continue;
      }
      if (block === void 0 || block.isAir || block.isLiquid) {
        continue;
      }
      damagerEntity.triggerEvent("shapescape_ext:stun");
      damagerEntity.dimension.playSound(
        `shapescape_ext.carnotaurus.charge_impact`,
        damagerEntity.location,
        {
          pitch: 0.8,
          volume: 2.5
        }
      );
      let volumeToDestroy = new BlockVolume2(
        {
          x: damagerEntity.location.x - 3,
          y: damagerEntity.location.y,
          z: damagerEntity.location.z - 3
        },
        {
          x: damagerEntity.location.x + 3,
          y: damagerEntity.location.y + 4,
          z: damagerEntity.location.z + 3
        }
      );
      let blocksToDestroy = damagerEntity.dimension.getBlocks(
        volumeToDestroy,
        {
          excludeTypes: Array.from(BLOCKS_TO_EXCLUDE_DESTROY)
        },
        true
      ).getBlockLocationIterator();
      for (const locationToDestroy of blocksToDestroy) {
        let blockToDestroy;
        try {
          blockToDestroy = damagerEntity.dimension.getBlock(locationToDestroy);
        } catch {
          continue;
        }
        if (blockToDestroy === void 0 || blockToDestroy.isAir || blockToDestroy.isLiquid) {
          continue;
        }
        breakBlock(damagerEntity, blockToDestroy, 1);
      }
      system14.runTimeout(() => {
        if (!damagerEntity.isValid())
          return;
        damagerEntity.triggerEvent("shapescape_ext:stroll");
      }, 100);
      system14.clearRun(runIntervalID);
      return;
    }
    let airBelow = 0;
    for (let i = 0; i < 3; i++) {
      if (damagerEntity.dimension.getBlock({
        x: damagerEntity.location.x,
        y: damagerEntity.location.y - i,
        z: damagerEntity.location.z
      })?.isAir) {
        airBelow = i;
      } else {
        break;
      }
    }
    let tpLocation = Vec3.from(damagerEntity.location).add(
      targetLocationDirection
    );
    if (!damagerEntity)
      return;
    damagerEntity.tryTeleport(
      {
        x: tpLocation.x,
        y: tpLocation.y - airBelow / 3,
        z: tpLocation.z
      },
      {
        rotation: rotationTowardsTarget
      }
    );
    if (system14.currentTick % 5 === 0) {
      const affectedEntities = dimension.getEntities({
        location: damagerEntity.location,
        maxDistance: 4,
        excludeTypes: [
          "shapescape_ext:carnotaurus",
          "minecraft:item",
          "minecraft:falling_block",
          "minecraft:experience_orb"
        ],
        excludeFamilies: ["big", "huge"]
      });
      for (const affectedEntity of affectedEntities) {
        if (affectedEntity === void 0)
          continue;
        affectedEntity.applyDamage(5);
        affectedEntity.applyImpulse(
          Vec3.from(damagerEntity.getViewDirection()).setY(0.5).multiply(0.75)
        );
      }
    }
  }, 1);
  system14.runTimeout(() => {
    if (damagerEntity.getProperty("shapescape_ext:state") === "stun")
      return;
    system14.clearRun(runIntervalID);
    if (!damagerEntity.isValid())
      return;
    damagerEntity.triggerEvent("shapescape_ext:stroll");
  }, 30);
}
function breakBlock(entity, block, keepItemChance) {
  if (Math.random() < keepItemChance) {
    const location = block.location;
    entity.runCommand(
      `/setblock ${location.x} ${location.y} ${location.z} air destroy`
    );
  } else {
    block.setType("minecraft:air");
  }
}
function clamp(value, min, max) {
  return Math.max(min, Math.min(max, value));
}

// data/system_template_esbuild/subscripts/nest.ts
import {
  system as system15,
  world as world15
} from "@minecraft/server";
var COLOR = [
  "black",
  "brown",
  "blue",
  "cyan",
  "gray",
  "green",
  "light_blue",
  "light_gray",
  "lime",
  "magenta",
  "orange",
  "pink",
  "purple",
  "red",
  "white",
  "yellow"
];
var DEBUG = false;
var EGG_TIMER_INTERVAL = 5;
var DINOSAURS = [{ "identifier": "skyreach", "display_name": "Skyreach", "lay_eggs": true, "nest_geometry": "common", "nest_texture": "common", "warm_nest_geometry": "common", "warm_nest_texture": "common", "egg_respawn_interval": 120, "egg_hatch_time": 600, "num_of_dinos": 1, "step_size": { "controlled_value": 1.5, "base_value": 1.5, "jump_prevented_value": 1.5 }, "custom_hit_test_adult": { "width": 3.8, "height": 5, "pivot": [0, 2.5, 0] }, "require_tame": true, "breed_cooldown": 60, "breed_items": ["minecraft:acacia_leaves", "minecraft:azalea_leaves", "minecraft:azalea_leaves_flowered", "minecraft:birch_leaves", "minecraft:cherry_leaves", "minecraft:dark_oak_leaves", "minecraft:jungle_leaves", "minecraft:mangrove_leaves", "minecraft:pale_oak_leaves", "minecraft:spruce_leaves"], "breeding_priority": 1, "baby_scale": 1, "baby_panic": { "priority": 0, "speed_multiplier": 2.5 }, "custom_hit_test_baby": { "width": 1.9, "height": 3.5, "pivot": [0, 1.75, 0] }, "growing_time": 600, "feed_items": ["minecraft:acacia_leaves", "minecraft:azalea_leaves", "minecraft:azalea_leaves_flowered", "minecraft:birch_leaves", "minecraft:cherry_leaves", "minecraft:dark_oak_leaves", "minecraft:jungle_leaves", "minecraft:mangrove_leaves", "minecraft:pale_oak_leaves", "minecraft:spruce_leaves"], "experience_reward": { "on_bred": "Math.Random(3,7)", "on_death": "query.last_hit_by_player ? Math.Random(10,15) : 0" }, "owner_hurt_by_target_priority": 1, "owner_hurt_target_priority": 2, "stay_while_sitting_priority": 3, "follow_owner": { "speed_multiplier": 2.5, "priority": 3, "start_distance": 8, "stop_distance": 4 }, "leashable": { "soft_distance": 4, "hard_distance": 6, "max_distance": 10 }, "healable_items": [{ "item": "acacia_leaves", "heal_amount": 5 }, { "item": "azalea_leaves", "heal_amount": 5 }, { "item": "azalea_leaves_flowered", "heal_amount": 5 }, { "item": "birch_leaves", "heal_amount": 5 }, { "item": "cherry_leaves", "heal_amount": 5 }, { "item": "dark_oak_leaves", "heal_amount": 5 }, { "item": "jungle_leaves", "heal_amount": 5 }, { "item": "mangrove_leaves", "heal_amount": 5 }, { "item": "pale_oak_leaves", "heal_amount": 5 }, { "item": "spruce_leaves", "heal_amount": 5 }], "tameable_probability": 0.2, "tempt_items": ["minecraft:acacia_leaves", "minecraft:azalea_leaves", "minecraft:azalea_leaves_flowered", "minecraft:birch_leaves", "minecraft:cherry_leaves", "minecraft:dark_oak_leaves", "minecraft:jungle_leaves", "minecraft:mangrove_leaves", "minecraft:pale_oak_leaves", "minecraft:spruce_leaves"] }, { "identifier": "venomfang", "display_name": "Venomfang", "lay_eggs": true, "nest_geometry": "common", "nest_texture": "common", "warm_nest_geometry": "common", "warm_nest_texture": "common", "egg_respawn_interval": 120, "egg_hatch_time": 600, "num_of_dinos": 1, "step_size": { "controlled_value": 1, "base_value": 1, "jump_prevented_value": 1 }, "custom_hit_test_adult": { "width": 1.9, "height": 2.5, "pivot": [0, 1.25, 0] }, "require_tame": false, "breed_cooldown": 0, "breed_items": ["minecraft:echo_shard", "minecraft:sculk_vein"], "breeding_priority": 4, "custom_hit_test_baby": { "width": 1.9, "height": 1.6, "pivot": [0, 0.8, 0] }, "baby_scale": 1, "baby_panic": { "priority": 0, "speed_multiplier": 1.75 }, "growing_time": 600, "feed_items": ["minecraft:echo_shard", "minecraft:sculk_vein"], "experience_reward": { "on_bred": "Math.Random(3,7)", "on_death": "query.last_hit_by_player ? Math.Random(5,10) : 0" }, "owner_hurt_by_target_priority": 1, "owner_hurt_target_priority": 2, "stay_while_sitting_priority": 3, "follow_owner": { "speed_multiplier": 1.75, "priority": 3, "start_distance": 8, "stop_distance": 4 }, "leashable": { "soft_distance": 4, "hard_distance": 6, "max_distance": 10 }, "healable_items": [{ "item": "minecraft:echo_shard", "heal_amount": 5 }, { "item": "minecraft:sculk_vein", "heal_amount": 5 }], "tameable_probability": 0, "tempt_items": [] }, { "identifier": "wooly_mammoth", "display_name": "Mammosk", "lay_eggs": false, "nest_geometry": "common", "nest_texture": "common", "warm_nest_geometry": "common", "warm_nest_texture": "common", "egg_respawn_interval": 120, "egg_hatch_time": 600, "num_of_dinos": 1, "step_size": { "controlled_value": 1.5, "base_value": 1.5, "jump_prevented_value": 1.5 }, "custom_hit_test_adult": { "width": 3, "height": 3.6, "pivot": [0, 1.8, 0] }, "require_tame": true, "breed_cooldown": 60, "breed_items": ["minecraft:hay_block"], "breeding_priority": 1, "baby_scale": 1, "baby_panic": { "priority": 0, "speed_multiplier": 2 }, "custom_hit_test_baby": { "width": 1.5, "height": 2, "pivot": [0, 1, 0] }, "growing_time": 600, "feed_items": ["minecraft:hay_block"], "experience_reward": { "on_bred": "Math.Random(3,7)", "on_death": "query.last_hit_by_player ? Math.Random(10,15) : 0" }, "owner_hurt_by_target_priority": 1, "owner_hurt_target_priority": 2, "stay_while_sitting_priority": 3, "follow_owner": { "speed_multiplier": 2, "priority": 3, "start_distance": 8, "stop_distance": 4 }, "leashable": { "soft_distance": 4, "hard_distance": 6, "max_distance": 10 }, "healable_items": [{ "item": "minecraft:wheat", "heal_amount": 2 }, { "item": "minecraft:hay_block", "heal_amount": 5 }], "tameable_probability": 0.2, "tempt_items": ["minecraft:hay_block"] }, { "identifier": "bloomdodo", "display_name": "Bloomdodo", "lay_eggs": false, "nest_geometry": "common", "nest_texture": "common", "warm_nest_geometry": "common", "warm_nest_texture": "common", "egg_respawn_interval": 120, "egg_hatch_time": 600, "num_of_dinos": 1, "step_size": { "controlled_value": 1.5, "base_value": 1.5, "jump_prevented_value": 1.5 }, "custom_hit_test_adult": { "width": 1.2, "height": 1.5, "pivot": [0, 0.75, 0] }, "require_tame": true, "breed_cooldown": 60, "breed_items": ["minecraft:wildflowers"], "breeding_priority": 1, "baby_scale": 1, "baby_panic": { "priority": 0, "speed_multiplier": 1.6 }, "custom_hit_test_baby": { "width": 1, "height": 1, "pivot": [0, 0.5, 0] }, "growing_time": 600, "feed_items": ["minecraft:wildflowers"], "experience_reward": { "on_bred": "Math.Random(3,7)", "on_death": "query.last_hit_by_player ? Math.Random(3,5) : 0" }, "owner_hurt_by_target_priority": 1, "owner_hurt_target_priority": 2, "stay_while_sitting_priority": 3, "follow_owner": { "speed_multiplier": 1.6, "priority": 3, "start_distance": 8, "stop_distance": 4 }, "leashable": { "soft_distance": 4, "hard_distance": 6, "max_distance": 10 }, "healable_items": [{ "item": "minecraft:wildflowers", "heal_amount": 5 }], "tameable_probability": 0.2, "tempt_items": ["minecraft:wildflowers"] }, { "identifier": "grumble", "display_name": "Grumble", "lay_eggs": true, "nest_geometry": "common", "nest_texture": "common", "warm_nest_geometry": "common", "warm_nest_texture": "common", "egg_respawn_interval": 120, "egg_hatch_time": 600, "num_of_dinos": 1, "step_size": { "controlled_value": 1.5, "base_value": 1.5, "jump_prevented_value": 1.5 }, "custom_hit_test_adult": { "width": 3.5, "height": 4.5, "pivot": [0, 2.25, 0] }, "require_tame": true, "breed_cooldown": 0, "breed_items": ["chicken", "cooked_chicken", "beef", "cooked_beef", "muttonRaw", "muttonCooked", "porkchop", "cooked_porkchop", "rotten_flesh"], "breeding_priority": 4, "baby_scale": 1, "baby_panic": { "priority": 0, "speed_multiplier": 2 }, "custom_hit_test_baby": { "width": 1.75, "height": 2, "pivot": [0, 1, 0] }, "growing_time": 600, "feed_items": ["chicken", "cooked_chicken", "beef", "cooked_beef", "muttonRaw", "muttonCooked", "porkchop", "cooked_porkchop", "rotten_flesh"], "experience_reward": { "on_bred": "Math.Random(3,7)", "on_death": "query.last_hit_by_player ? Math.Random(15,20) : 0" }, "owner_hurt_by_target_priority": 1, "owner_hurt_target_priority": 2, "stay_while_sitting_priority": 3, "follow_owner": { "speed_multiplier": 2, "priority": 3, "start_distance": 8, "stop_distance": 4 }, "leashable": { "soft_distance": 4, "hard_distance": 6, "max_distance": 10 }, "healable_items": [{ "item": "porkchop", "heal_amount": 6 }, { "item": "cooked_porkchop", "heal_amount": 16 }, { "item": "beef", "heal_amount": 6 }, { "item": "cooked_beef", "heal_amount": 16 }, { "item": "chicken", "heal_amount": 4 }, { "item": "cooked_chicken", "heal_amount": 12 }, { "item": "muttonRaw", "heal_amount": 4 }, { "item": "muttonCooked", "heal_amount": 12 }, { "item": "rotten_flesh", "heal_amount": 8 }, { "item": "rabbit", "heal_amount": 6 }], "tameable_probability": 0, "tempt_items": [] }, { "identifier": "wooly_rhino", "display_name": "Frosthorn", "lay_eggs": false, "nest_geometry": "common", "nest_texture": "common", "warm_nest_geometry": "common", "warm_nest_texture": "common", "egg_respawn_interval": 120, "egg_hatch_time": 600, "num_of_dinos": 1, "step_size": { "controlled_value": 1.5, "base_value": 1.5, "jump_prevented_value": 1.5 }, "custom_hit_test_adult": { "width": 3.5, "height": 3.25, "pivot": [0, 1.625, 0] }, "require_tame": true, "breed_cooldown": 60, "breed_items": ["shapescape_ext:frozen_carrot"], "breeding_priority": 1, "baby_scale": 1, "baby_panic": { "priority": 0, "speed_multiplier": 1 }, "custom_hit_test_baby": { "width": 2, "height": 1.8, "pivot": [0, 0.9, 0] }, "growing_time": 600, "feed_items": ["shapescape_ext:frozen_carrot"], "experience_reward": { "on_bred": "Math.Random(3,7)", "on_death": "query.last_hit_by_player ? Math.Random(10,15) : 0" }, "owner_hurt_by_target_priority": 1, "owner_hurt_target_priority": 2, "stay_while_sitting_priority": 3, "follow_owner": { "speed_multiplier": 1, "priority": 3, "start_distance": 8, "stop_distance": 4 }, "leashable": { "soft_distance": 4, "hard_distance": 6, "max_distance": 10 }, "healable_items": [{ "item": "shapescape_ext:frozen_carrot", "heal_amount": 5 }], "tameable_probability": 0.2, "tempt_items": ["shapescape_ext:frozen_carrot"] }, { "identifier": "stegosaurus", "display_name": "Spikeback", "lay_eggs": true, "nest_geometry": "common", "nest_texture": "common", "warm_nest_geometry": "common", "warm_nest_texture": "common", "egg_respawn_interval": 120, "egg_hatch_time": 600, "num_of_dinos": 1, "step_size": { "controlled_value": 1.5625, "base_value": 1.5625, "jump_prevented_value": 1.5 }, "custom_hit_test_adult": { "width": 3, "height": 3.5, "pivot": [0, 1.75, 0] }, "require_tame": true, "breed_cooldown": 60, "breed_items": ["minecraft:apple"], "breeding_priority": 1, "baby_scale": 1, "baby_panic": { "priority": 0, "speed_multiplier": 2 }, "custom_hit_test_baby": { "width": 1.75, "height": 1.75, "pivot": [0, 0.875, 0] }, "growing_time": 600, "feed_items": ["minecraft:apple"], "experience_reward": { "on_bred": "Math.Random(3,7)", "on_death": "query.last_hit_by_player ? Math.Random(10,15) : 0" }, "owner_hurt_by_target_priority": 1, "owner_hurt_target_priority": 2, "stay_while_sitting_priority": 3, "follow_owner": { "speed_multiplier": 2, "priority": 3, "start_distance": 8, "stop_distance": 4 }, "leashable": { "soft_distance": 4, "hard_distance": 6, "max_distance": 10 }, "healable_items": [{ "item": "apple", "heal_amount": 5 }], "tameable_probability": 0.2, "tempt_items": ["minecraft:apple"] }, { "identifier": "sabertooth_tiger", "display_name": "Sabertooth", "lay_eggs": false, "nest_geometry": "common", "nest_texture": "common", "warm_nest_geometry": "common", "warm_nest_texture": "common", "egg_respawn_interval": 120, "egg_hatch_time": 600, "num_of_dinos": 1, "step_size": { "controlled_value": 1.5, "base_value": 1.5, "jump_prevented_value": 1.5 }, "custom_hit_test_adult": { "width": 1.5, "height": 1.5, "pivot": [0, 0.75, 0] }, "require_tame": true, "breed_cooldown": 60, "breed_items": ["chicken", "cooked_chicken", "beef", "cooked_beef", "muttonRaw", "muttonCooked", "porkchop", "cooked_porkchop", "rabbit", "cooked_rabbit", "rotten_flesh"], "breeding_priority": 1, "baby_scale": 1, "baby_panic": { "priority": 0, "speed_multiplier": 1.75 }, "custom_hit_test_baby": { "width": 1.05, "height": 1, "pivot": [0, 0.5, 0] }, "growing_time": 600, "feed_items": ["chicken", "cooked_chicken", "beef", "cooked_beef", "muttonRaw", "muttonCooked", "porkchop", "cooked_porkchop", "rabbit", "cooked_rabbit", "rotten_flesh"], "experience_reward": { "on_bred": "Math.Random(3,7)", "on_death": "query.last_hit_by_player ? Math.Random(7,11) : 0" }, "owner_hurt_by_target_priority": 1, "owner_hurt_target_priority": 2, "stay_while_sitting_priority": 3, "follow_owner": { "speed_multiplier": 1, "priority": 3, "start_distance": 25, "stop_distance": 8 }, "leashable": { "soft_distance": 4, "hard_distance": 6, "max_distance": 10 }, "healable_items": [{ "item": "porkchop", "heal_amount": 6 }, { "item": "cooked_porkchop", "heal_amount": 16 }, { "item": "fish", "heal_amount": 4 }, { "item": "salmon", "heal_amount": 4 }, { "item": "clownfish", "heal_amount": 2 }, { "item": "pufferfish", "heal_amount": 2 }, { "item": "cooked_fish", "heal_amount": 10 }, { "item": "cooked_salmon", "heal_amount": 12 }, { "item": "beef", "heal_amount": 6 }, { "item": "cooked_beef", "heal_amount": 16 }, { "item": "chicken", "heal_amount": 4 }, { "item": "cooked_chicken", "heal_amount": 12 }, { "item": "muttonRaw", "heal_amount": 4 }, { "item": "muttonCooked", "heal_amount": 12 }, { "item": "rotten_flesh", "heal_amount": 8 }, { "item": "rabbit", "heal_amount": 6 }, { "item": "cooked_rabbit", "heal_amount": 10 }, { "item": "rabbit_stew", "heal_amount": 20 }], "tameable_probability": 0.2, "tempt_items": ["chicken", "cooked_chicken", "beef", "cooked_beef", "muttonRaw", "muttonCooked", "porkchop", "cooked_porkchop", "rabbit", "cooked_rabbit", "rotten_flesh"] }, { "identifier": "void_runner", "display_name": "Void Runner", "lay_eggs": true, "nest_geometry": "common", "nest_texture": "common", "warm_nest_geometry": "common", "warm_nest_texture": "common", "egg_respawn_interval": 120, "egg_hatch_time": 600, "num_of_dinos": 1, "step_size": { "controlled_value": 1.5, "base_value": 1.5, "jump_prevented_value": 1.5 }, "custom_hit_test_adult": { "width": 1.5, "height": 2, "pivot": [0, 1.2, 0] }, "require_tame": true, "breed_cooldown": 60, "breed_items": ["minecraft:chorus_fruit"], "breeding_priority": 1, "baby_scale": 1, "baby_panic": { "priority": 0, "speed_multiplier": 1.75 }, "custom_hit_test_baby": { "width": 0.75, "height": 1.5, "pivot": [0, 0.75, 0] }, "growing_time": 600, "feed_items": ["minecraft:chorus_fruit"], "experience_reward": { "on_bred": "Math.Random(3,7)", "on_death": "query.last_hit_by_player ? Math.Random(5,10) : 0" }, "owner_hurt_by_target_priority": 1, "owner_hurt_target_priority": 2, "stay_while_sitting_priority": 3, "follow_owner": { "speed_multiplier": 1.75, "priority": 3, "start_distance": 8, "stop_distance": 4 }, "leashable": { "soft_distance": 4, "hard_distance": 6, "max_distance": 10 }, "healable_items": [{ "item": "chorus_fruit", "heal_amount": 5 }], "tameable_probability": 0.2, "tempt_items": ["minecraft:chorus_fruit"] }, { "identifier": "void_wing", "display_name": "Ender Wing", "lay_eggs": true, "nest_geometry": "common", "nest_texture": "common", "warm_nest_geometry": "common", "warm_nest_texture": "common", "egg_respawn_interval": 120, "egg_hatch_time": 600, "num_of_dinos": 1, "step_size": { "controlled_value": 1.5, "base_value": 1.5, "jump_prevented_value": 1.5 }, "custom_hit_test_adult": { "width": 2.5, "height": 2.25, "pivot": [0, 1.125, 0] }, "require_tame": true, "breed_cooldown": 60, "breed_items": ["minecraft:chorus_fruit"], "breeding_priority": 1, "baby_scale": 1, "baby_panic": { "priority": 0, "speed_multiplier": 1 }, "custom_hit_test_baby": { "width": 1.5, "height": 1, "pivot": [0, 0.5, 0] }, "growing_time": 600, "feed_items": ["minecraft:chorus_fruit"], "experience_reward": { "on_bred": "Math.Random(3,7)", "on_death": "query.last_hit_by_player ? Math.Random(10,15) : 0" }, "owner_hurt_by_target_priority": 1, "owner_hurt_target_priority": 2, "stay_while_sitting_priority": 3, "follow_owner": { "speed_multiplier": 1, "priority": 3, "start_distance": 12, "stop_distance": 4 }, "leashable": { "soft_distance": 4, "hard_distance": 6, "max_distance": 10 }, "healable_items": [{ "item": "chorus_fruit", "heal_amount": 5 }], "tameable_probability": 0.2, "tempt_items": ["minecraft:chorus_fruit"] }, { "identifier": "thorncrest", "display_name": "Thorncrest", "lay_eggs": true, "nest_geometry": "common", "nest_texture": "common", "warm_nest_geometry": "common", "warm_nest_texture": "common", "egg_respawn_interval": 120, "egg_hatch_time": 600, "num_of_dinos": 1, "step_size": { "controlled_value": 1.5, "base_value": 1.5, "jump_prevented_value": 1.5 }, "custom_hit_test_adult": { "width": 3.5, "height": 3.5, "pivot": [0, 1.75, 0] }, "require_tame": true, "breed_cooldown": 60, "breed_items": ["shapescape_ext:thorncrest_bush_berry"], "breeding_priority": 4, "baby_scale": 1, "baby_panic": { "priority": 0, "speed_multiplier": 1.65 }, "custom_hit_test_baby": { "width": 1, "height": 1.25, "pivot": [0, 0.625, 0] }, "growing_time": 600, "feed_items": ["shapescape_ext:thorncrest_bush_berry"], "experience_reward": { "on_bred": "Math.Random(3,7)", "on_death": "query.last_hit_by_player ? Math.Random(10,15) : 0" }, "owner_hurt_by_target_priority": 1, "owner_hurt_target_priority": 2, "stay_while_sitting_priority": 3, "follow_owner": { "speed_multiplier": 1.65, "priority": 3, "start_distance": 8, "stop_distance": 4 }, "leashable": { "soft_distance": 4, "hard_distance": 6, "max_distance": 10 }, "healable_items": [{ "item": "shapescape_ext:thorncrest_bush_berry", "heal_amount": 10 }], "tameable_probability": 0.2, "tempt_items": ["shapescape_ext:thorncrest_bush_berry"] }, { "identifier": "ankylosaurus", "display_name": "Rocktail", "lay_eggs": true, "nest_geometry": "common", "nest_texture": "common", "warm_nest_geometry": "common", "warm_nest_texture": "common", "egg_respawn_interval": 120, "egg_hatch_time": 600, "num_of_dinos": 1, "step_size": { "controlled_value": 1.5, "base_value": 1.5, "jump_prevented_value": 1.5 }, "custom_hit_test_adult": { "width": 3.5, "height": 3, "pivot": [0, 1.75, 0] }, "require_tame": true, "breed_cooldown": 60, "breed_items": ["minecraft:spider_eye"], "breeding_priority": 4, "baby_scale": 1, "baby_panic": { "priority": 0, "speed_multiplier": 2.15 }, "custom_hit_test_baby": { "width": 1.75, "height": 1.5, "pivot": [0, 0.875, 0] }, "growing_time": 600, "feed_items": ["minecraft:spider_eye"], "experience_reward": { "on_bred": "Math.Random(3,7)", "on_death": "query.last_hit_by_player ? Math.Random(10,15) : 0" }, "owner_hurt_by_target_priority": 1, "owner_hurt_target_priority": 2, "stay_while_sitting_priority": 3, "follow_owner": { "speed_multiplier": 2.15, "priority": 3, "start_distance": 8, "stop_distance": 4 }, "leashable": { "soft_distance": 4, "hard_distance": 6, "max_distance": 10 }, "healable_items": [{ "item": "minecraft:spider_eye", "heal_amount": 10 }], "tameable_probability": 0.2, "tempt_items": ["minecraft:spider_eye"] }, { "identifier": "sand_runner", "display_name": "Sand Runner", "lay_eggs": true, "nest_geometry": "common", "nest_texture": "common", "warm_nest_geometry": "common", "warm_nest_texture": "common", "egg_respawn_interval": 120, "egg_hatch_time": 600, "num_of_dinos": 1, "step_size": { "controlled_value": 1.5, "base_value": 1.5, "jump_prevented_value": 1.5 }, "custom_hit_test_adult": { "width": 2, "height": 3, "pivot": [0, 1.5, 0] }, "require_tame": true, "breed_cooldown": 60, "breed_items": ["minecraft:cactus"], "breeding_priority": 1, "baby_scale": 1, "baby_panic": { "priority": 0, "speed_multiplier": 1.5 }, "custom_hit_test_baby": { "width": 1.2, "height": 1.7, "pivot": [0, 0.85, 0] }, "growing_time": 600, "feed_items": ["minecraft:cactus"], "experience_reward": { "on_bred": "Math.Random(3,7)", "on_death": "query.last_hit_by_player ? Math.Random(3,5) : 0" }, "owner_hurt_by_target_priority": 1, "owner_hurt_target_priority": 2, "stay_while_sitting_priority": 3, "follow_owner": { "speed_multiplier": 1.5, "priority": 3, "start_distance": 8, "stop_distance": 4 }, "leashable": { "soft_distance": 4, "hard_distance": 6, "max_distance": 10 }, "healable_items": [{ "item": "wheat", "heal_amount": 2 }, { "item": "sugar", "heal_amount": 1 }, { "item": "hay_block", "heal_amount": 20 }, { "item": "apple", "heal_amount": 3 }, { "item": "golden_carrot", "heal_amount": 4 }, { "item": "golden_apple", "heal_amount": 10 }, { "item": "appleEnchanted", "heal_amount": 10 }, { "item": "cactus", "heal_amount": 10 }], "tameable_probability": 0.2, "tempt_items": ["minecraft:cactus"] }, { "identifier": "carnotaurus", "display_name": "Carnoravager", "lay_eggs": false, "nest_geometry": "common", "nest_texture": "common", "warm_nest_geometry": "common", "warm_nest_texture": "common", "egg_respawn_interval": 120, "egg_hatch_time": 600, "num_of_dinos": 1, "step_size": { "controlled_value": 1.5, "base_value": 1.5, "jump_prevented_value": 1.5 }, "custom_hit_test_adult": { "width": 3.25, "height": 4, "pivot": [0, 2, 0] }, "require_tame": true, "breed_cooldown": 0, "breed_items": [], "breeding_priority": 0, "baby_scale": 1, "baby_panic": { "priority": 0, "speed_multiplier": 1 }, "custom_hit_test_baby": { "width": 1.2, "height": 1.7, "pivot": [0, 0.85, 0] }, "growing_time": 600, "feed_items": [], "experience_reward": { "on_bred": "Math.Random(3,7)", "on_death": "query.last_hit_by_player ? Math.Random(15,20) : 0" }, "owner_hurt_by_target_priority": 1, "owner_hurt_target_priority": 2, "stay_while_sitting_priority": 3, "follow_owner": { "speed_multiplier": 1, "priority": 3, "start_distance": 8, "stop_distance": 4 }, "leashable": { "soft_distance": 4, "hard_distance": 6, "max_distance": 10 }, "healable_items": [], "tameable_probability": 0, "tempt_items": [] }, { "identifier": "razor_jaw", "display_name": "Razorjaw", "lay_eggs": true, "nest_geometry": "common", "nest_texture": "common", "warm_nest_geometry": "common", "warm_nest_texture": "common", "egg_respawn_interval": 120, "egg_hatch_time": 600, "num_of_dinos": 1, "step_size": { "controlled_value": 1.5, "base_value": 1.5, "jump_prevented_value": 1.5 }, "custom_hit_test_adult": { "width": 1.5, "height": 2, "pivot": [0, 1.2, 0] }, "require_tame": true, "breed_cooldown": 60, "breed_items": ["minecraft:rabbit", "minecraft:cooked_rabbit", "minecraft:beetroot"], "breeding_priority": 1, "baby_scale": 1, "baby_panic": { "priority": 0, "speed_multiplier": 1.75 }, "custom_hit_test_baby": { "width": 0.75, "height": 1.5, "pivot": [0, 0.75, 0] }, "growing_time": 600, "feed_items": ["minecraft:rabbit", "minecraft:cooked_rabbit", "minecraft:beetroot"], "experience_reward": { "on_bred": "Math.Random(3,7)", "on_death": "query.last_hit_by_player ? Math.Random(5,10) : 0" }, "owner_hurt_by_target_priority": 1, "owner_hurt_target_priority": 2, "stay_while_sitting_priority": 3, "follow_owner": { "speed_multiplier": 1.75, "priority": 3, "start_distance": 8, "stop_distance": 4 }, "leashable": { "soft_distance": 4, "hard_distance": 6, "max_distance": 10 }, "healable_items": [{ "item": "rabbit", "heal_amount": 5 }, { "item": "cooked_rabbit", "heal_amount": 5 }, { "item": "beetroot", "heal_amount": 5 }], "tameable_probability": 0.2, "tempt_items": ["minecraft:rabbit", "minecraft:cooked_rabbit", "minecraft:beetroot"] }, { "identifier": "velociraptor_nether", "display_name": "Ashclaw", "lay_eggs": true, "nest_geometry": "common", "nest_texture": "common", "warm_nest_geometry": "common", "warm_nest_texture": "common", "egg_respawn_interval": 120, "egg_hatch_time": 600, "num_of_dinos": 1, "step_size": { "controlled_value": 1.5, "base_value": 1.5, "jump_prevented_value": 1.5 }, "custom_hit_test_adult": { "width": 1.5, "height": 2, "pivot": [0, 1.2, 0] }, "require_tame": true, "breed_cooldown": 60, "breed_items": ["chicken", "cooked_chicken", "beef", "cooked_beef", "muttonRaw", "muttonCooked", "porkchop", "cooked_porkchop", "rotten_flesh"], "breeding_priority": 1, "baby_scale": 1, "baby_panic": { "priority": 0, "speed_multiplier": 1.75 }, "custom_hit_test_baby": { "width": 0.75, "height": 1.5, "pivot": [0, 0.75, 0] }, "growing_time": 600, "feed_items": ["chicken", "cooked_chicken", "beef", "cooked_beef", "muttonRaw", "muttonCooked", "porkchop", "cooked_porkchop", "rotten_flesh"], "experience_reward": { "on_bred": "Math.Random(3,7)", "on_death": "query.last_hit_by_player ? Math.Random(5,10) : 0" }, "owner_hurt_by_target_priority": 1, "owner_hurt_target_priority": 2, "stay_while_sitting_priority": 3, "follow_owner": { "speed_multiplier": 1.75, "priority": 3, "start_distance": 8, "stop_distance": 4 }, "leashable": { "soft_distance": 4, "hard_distance": 6, "max_distance": 10 }, "healable_items": [{ "item": "chicken", "heal_amount": 5 }, { "item": "cooked_chicken", "heal_amount": 5 }, { "item": "beef", "heal_amount": 5 }, { "item": "cooked_beef", "heal_amount": 5 }, { "item": "muttonRaw", "heal_amount": 5 }, { "item": "muttonCooked", "heal_amount": 5 }, { "item": "porkchop", "heal_amount": 5 }, { "item": "cooked_porkchop", "heal_amount": 5 }, { "item": "rotten_flesh", "heal_amount": 5 }], "tameable_probability": 0, "tempt_items": [] }, { "identifier": "pterodactyl", "display_name": "Cloudclaw", "lay_eggs": true, "nest_geometry": "common", "nest_texture": "common", "warm_nest_geometry": "common", "warm_nest_texture": "common", "egg_respawn_interval": 120, "egg_hatch_time": 600, "num_of_dinos": 1, "step_size": { "controlled_value": 1.5, "base_value": 1.5, "jump_prevented_value": 1.5 }, "custom_hit_test_adult": { "width": 2.5, "height": 2.25, "pivot": [0, 1.125, 0] }, "require_tame": true, "breed_cooldown": 60, "breed_items": ["minecraft:potato"], "breeding_priority": 1, "baby_scale": 1, "baby_panic": { "priority": 0, "speed_multiplier": 1 }, "custom_hit_test_baby": { "width": 1.5, "height": 1, "pivot": [0, 0.5, 0] }, "growing_time": 600, "feed_items": ["minecraft:potato"], "experience_reward": { "on_bred": "Math.Random(3,7)", "on_death": "query.last_hit_by_player ? Math.Random(10,15) : 0" }, "owner_hurt_by_target_priority": 1, "owner_hurt_target_priority": 2, "stay_while_sitting_priority": 3, "follow_owner": { "speed_multiplier": 1, "priority": 3, "start_distance": 20, "stop_distance": 4 }, "leashable": { "soft_distance": 4, "hard_distance": 6, "max_distance": 10 }, "healable_items": [{ "item": "potato", "heal_amount": 5 }], "tameable_probability": 0.2, "tempt_items": ["minecraft:potato"] }];
world15.beforeEvents.worldInitialize.subscribe((event) => {
  event.blockComponentRegistry.registerCustomComponent(
    "shapescape_ext:nest_block",
    {
      onTick: (event2) => {
        const block = event2.block;
        const isEgg = checkForEgg(block.center(), block.dimension);
        const eggPermutation = block.permutation.getState("shapescape_ext:egg");
        if (isEgg) {
          if (!eggPermutation) {
            block.setPermutation(
              block.permutation.withState("shapescape_ext:egg", true)
            );
          }
          return;
        } else {
          const dinoData = DINOSAURS.find(
            (dino) => block.typeId.includes(dino.identifier)
          );
          if (dinoData === void 0)
            return;
          increaseTime(block, dinoData);
        }
      }
    }
  );
});
world15.beforeEvents.playerInteractWithBlock.subscribe((event) => {
  const { block, player, itemStack } = event;
  if (block.typeId.includes("shapescape") && block.typeId.includes("nest_block") && !block.typeId.includes("warm") && player && itemStack && itemStack.typeId.includes("shapescape") && itemStack.typeId.includes("furry_carpet")) {
    event.cancel = true;
    system15.run(() => {
      if (!player.isValid() || !block)
        return;
      const colorMatch = COLOR.find(
        (color) => itemStack.typeId.includes(color)
      );
      if (itemStack.typeId.includes("shapescape") && itemStack.typeId.includes("furry_carpet") && colorMatch) {
        player.runCommandAsync(
          `clear @s shapescape_ext:${colorMatch}_furry_carpet 0 1`
        );
      }
      const newBlockId = block.typeId.replace("nest_block", "warm_nest_block").replace("_fake", "");
      block.setType(newBlockId);
      player.dimension.playSound("use.cloth", player.location);
    });
  }
});
function checkForEgg(location, dimension) {
  const entities2 = dimension.getEntities({
    location: {
      x: location.x,
      y: location.y + 1,
      z: location.z
    },
    maxDistance: 1
  });
  for (const entity of entities2) {
    if (entity.typeId.includes("shapescape") && entity.typeId.includes("egg")) {
      return true;
    }
  }
  return false;
}
function increaseTime(block, dinoData) {
  if (!block)
    return;
  let eggTimerSeconds = block.permutation.getState("shapescape_ext:egg_timer_seconds");
  let eggTimerSeconds10 = block.permutation.getState("shapescape_ext:egg_timer_seconds_10");
  let eggTimerSeconds60 = block.permutation.getState("shapescape_ext:egg_timer_seconds_60");
  eggTimerSeconds = eggTimerSeconds + EGG_TIMER_INTERVAL;
  if (eggTimerSeconds >= 10) {
    eggTimerSeconds = 0;
    eggTimerSeconds10 = eggTimerSeconds10 + 1;
    if (eggTimerSeconds10 >= 6) {
      eggTimerSeconds10 = 0;
      eggTimerSeconds60 = eggTimerSeconds60 + 1;
    }
  }
  if (DEBUG) {
    world15.sendMessage("=============");
    world15.sendMessage("Seconds: " + JSON.stringify(eggTimerSeconds));
    world15.sendMessage("Seconds * 10: " + JSON.stringify(eggTimerSeconds10));
    world15.sendMessage("Seconds * 60: " + JSON.stringify(eggTimerSeconds60));
  }
  block.setPermutation(
    block.permutation.withState("shapescape_ext:egg_timer_seconds", eggTimerSeconds)
  );
  block.setPermutation(
    block.permutation.withState(
      "shapescape_ext:egg_timer_seconds_10",
      eggTimerSeconds10
    )
  );
  block.setPermutation(
    block.permutation.withState(
      "shapescape_ext:egg_timer_seconds_60",
      eggTimerSeconds60
    )
  );
  const totalTime = eggTimerSeconds + eggTimerSeconds10 * 10 + eggTimerSeconds60 * 60;
  if (totalTime >= dinoData.egg_respawn_interval) {
    block.setPermutation(
      block.permutation.withState("shapescape_ext:egg_timer_seconds", 0)
    );
    block.setPermutation(
      block.permutation.withState("shapescape_ext:egg_timer_seconds_10", 0)
    );
    block.setPermutation(
      block.permutation.withState("shapescape_ext:egg_timer_seconds_60", 0)
    );
    block.setPermutation(block.permutation.withState("shapescape_ext:egg", true));
    const egg = block.dimension.spawnEntity(
      block.typeId.replace("nest_block", "egg"),
      {
        x: block.center().x,
        y: block.center().y,
        z: block.center().z
      }
    );
    egg.triggerEvent(`shapescape_ext:naturally_spawned`);
    if (!checkForDino(dinoData.identifier, block.location, block.dimension)) {
      for (let index = 0; index < dinoData.num_of_dinos; index++) {
        block.dimension.runCommandAsync(
          `summon shapescape_ext:${dinoData.identifier} ${block.center().x} ${block.center().y} ${block.center().z}`
        );
      }
    }
  }
}
function checkForDino(typeId, location, dimension) {
  const dinos = dimension.getEntities({
    location,
    maxDistance: 30,
    type: `shapescape_ext:${typeId}`
  });
  if (dinos.length > 0) {
    for (const dino of dinos) {
      let tamedComponent = dino.getComponent("minecraft:is_tamed");
      if (tamedComponent === void 0) {
        return true;
      }
    }
  }
  return false;
}

// data/system_template_esbuild/subscripts/feature_nest.ts
import { world as world16 } from "@minecraft/server";
var nestLocations = /* @__PURE__ */ new Set();
world16.beforeEvents.worldInitialize.subscribe((event) => {
  event.blockComponentRegistry.registerCustomComponent("shapescape_ext:feature_nest_block", {
    onTick(event2) {
      const scoreboard = world16.scoreboard.getObjective("shapescape_ext_feature_nest_block");
      const block = event2.block;
      if (scoreboard !== void 0)
        return;
      if (!nestLocations.has(JSON.stringify(block.location))) {
        nestLocations.add(JSON.stringify(block.location));
        block.dimension.setBlockType(block.location, block.typeId);
        return;
      }
      if (block.typeId.includes("grumble")) {
        let grumbleSpawn = world16.getDynamicProperty("grumble_spawn");
        if (!grumbleSpawn) {
          try {
            block.dimension.setBlockType(block.location, `minecraft:air`);
          } catch {
          }
        } else {
          setNest(block);
        }
      } else {
        setNest(block);
      }
    }
  });
});
function setNest(block) {
  nestLocations.delete(JSON.stringify(block.location));
  try {
    const aboveOneLocation = block.above(1).center();
    const aboveTwoLocation = block.above(2).center();
    block.dimension.setBlockType(block.location, block.typeId.replace("feature_nest_block", "nest_block"));
    const egg = block.dimension.spawnEntity(
      block.typeId.replace("feature_nest_block", "egg").replace("nest_block", "egg"),
      {
        x: block.center().x,
        y: block.center().y + 0.5,
        z: block.center().z
      }
    );
    egg.triggerEvent(`shapescape_ext:naturally_spawned`);
    if (block.typeId.includes("void_wing")) {
      block.dimension.runCommand(
        `summon shapescape_ext:void_wing ${aboveOneLocation.x} ${aboveOneLocation.y} ${aboveOneLocation.z}`
      );
      if (Math.random() > 0.5) {
        block.dimension.runCommand(
          `summon shapescape_ext:void_wing ${aboveTwoLocation.x} ${aboveTwoLocation.y} ${aboveTwoLocation.z}`
        );
      }
    } else if (block.typeId.includes("void_runner")) {
      block.dimension.runCommand(
        `summon shapescape_ext:void_runner ${aboveOneLocation.x} ${aboveOneLocation.y} ${aboveOneLocation.z} ~~ shapescape_ext:leader`
      );
      if (Math.random() > 0.5) {
        block.dimension.runCommand(
          `summon shapescape_ext:void_runner ${aboveTwoLocation.x} ${aboveTwoLocation.y} ${aboveTwoLocation.z} ~~ shapescape_ext:follower`
        );
      }
      block.dimension.runCommand(
        `tag @e[type=shapescape_ext:void_runner, x=${aboveOneLocation.x},y=${aboveOneLocation.y},z=${aboveOneLocation.z},r=1] add shapescape_ext_INITIALIZED`
      );
      block.dimension.runCommand(
        `tag @e[type=shapescape_ext:void_runner, x=${aboveTwoLocation.x},y=${aboveTwoLocation.y},z=${aboveTwoLocation.z},r=1] add shapescape_ext_INITIALIZED`
      );
    } else if (block.typeId.includes("venomfang")) {
      block.dimension.runCommand(
        `summon shapescape_ext:venomfang ${aboveOneLocation.x} ${aboveOneLocation.y} ${aboveOneLocation.z}`
      );
      if (Math.random() > 0.5) {
        block.dimension.runCommand(
          `summon shapescape_ext:venomfang ${aboveTwoLocation.x} ${aboveTwoLocation.y} ${aboveTwoLocation.z}`
        );
      }
    } else if (block.typeId.includes("thorncrest")) {
      block.dimension.runCommand(
        `summon shapescape_ext:thorncrest ${aboveOneLocation.x} ${aboveOneLocation.y} ${aboveOneLocation.z}`
      );
      if (Math.random() > 0.5) {
        block.dimension.runCommand(
          `summon shapescape_ext:thorncrest ${aboveTwoLocation.x} ${aboveTwoLocation.y} ${aboveTwoLocation.z}`
        );
      }
    } else if (block.typeId.includes("stegosaurus")) {
      block.dimension.runCommand(
        `summon shapescape_ext:stegosaurus ${aboveOneLocation.x} ${aboveOneLocation.y} ${aboveOneLocation.z}`
      );
      if (Math.random() > 0.5) {
        block.dimension.runCommand(
          `summon shapescape_ext:stegosaurus ${aboveTwoLocation.x} ${aboveTwoLocation.y} ${aboveTwoLocation.z}`
        );
      }
    } else if (block.typeId.includes("skyreach")) {
      block.dimension.runCommand(
        `summon shapescape_ext:skyreach ${aboveOneLocation.x} ${aboveOneLocation.y} ${aboveOneLocation.z}`
      );
      if (Math.random() > 0.5) {
        block.dimension.runCommand(
          `summon shapescape_ext:skyreach ${aboveTwoLocation.x} ${aboveTwoLocation.y} ${aboveTwoLocation.z}`
        );
      }
    } else if (block.typeId.includes("ankylosaurus")) {
      block.dimension.runCommand(
        `summon shapescape_ext:ankylosaurus ${aboveOneLocation.x} ${aboveOneLocation.y} ${aboveOneLocation.z}`
      );
      if (Math.random() > 0.5) {
        block.dimension.runCommand(
          `summon shapescape_ext:ankylosaurus ${aboveTwoLocation.x} ${aboveTwoLocation.y} ${aboveTwoLocation.z}`
        );
      }
    } else if (block.typeId.includes("sand_runner")) {
      block.dimension.runCommand(
        `summon shapescape_ext:sand_runner ${aboveOneLocation.x} ${aboveOneLocation.y} ${aboveOneLocation.z}`
      );
      if (Math.random() > 0.5) {
        block.dimension.runCommand(
          `summon shapescape_ext:sand_runner ${aboveTwoLocation.x} ${aboveTwoLocation.y} ${aboveTwoLocation.z}`
        );
      }
    } else if (block.typeId.includes("grumble")) {
      block.dimension.runCommand(
        `summon shapescape_ext:grumble ${aboveOneLocation.x} ${aboveOneLocation.y} ${aboveOneLocation.z}`
      );
      if (Math.random() > 0.5) {
        block.dimension.runCommand(
          `summon shapescape_ext:grumble ${aboveTwoLocation.x} ${aboveTwoLocation.y} ${aboveTwoLocation.z}`
        );
      }
    } else if (block.typeId.includes("razor_jaw")) {
      block.dimension.runCommand(
        `summon shapescape_ext:razor_jaw ${aboveOneLocation.x} ${aboveOneLocation.y} ${aboveOneLocation.z}`
      );
      if (Math.random() > 0.5) {
        block.dimension.runCommand(
          `summon shapescape_ext:razor_jaw ${aboveTwoLocation.x} ${aboveTwoLocation.y} ${aboveTwoLocation.z}`
        );
      }
    } else if (block.typeId.includes("velociraptor_nether")) {
      block.dimension.runCommand(
        `summon shapescape_ext:velociraptor_nether ${aboveOneLocation.x} ${aboveOneLocation.y} ${aboveOneLocation.z}`
      );
      if (Math.random() > 0.5) {
        block.dimension.runCommand(
          `summon shapescape_ext:velociraptor_nether ${aboveTwoLocation.x} ${aboveTwoLocation.y} ${aboveTwoLocation.z}`
        );
      }
    }
  } catch {
  }
}

// data/system_template_esbuild/subscripts/egg.ts
import {
  system as system17,
  world as world17,
  Player as Player7,
  ItemStack,
  BlockVolume as BlockVolume3,
  TicksPerSecond as TicksPerSecond2
} from "@minecraft/server";
var HATCHING_TIME = 20 * 4.6;
world17.afterEvents.entityHitEntity.subscribe((event) => {
  const { damagingEntity, hitEntity } = event;
  if (damagingEntity instanceof Player7 && hitEntity.typeId.includes("shapescape") && hitEntity.typeId.includes("egg")) {
    const itemStack = new ItemStack(hitEntity.typeId, 1);
    hitEntity.dimension.spawnItem(itemStack, hitEntity.location);
    hitEntity.dimension.playSound("random.pop", hitEntity.location);
    hitEntity.remove();
  }
});
system17.afterEvents.scriptEventReceive.subscribe((event) => {
  const message = event.message;
  const messageID = event.id;
  const egg = event.sourceEntity;
  if (messageID.includes("shapescape") && messageID.includes("egg") && message === "hatch" && egg) {
    const { location, dimension } = egg;
    system17.runTimeout(() => {
      if (!egg.isValid())
        return;
      const eggTameableComponent = egg.getComponent("minecraft:tameable");
      let owner = eggTameableComponent.tamedToPlayer;
      if (!owner) {
        owner = dimension.getEntities({
          location: egg.location,
          closest: 1,
          type: "player"
        })[0];
        if (!owner)
          return;
      }
      const entityTypeID = egg.typeId.replace("_egg", "");
      egg.runCommand(`/summon ${entityTypeID} ~~~ ~~ minecraft:entity_born`);
      const baby = egg.dimension.getEntities({
        type: entityTypeID,
        location: egg.location,
        closest: 1,
        maxDistance: 0.1
      })[0];
      if (baby === void 0) {
        egg.remove();
        return;
      }
      const babyTameableComponent = baby.getComponent("minecraft:tameable");
      babyTameableComponent.tame(owner);
      baby.triggerEvent("shapescape_ext:tamed");
      if (baby.typeId.includes("void_runner")) {
        baby.addTag("shapescape_ext_INITIALIZED");
        baby.triggerEvent("shapescape_ext:leader");
      }
      baby.triggerEvent("minecraft:entity_born");
      egg.remove();
    }, HATCHING_TIME);
  }
  if (messageID.includes("shapescape") && messageID.includes("egg") && message === "tp_to_nest" && egg) {
    const { location, dimension } = egg;
    const size = { x: 20, y: 10, z: 20 };
    const from = {
      x: location.x - Math.round(size.x / 2),
      y: location.y - Math.round(size.y / 2),
      z: location.z - Math.round(size.z / 2)
    };
    const to = {
      x: location.x + Math.round(size.x / 2),
      y: location.y + Math.round(size.y / 2),
      z: location.z + Math.round(size.z / 2)
    };
    const blockLocations = new BlockVolume3(from, to).getBlockLocationIterator();
    for (const location2 of blockLocations) {
      let block;
      try {
        block = dimension.getBlock(location2);
      } catch {
        continue;
      }
      if (block && block.typeId.includes("shapescape") && block.typeId.includes("nest_block")) {
        const eggs = dimension.getEntities({
          location: {
            x: location2.x,
            y: location2.y + 1,
            z: location2.z
          },
          maxDistance: 1
        });
        if (eggs.length === 0) {
          egg.teleport(block.center());
        }
        return;
      }
    }
  }
  if (messageID.includes("shapescape") && messageID.includes("egg") && message === "check_warm_nest" && egg) {
    const { location, dimension } = egg;
    let block;
    try {
      block = dimension.getBlock({
        x: location.x,
        y: location.y - 0.5,
        z: location.z
      });
    } catch {
    }
    if (block && block.typeId.includes("shapescape") && block.typeId.includes("nest_block") && block.typeId.includes("warm")) {
      egg.triggerEvent("shapescape_ext:warm");
    }
  }
  if (messageID.includes("shapescape") && messageID.includes("egg") && message === "egg_thief" && egg) {
    const { location, dimension } = egg;
    const dinoTypeID = egg.typeId.replace("_egg", "").replace("shapescape_ext:", "");
    const TAG19 = `shapescape_ext_${dinoTypeID}_egg_thief`;
    const players = dimension.getPlayers({
      location,
      maxDistance: 10
    });
    for (const player of players) {
      if (!player.hasTag(TAG19)) {
        player.addTag(TAG19);
        player.setDynamicProperty(TAG19, system17.currentTick);
      }
    }
  }
});
world17.afterEvents.itemUseOn.subscribe((event) => {
  const { block, source, itemStack } = event;
  if (!source || !block || !itemStack)
    return;
  if (itemStack.typeId.includes("shapescape") && itemStack.typeId.includes("egg")) {
    const entities2 = source.dimension.getEntities({
      location: block.center(),
      maxDistance: 1,
      type: itemStack.typeId
    });
    if (entities2.length === 1) {
      const entity = entities2[0];
      const tameableComponent = entity.getComponent("minecraft:tameable");
      tameableComponent.tame(source);
      entity.triggerEvent("shapescape_ext:tamed");
    } else {
      return;
    }
  }
});
system17.runInterval(() => {
  const players = world17.getAllPlayers();
  for (const player of players) {
    const playerPropertyIDs = player.getDynamicPropertyIds();
    for (const propertyID of playerPropertyIDs) {
      if (propertyID.includes("shapescape") && propertyID.includes("egg_thief")) {
        if (!player.hasTag(propertyID))
          return;
        let timeStamp = player.getDynamicProperty(propertyID);
        if (timeStamp === void 0) {
          timeStamp = 0;
        }
        if (system17.currentTick - timeStamp > 10 * TicksPerSecond2) {
          player.removeTag(propertyID);
          player.setDynamicProperty(propertyID);
        }
      }
    }
  }
}, 40);

// data/system_template_esbuild/subscripts/flute.ts
import {
  world as world18,
  Player as Player8,
  ItemStack as ItemStack2,
  system as system18,
  EntityComponentTypes as EntityComponentTypes2,
  EquipmentSlot as EquipmentSlot3
} from "@minecraft/server";
var RADIUS = 15;
world18.beforeEvents.itemUse.subscribe((event) => {
  const { itemStack, source } = event;
  if (itemStack.typeId.includes("shapescape") && itemStack.typeId.includes("flute") && source instanceof Player8) {
    const playerId = source.id;
    if (!source.isSneaking) {
      system18.run(() => {
        followSwitch(playerId);
      });
    } else {
    }
    system18.run(() => {
      if (!itemStack || !source)
        return;
      const equippableComponent = source.getComponent(EntityComponentTypes2.Equippable);
      const durComponent = itemStack.getComponent("minecraft:durability");
      if (durComponent.damage + 1 > durComponent.maxDurability) {
        source.playSound("random.break", { location: source.location });
        equippableComponent.setEquipment(EquipmentSlot3.Mainhand, void 0);
        return;
      }
      const newItemStack = new ItemStack2(itemStack.typeId, 1);
      const newDurComponent = newItemStack.getComponent("minecraft:durability");
      newDurComponent.damage = durComponent.damage + 1;
      equippableComponent.setEquipment(EquipmentSlot3.Mainhand, newItemStack);
    });
  }
});
function followSwitch(playerId) {
  const player = world18.getEntity(playerId);
  world18.playSound("shapescape_ext.flute.flute", player.location);
  player.dimension.spawnParticle("shapescape_ext:flute_note", {
    x: player.location.x,
    y: player.location.y + 1.5,
    z: player.location.z
  });
  player.dimension.spawnParticle("shapescape_ext:flute_radius", {
    x: player.location.x,
    y: player.location.y,
    z: player.location.z
  });
  const entities2 = player.dimension.getEntities({
    location: player.location,
    maxDistance: RADIUS
  });
  const propertySwitch = getSwitchProperty(player);
  for (const entity of entities2) {
    if (entity.typeId.includes("shapescape") && !entity.typeId.includes("egg") && !entity.typeId.includes("scavenging_dropper") && !entity.typeId.includes("javelin") && !entity.typeId.includes("spit")) {
      const entityTameableComponent = entity.getComponent("minecraft:tameable");
      if (entityTameableComponent.tamedToPlayerId === playerId) {
        try {
          if (propertySwitch) {
            entity.triggerEvent("shapescape_ext:follow_owner");
          } else {
            entity.triggerEvent("shapescape_ext:remove_follow_owner");
          }
        } catch {
        }
      }
    }
  }
}
function getSwitchProperty(player) {
  const property = player.getDynamicProperty("flute_follow_owner");
  let returnValue = false;
  if (property) {
    player.setDynamicProperty("flute_follow_owner", false);
    returnValue = false;
  } else {
    player.setDynamicProperty("flute_follow_owner", true);
    returnValue = true;
  }
  return returnValue;
}

// data/system_template_esbuild/subscripts/fly.ts
import {
  world as world19,
  system as system19,
  EntityRideableComponent as EntityRideableComponent2
} from "@minecraft/server";
var DEBUG2 = false;
var TICK_INTERVAL = 1;
var MAX_VELOCITY = 0.5;
var HOVER_ANGLE = 10;
var STATIONARY_VELOCITY = 0.15;
var entities = {};
var FLYING_ENTITY_TYPES = ["shapescape_ext:void_wing", "shapescape_ext:pterodactyl"];
system19.afterEvents.scriptEventReceive.subscribe((event) => {
  if (!event.sourceEntity) {
    return;
  }
  if (!FLYING_ENTITY_TYPES.includes(event.sourceEntity.typeId)) {
    return;
  }
  if (event.id == "shapescape_ext:ride") {
    if (event.message === "NULL") {
      popEntity(event.sourceEntity);
    } else {
      const rideable = event.sourceEntity.getComponent(
        EntityRideableComponent2.componentId
      );
      if (rideable) {
        const riders = rideable.getRiders();
        if (riders.length > rideable.controllingSeat) {
          const rider = riders[rideable.controllingSeat];
          if (rider) {
            pushEntity(event.sourceEntity, rider);
          }
        }
      }
    }
  }
});
world19.beforeEvents.playerLeave.subscribe((event) => {
  var desiredEntity = null;
  for (var entityId in entities) {
    if (entities.hasOwnProperty(entityId)) {
      if (entities[entityId].playerObject === event.player) {
        desiredEntity = entities[entityId];
        break;
      }
    }
  }
  if (desiredEntity != null) {
    delete entities[desiredEntity];
  }
});
function pushEntity(entityEntityObject, playerEntityObject) {
  if (!FLYING_ENTITY_TYPES.includes(entityEntityObject.typeId)) {
    return;
  }
  entities[entityEntityObject.id] = {};
  let entity = entities[entityEntityObject.id];
  entity["entityObject"] = entityEntityObject;
  entity["playerObject"] = playerEntityObject;
  if (DEBUG2) {
    printEntitiesObject();
  }
}
function popEntity(entityEntityObject) {
  delete entities[entityEntityObject.id];
  if (DEBUG2) {
    printEntitiesObject();
  }
}
function printEntitiesObject() {
}
function vector2DtoMetersPerSecond(x, z) {
  return Math.sqrt(x ** 2 + z ** 2);
}
function sigmoid(x) {
  return 1 / (1 + Math.exp(-x));
}
function calculateVerticalSpeed(headRotation) {
  const sigmoidScale = 0.1;
  const sigmoidShift = 40;
  const speed = sigmoid(sigmoidScale * (headRotation - sigmoidShift));
  const scaledSpeed = speed * 0.45;
  return scaledSpeed;
}
function moveEntity(object) {
  let player = object["playerObject"];
  let entity = object["entityObject"];
  if (entity == void 0) {
    return;
  }
  let entity_velocity_vector = entity.getVelocity();
  let player_head_v_rotation = -player.getRotation().x;
  let player_view_direction = player.getViewDirection();
  let entity_y_velocity = -entity_velocity_vector.y;
  let entity_speed_meters_per_second = vector2DtoMetersPerSecond(
    entity_velocity_vector.x,
    entity_velocity_vector.z
  );
  let new_velocity_vector = {
    x: 0,
    y: 0,
    z: 0
  };
  if (entity_speed_meters_per_second < STATIONARY_VELOCITY) {
  } else {
    if (Math.abs(player_head_v_rotation) < HOVER_ANGLE) {
    } else if (player_head_v_rotation > HOVER_ANGLE) {
      new_velocity_vector.y = calculateVerticalSpeed(
        Math.abs(player_head_v_rotation - HOVER_ANGLE)
      );
    } else if (player_head_v_rotation < -HOVER_ANGLE) {
      new_velocity_vector.y = -calculateVerticalSpeed(
        Math.abs(player_head_v_rotation - HOVER_ANGLE)
      );
    }
  }
  if (DEBUG2) {
    world19.sendMessage(
      `Entity Horizontal Speed ${entity_speed_meters_per_second.toFixed(2).toString()}m/s`
    );
  }
  if (Math.abs(entity_y_velocity) < MAX_VELOCITY) {
    entity.applyImpulse({
      x: 0,
      y: new_velocity_vector.y,
      z: 0
    });
  }
}
function main() {
  Object.entries(entities).forEach(([entityKey, entity]) => {
    try {
      moveEntity(entity);
    } catch (error) {
    }
  });
}
system19.runInterval(main, TICK_INTERVAL);

// data/system_template_esbuild/subscripts/grumble.ts
import {
  system as system20,
  world as world20,
  BlockVolume as BlockVolume4,
  Player as Player10,
  TicksPerSecond as TicksPerSecond3
} from "@minecraft/server";
Polyfill.installPlayer();
var ROAR_RADIUS = 15;
var BLOCKS_TO_INCLUDE = /* @__PURE__ */ new Set([
  // Leaves
  "minecraft:acacia_leaves",
  "minecraft:azalea_leaves",
  "minecraft:azalea_leaves_flowered",
  "minecraft:birch_leaves",
  "minecraft:cherry_leaves",
  "minecraft:dark_oak_leaves",
  "minecraft:jungle_leaves",
  "minecraft:mangrove_leaves",
  "minecraft:oak_leaves",
  "minecraft:pale_oak_leaves",
  "minecraft:spruce_leaves",
  "minecraft:nether_wart_block",
  "minecraft:warped_wart_block",
  // Small plants
  "minecraft:deadbush",
  "minecraft:chorus_flower",
  "minecraft:chorus_plant",
  "minecraft:nether_sprouts",
  "minecraft:warped_roots",
  "minecraft:warped_fungus",
  "minecraft:crimson_roots",
  "minecraft:crimson_fungus",
  "minecraft:fern",
  "minecraft:short_grass",
  "minecraft:tall_grass",
  "minecraft:wheat",
  "minecraft:carrots",
  "minecraft:potatoes",
  "minecraft:beetroot",
  "minecraft:melon_stem",
  "minecraft:pumpkin_stem",
  "minecraft:sweet_berry_bush",
  "minecraft:cocoa",
  "minecraft:pink_petals",
  "minecraft:wildflowers",
  "minecraft:mangrove_propagule",
  "minecraft:acacia_sapling",
  "minecraft:birch_sapling",
  "minecraft:cherry_sapling",
  "minecraft:dark_oak_sapling",
  "minecraft:jungle_sapling",
  "minecraft:oak_sapling",
  "minecraft:pale_oak_sapling",
  "minecraft:spruce_sapling",
  "minecraft:reeds",
  "minecraft:bamboo_sapling",
  "minecraft:bamboo",
  "minecraft:kelp",
  "minecraft:twisting_vines",
  "minecraft:cave_vines",
  "minecraft:weeping_vines",
  "minecraft:sunflower",
  "minecraft:lilac",
  "minecraft:rose_bush",
  "minecraft:peony",
  "minecraft:bush",
  "minecraft:firefly_bush",
  "minecraft:tall_dry_grass",
  "minecraft:short_dry_grass",
  "minecraft:tall_dry_grass",
  "minecraft:orange_tulip",
  "minecraft:pink_tulip",
  "minecraft:white_tulip",
  "minecraft:red_tulip",
  "minecraft:blue_orchid",
  "minecraft:allium",
  "minecraft:azure_bluet",
  "minecraft:cornflower",
  "minecraft:dandelion",
  "minecraft:lily_of_the_valley",
  "minecraft:oxeye_daisy",
  "minecraft:poppy",
  "minecraft:short_grass"
]);
var TAG4 = "shapescape_ext_grumble_eating";
var tamingItem = [
  "minecraft:chicken",
  "minecraft:cooked_chicken",
  "minecraft:beef",
  "minecraft:cooked_beef",
  "minecraft:muttonRaw",
  "minecraft:muttonCooked",
  "minecraft:porkchop",
  "minecraft:cooked_porkchop",
  "minecraft:rabbit",
  "minecraft:cooked_rabbit",
  "minecraft:rotten_flesh"
];
system20.afterEvents.scriptEventReceive.subscribe((event) => {
  const message = event.message;
  const messageID = event.id;
  const entity = event.sourceEntity;
  if (!entity)
    return;
  const baby = entity.getComponent(
    "minecraft:is_baby"
  );
  if (entity && messageID === "shapescape_ext:grumble" && message === "roar" && !baby) {
    entity.triggerEvent("shapescape_ext:roar");
    roar(entity);
  }
  if (entity && messageID === "shapescape_ext:grumble" && message === "naturally_spawned") {
    let property = world20.getDynamicProperty("grumble_spawn");
    if (property === void 0 || property === false) {
      entity.remove();
    }
  }
  if (entity && messageID === "shapescape_ext:grumble" && message === "set_spawn_true") {
    world20.setDynamicProperty("grumble_spawn", true);
  }
});
world20.afterEvents.playerInteractWithEntity.subscribe((event) => {
  const { player, target, itemStack } = event;
  if (itemStack?.typeId === "minecraft:lava_bucket" && target?.typeId === "shapescape_ext:grumble") {
    player.runCommand(`scriptevent shapescape_ext:grumble set_spawn_true`);
    player.runCommand(`clear @s minecraft:lava_bucket 0 1`);
    player.runCommand(`give @s minecraft:bucket 1`);
    target.runCommand(
      `summon shapescape_ext:grumble ~~~ ~~ minecraft:entity_spawned`
    );
    system20.runTimeout(() => {
      if (!target || !target.isValid() || !player || !player.isValid())
        return;
      target.dimension.spawnParticle(
        `shapescape_ext:grumble_defrost`,
        target.location
      );
      target.remove();
      player.sendMessage({
        rawtext: [{ translate: `action.interact.shapescape_ext:grumble.defrost` }]
      });
      player.playSound(`shapescape_ext.grumble.defrost`, {
        location: player.location
      });
    }, 10);
  }
});
world20.afterEvents.playerInteractWithEntity.subscribe((event) => {
  const { player, target, itemStack } = event;
  if (!itemStack || !player || !target || target.typeId !== "shapescape_ext:grumble" || !tamingItem.includes(itemStack.typeId))
    return;
  const baby = target.getComponent(
    "minecraft:is_baby"
  );
  if (!target.hasTag(TAG4)) {
    target.addTag(TAG4);
    if (baby) {
      target.playAnimation("animation.shapescape_ext.grumble_baby.chewing_layer", {
        blendOutTime: 0.2
      });
    } else {
      target.playAnimation("animation.shapescape_ext.grumble.chewing_layer", {
        blendOutTime: 0.2
      });
    }
    system20.runTimeout(() => {
      target.removeTag(TAG4);
    }, 20 * 1.2);
  }
});
function roar(damagerEntity) {
  const dimension = damagerEntity.dimension;
  system20.runTimeout(() => {
    if (!damagerEntity.isValid())
      return;
    let volume = new BlockVolume4(
      {
        x: damagerEntity.location.x - Math.round(ROAR_RADIUS / 2),
        y: damagerEntity.location.y - Math.round(ROAR_RADIUS / 2),
        z: damagerEntity.location.z - Math.round(ROAR_RADIUS / 2)
      },
      {
        x: damagerEntity.location.x + Math.round(ROAR_RADIUS / 2),
        y: damagerEntity.location.y + Math.round(ROAR_RADIUS / 2),
        z: damagerEntity.location.z + Math.round(ROAR_RADIUS / 2)
      }
    );
    let blocksToDestroy = damagerEntity.dimension.getBlocks(
      volume,
      {
        includeTypes: Array.from(BLOCKS_TO_INCLUDE)
      },
      true
    ).getBlockLocationIterator();
    for (const location of blocksToDestroy) {
      let block;
      try {
        block = damagerEntity.dimension.getBlock(location);
      } catch (error) {
        continue;
      }
      if (block === void 0)
        continue;
      breakBlock2(damagerEntity, block, 0.15);
    }
    const affectedEntities = dimension.getEntities({
      location: damagerEntity.location,
      maxDistance: ROAR_RADIUS,
      excludeTypes: [
        "shapescape_ext:grumble",
        "minecraft:item",
        "minecraft:falling_block",
        "minecraft:experience_orb"
      ]
    });
    for (const affectedEntity of affectedEntities) {
      if (affectedEntity === void 0)
        continue;
      affectedEntity.applyDamage(10);
      if (affectedEntity instanceof Player10) {
        affectedEntity.runCommand(`/camerashake add @s 0.4 1.75 positional`);
      }
    }
  }, 1 * TicksPerSecond3);
  system20.runTimeout(() => {
    if (!damagerEntity.isValid())
      return;
    dimension.playSound(`shapescape_ext.grumble.roar`, damagerEntity.location, {
      volume: 2,
      pitch: 1
    });
  }, 0.75 * TicksPerSecond3);
  system20.runTimeout(() => {
    if (!damagerEntity.isValid())
      return;
    damagerEntity.triggerEvent("shapescape_ext:stroll");
  }, 2.75 * TicksPerSecond3);
}
function breakBlock2(entity, block, keepItemChance) {
  if (Math.random() < keepItemChance) {
    const location = block.location;
    entity.runCommandAsync(
      `/setblock ${location.x} ${location.y} ${location.z} air destroy`
    );
  } else {
    block.setType("minecraft:air");
  }
}

// data/system_template_esbuild/subscripts/grumble_spawner.ts
import {
  world as world21
} from "@minecraft/server";
var nestLocations2 = /* @__PURE__ */ new Set();
world21.beforeEvents.worldInitialize.subscribe((event) => {
  event.blockComponentRegistry.registerCustomComponent(
    "shapescape_ext:grumble_spawner",
    {
      onTick(event2) {
        const scoreboard = world21.scoreboard.getObjective(
          "shapescape_ext_feature_nest_block"
        );
        const block = event2.block;
        if (scoreboard === void 0) {
          if (!nestLocations2.has(JSON.stringify(block.location))) {
            nestLocations2.add(JSON.stringify(block.location));
            block.dimension.setBlockType(block.location, block.typeId);
            return;
          }
          spawnGrumble(event2.block);
        } else {
          return;
        }
      }
    }
  );
});
function spawnGrumble(block) {
  nestLocations2.delete(JSON.stringify(block.location));
  try {
    const northLocation = block.north(1).above(1).center();
    const southLocation = block.south(1).above(1).center();
    block.dimension.setBlockType(block.location, "minecraft:air");
    block.dimension.runCommand(
      `summon shapescape_ext:grumble ${northLocation.x} ${northLocation.y} ${northLocation.z} 45 0 shapescape_ext:ice_form`
    );
  } catch {
  }
}

// data/system_template_esbuild/subscripts/tusked_javelin.ts
import {
  world as world23,
  Player as Player12,
  EntityComponentTypes as EntityComponentTypes3,
  EquipmentSlot as EquipmentSlot4,
  TicksPerSecond as TicksPerSecond4
} from "@minecraft/server";
world23.afterEvents.entityHitEntity.subscribe((event) => {
  const { damagingEntity, hitEntity } = event;
  if (!(damagingEntity instanceof Player12))
    return;
  const player = damagingEntity;
  const itemStack = player.getComponent(EntityComponentTypes3.Equippable)?.getEquipment(EquipmentSlot4.Mainhand);
  if (itemStack?.typeId === "shapescape_ext:tusked_javelin") {
    const duration = Math.random() * 3 + 2;
    hitEntity.addEffect("slowness", duration * TicksPerSecond4, {
      amplifier: 2,
      showParticles: true
    });
  }
});

// data/system_template_esbuild/subscripts/mammoth.ts
import { system as system24 } from "@minecraft/server";
var includePassableBlocks = [
  "minecraft:double_plant",
  "minecraft:short_grass",
  "minecraft:tall_grass",
  "minecraft:seagrass",
  "minecraft:sunflower",
  "minecraft:torchflower_crop",
  "minecraft:torchflower",
  "minecraft:orange_tulip",
  "minecraft:pink_tulip",
  "minecraft:white_tulip",
  "minecraft:red_tulip",
  "minecraft:blue_orchid",
  "minecraft:allium",
  "minecraft:azure_bluet",
  "minecraft:cornflower",
  "minecraft:dandelion",
  "minecraft:lily_of_the_valley",
  "minecraft:oxeye_daisy",
  "minecraft:poppy",
  "minecraft:rose_bush",
  "minecraft:peony",
  "minecraft:lilac",
  "minecraft:fern",
  "minecraft:wither_rose",
  "minecraft:crimson_roots",
  "minecraft:warped_roots",
  "minecraft:nether_sprouts",
  "minecraft:brain_coral",
  "minecraft:bubble_coral",
  "minecraft:fire_coral",
  "minecraft:horn_coral",
  "minecraft:tube_coral",
  "minecraft:dead_brain_coral",
  "minecraft:dead_bubble_coral",
  "minecraft:dead_fire_coral",
  "minecraft:dead_horn_coral",
  "minecraft:dead_tube_coral"
];
var ATTACK_DISTANCE = 3.5;
var ATTACK_RADIUS = 3.5;
var ATTACK_DAMAGE = 15;
system24.afterEvents.scriptEventReceive.subscribe((event) => {
  const sourceEntity = event.sourceEntity;
  const eventName = event.id;
  if (eventName != "shapescape_ext:breaking_blocks" || sourceEntity == void 0 || !sourceEntity.isValid() || sourceEntity.typeId != "shapescape_ext:wooly_mammoth") {
    return;
  }
  sourceEntity.runCommandAsync(
    "playsound shapescape_ext.wooly_mammoth.roar @a ~ ~ ~ 1 1 0.5"
  );
  system24.runTimeout(() => {
    breakingBlocks(sourceEntity);
  }, 20 * 1.9);
});
function breakingBlocks(sourceEntity) {
  const location = sourceEntity.location;
  let radius = 6;
  includePassableBlocks.forEach((blockType) => {
    for (let dx = -radius; dx <= radius; dx++) {
      for (let dz = -radius; dz <= radius; dz++) {
        for (let dy = -radius; dy <= radius; dy++) {
          const targetLocation = {
            x: location.x + dx,
            y: location.y + dy,
            z: location.z + dz
          };
          const block = sourceEntity.dimension.getBlock(targetLocation);
          if (block?.typeId === blockType) {
            sourceEntity.runCommandAsync(
              `setblock ${targetLocation.x} ${targetLocation.y} ${targetLocation.z} air [] destroy`
            );
          }
        }
      }
    }
  });
  sourceEntity.runCommandAsync(`camerashake add @a[r=10] 0.7 0.5 positional`);
}
system24.afterEvents.scriptEventReceive.subscribe((event) => {
  const message = event.message;
  const messageID = event.id;
  const entity = event.sourceEntity;
  if (entity && messageID === "shapescape_ext:wooly_mammoth" && message === "attack") {
    system24.runTimeout(() => {
      tamedAttack(entity);
      entity.playAnimation("animation.shapescape_ext.wooly_mammoth.attack", {
        blendOutTime: 1
      });
      entity.dimension.playSound("shapescape_ext.wooly_mammoth.attack", {
        x: entity.location.x,
        y: entity.location.y,
        z: entity.location.z
      });
    }, 20 * 0.4);
  }
});
function tamedAttack(entity) {
  const viewDirection = entity.getViewDirection();
  const dimension = entity.dimension;
  const location = entity.location;
  const tag = `shapescape_ext_${entity.id}`;
  entity.addTag(tag);
  const positionInFront = Vec3.from(viewDirection).multiply({ x: ATTACK_DISTANCE, y: 0, z: ATTACK_DISTANCE }).add(location);
  const entitiesToDamage = dimension.getEntities({
    location: positionInFront,
    maxDistance: ATTACK_RADIUS,
    excludeFamilies: ["projectile", "inanimate"],
    excludeTypes: ["minecraft:item", "minecraft:arrow"],
    excludeTags: [tag]
  });
  for (const entity2 of entitiesToDamage) {
    entity2.applyDamage(ATTACK_DAMAGE);
    entity2.applyImpulse(
      Vec3.from(viewDirection).multiply({
        x: 2,
        y: 2,
        z: 2
      })
    );
  }
  system24.runTimeout(() => {
    entity.removeTag(tag);
    entity.setProperty("shapescape_ext:attack", false);
  }, 20 * 1.5);
}

// data/system_template_esbuild/subscripts/mammoth_eating.ts
import { world as world25, system as system25 } from "@minecraft/server";
var tamingItem2 = ["minecraft:hay_block", "minecraft:wheat"];
var TAG5 = "shapescape_ext_wooly_mammoth_eating";
world25.afterEvents.playerInteractWithEntity.subscribe((event) => {
  const player = event.player;
  const itemStack = event.beforeItemStack;
  const entity = event.target;
  if (!itemStack || !player || !entity || entity.typeId !== "shapescape_ext:wooly_mammoth" || !tamingItem2.includes(itemStack.typeId))
    return;
  const baby = entity.getComponent(
    "minecraft:is_baby"
  );
  if (!entity.hasTag(TAG5)) {
    entity.addTag(TAG5);
    if (baby) {
      entity.playAnimation("animation.shapescape_ext.wooly_mammoth_baby.chewing", {
        blendOutTime: 0.2
      });
    } else {
      entity.playAnimation("animation.shapescape_ext.wooly_mammoth.chewing", {
        blendOutTime: 0.2
      });
    }
    system25.runTimeout(() => {
      entity.removeTag(TAG5);
    }, 20 * 1.5);
  }
});

// data/system_template_esbuild/subscripts/pterodactyl_eating.ts
import { world as world26, system as system26 } from "@minecraft/server";
var TAG6 = "shapescape_ext_pterodactyl_eating";
world26.afterEvents.playerInteractWithEntity.subscribe((event) => {
  const player = event.player;
  const itemStack = event.beforeItemStack;
  const entity = event.target;
  if (!itemStack || !player || !entity || entity.typeId !== "shapescape_ext:pterodactyl" || itemStack.typeId !== "minecraft:potato")
    return;
  const baby = entity.getComponent(
    "minecraft:is_baby"
  );
  if (!entity.hasTag(TAG6)) {
    entity.addTag(TAG6);
    if (baby) {
      entity.playAnimation(
        "animation.shapescape_ext.pterodactyl_baby.chewing_layer",
        {
          blendOutTime: 0.2
        }
      );
    } else {
      entity.playAnimation("animation.shapescape_ext.pterodactyl.chewing_layer", {
        blendOutTime: 0.2
      });
    }
    system26.runTimeout(() => {
      entity.removeTag(TAG6);
    }, 20 * 1.9);
  }
});

// data/system_template_esbuild/subscripts/pterodactyl.ts
import { system as system27 } from "@minecraft/server";
var ATTACK_DISTANCE2 = 3;
var ATTACK_RADIUS2 = 3;
var ATTACK_DAMAGE2 = 15;
system27.afterEvents.scriptEventReceive.subscribe((event) => {
  const message = event.message;
  const messageID = event.id;
  const entity = event.sourceEntity;
  if (entity && messageID === "shapescape_ext:pterodactyl" && message === "attack") {
    system27.runTimeout(() => {
      tamedAttack2(entity);
      entity.playAnimation("animation.shapescape_ext.pterodactyl.attack_layer", {
        blendOutTime: 1
      });
    }, 20 * 0.13);
  }
});
function tamedAttack2(entity) {
  const viewDirection = entity.getViewDirection();
  const dimension = entity.dimension;
  const location = entity.location;
  const tag = `shapescape_ext_${entity.id}`;
  entity.addTag(tag);
  const positionInFront = Vec3.from(viewDirection).multiply({ x: ATTACK_DISTANCE2, y: 0, z: ATTACK_DISTANCE2 }).add(location);
  const entitiesToDamage = dimension.getEntities({
    location: positionInFront,
    maxDistance: ATTACK_RADIUS2,
    excludeFamilies: ["projectile", "inanimate"],
    excludeTypes: ["minecraft:item", "minecraft:arrow"],
    excludeTags: [tag]
  });
  for (const entity2 of entitiesToDamage) {
    entity2.applyDamage(ATTACK_DAMAGE2);
    entity2.applyImpulse(
      Vec3.from(viewDirection).multiply({
        x: 2,
        y: 2,
        z: 2
      })
    );
  }
  system27.runTimeout(() => {
    entity.removeTag(tag);
    entity.setProperty("shapescape_ext:state", "default");
  }, 20 * 0.58);
}

// data/system_template_esbuild/subscripts/shimmer_feather_chestplate.ts
import {
  EntityComponentTypes as EntityComponentTypes4,
  EquipmentSlot as EquipmentSlot5,
  system as system28,
  world as world28
} from "@minecraft/server";
var SHIMMER_FEATHER_CHESTPLATE_ID = "shapescape_ext:shimmer_feather_chestplate";
var SHIMMER_FEATHER_TAG = "shapescape_ext_shimmer_feather_chestplate";
var CHECK_INTERVAL_TICKS = 10;
world28.beforeEvents.itemUse.subscribe((event) => {
  const player = event.source;
  const item = event.itemStack;
  if (item.typeId === SHIMMER_FEATHER_CHESTPLATE_ID) {
    checkPlayerEquipment2(player);
  }
});
system28.runInterval(() => {
  for (const player of world28.getAllPlayers()) {
    checkPlayerEquipment2(player);
  }
}, CHECK_INTERVAL_TICKS);
function checkPlayerEquipment2(player) {
  const equipment = player.getComponent(
    EntityComponentTypes4.Equippable
  );
  if (!equipment)
    return;
  const chestplateSlot = equipment.getEquipmentSlot(EquipmentSlot5.Chest);
  if (!chestplateSlot.isValid())
    return;
  const chestplateItem = chestplateSlot.getItem();
  const isWearingShimmerChestplate = chestplateItem?.typeId === SHIMMER_FEATHER_CHESTPLATE_ID;
  const hasShimmerTag = player.hasTag(SHIMMER_FEATHER_TAG);
  if (isWearingShimmerChestplate && !hasShimmerTag) {
    applySlowFallingEffect(player);
  } else if (!isWearingShimmerChestplate && hasShimmerTag) {
    removeSlowFallingEffect(player);
  }
}
function applySlowFallingEffect(player) {
  player.addTag(SHIMMER_FEATHER_TAG);
  player.addEffect("minecraft:slow_falling", 999999, {
    amplifier: 1,
    showParticles: false
  });
}
function removeSlowFallingEffect(player) {
  player.removeTag(SHIMMER_FEATHER_TAG);
  player.removeEffect("minecraft:slow_falling");
}

// data/system_template_esbuild/subscripts/razor_jaw.ts
import { world as world29, system as system29 } from "@minecraft/server";
var TAG7 = "shapescape_ext_razor_jaw_eating";
var tamingItem3 = ["minecraft:rabbit", "minecraft:cooked_rabbit", "minecraft:beetroot"];
world29.afterEvents.playerInteractWithEntity.subscribe((event) => {
  const { player, target, itemStack } = event;
  if (!itemStack || !player || !target || target.typeId !== "shapescape_ext:razor_jaw" || !tamingItem3.includes(itemStack.typeId))
    return;
  const baby = target.getComponent("minecraft:is_baby");
  if (!target.hasTag(TAG7)) {
    target.addTag(TAG7);
    if (baby) {
      target.playAnimation("animation.shapescape_ext.razor_jaw_baby.chewing_layer", {
        blendOutTime: 0.2
      });
    } else {
      target.playAnimation("animation.shapescape_ext.razor_jaw.chewing_layer", {
        blendOutTime: 0.2
      });
    }
    system29.runTimeout(() => {
      target.removeTag(TAG7);
    }, 20 * 1.2);
  }
});
world29.afterEvents.entityLoad.subscribe((event) => {
  if (event.entity.hasTag(TAG7)) {
    event.entity.removeTag(TAG7);
  }
});

// data/system_template_esbuild/subscripts/sabertooth_spawner.ts
import {
  world as world30
} from "@minecraft/server";
var nestLocations3 = /* @__PURE__ */ new Set();
world30.beforeEvents.worldInitialize.subscribe((event) => {
  event.blockComponentRegistry.registerCustomComponent(
    "shapescape_ext:sabertooth_spawner",
    {
      onTick(event2) {
        const scoreboard = world30.scoreboard.getObjective(
          "shapescape_ext_feature_nest_block"
        );
        const block = event2.block;
        if (scoreboard === void 0) {
          if (!nestLocations3.has(JSON.stringify(block.location))) {
            nestLocations3.add(JSON.stringify(block.location));
            block.dimension.setBlockType(block.location, block.typeId);
            return;
          }
          spawnTiger(event2.block);
        } else {
          return;
        }
      }
    }
  );
});
function spawnTiger(block) {
  nestLocations3.delete(JSON.stringify(block.location));
  try {
    const northLocation = block.north(1).above(1).center();
    const southLocation = block.south(1).above(1).center();
    block.dimension.setBlockType(block.location, "minecraft:air");
    block.dimension.runCommand(
      `summon shapescape_ext:sabertooth_tiger ${northLocation.x} ${northLocation.y} ${northLocation.z}`
    );
    if (Math.random() > 0.5) {
      block.dimension.runCommand(
        `summon shapescape_ext:sabertooth_tiger ${southLocation.x} ${southLocation.y} ${southLocation.z}`
      );
    }
    block.dimension.runCommand(
      `summon shapescape_ext:sabertooth_tiger ${northLocation.x} ${northLocation.y} ${northLocation.z} ~~ minecraft:entity_born`
    );
    if (Math.random() > 0.5) {
      block.dimension.runCommand(
        `summon shapescape_ext:sabertooth_tiger ${southLocation.x} ${southLocation.y} ${southLocation.z} ~~ minecraft:entity_born`
      );
    }
  } catch {
  }
}

// data/system_template_esbuild/subscripts/sabertooth_tiger_eating.ts
import { world as world31, system as system31 } from "@minecraft/server";
var tamingItem4 = [
  "minecraft:chicken",
  "minecraft:cooked_chicken",
  "minecraft:beef",
  "minecraft:cooked_beef",
  "minecraft:muttonRaw",
  "minecraft:muttonCooked",
  "minecraft:porkchop",
  "minecraft:cooked_porkchop",
  "minecraft:rabbit",
  "minecraft:cooked_rabbit",
  "minecraft:rotten_flesh"
];
var TAG8 = "shapescape_ext_sabertooth_tiger_eating";
world31.afterEvents.playerInteractWithEntity.subscribe((event) => {
  const player = event.player;
  const itemStack = event.beforeItemStack;
  const entity = event.target;
  if (!itemStack || !player || !entity || entity.typeId !== "shapescape_ext:sabertooth_tiger" || !tamingItem4.includes(itemStack.typeId))
    return;
  const baby = entity.getComponent(
    "minecraft:is_baby"
  );
  if (!entity.hasTag(TAG8)) {
    entity.addTag(TAG8);
    if (baby) {
      entity.playAnimation(
        "animation.shapescape_ext.sabertooth_baby.chewing_layer",
        {
          blendOutTime: 0.2
        }
      );
    } else {
      entity.playAnimation("animation.shapescape_ext.sabertooth.chewing_layer", {
        blendOutTime: 0.2
      });
    }
    system31.runTimeout(() => {
      entity.removeTag(TAG8);
    }, 20 * 1.2);
  }
});

// data/system_template_esbuild/subscripts/sand_runner.ts
import { system as system32, world as world33 } from "@minecraft/server";
var TAG9 = "shapescape_ext_sand_runner_eating";
world33.afterEvents.playerInteractWithEntity.subscribe((event) => {
  const player = event.player;
  const itemStack = event.beforeItemStack;
  const entity = event.target;
  if (!itemStack || !player || !entity || entity.typeId !== "shapescape_ext:sand_runner" || itemStack.typeId !== "minecraft:cactus")
    return;
  const baby = entity.getComponent(
    "minecraft:is_baby"
  );
  if (!entity.hasTag(TAG9)) {
    entity.addTag(TAG9);
    if (baby) {
      entity.playAnimation(
        "animation.shapescape_ext.sand_runner_baby.breeding_layer",
        {
          blendOutTime: 0.1
        }
      );
    } else {
      entity.playAnimation("animation.shapescape_ext.sand_runner.breeding_layer", {
        blendOutTime: 0.1
      });
    }
    system32.runTimeout(() => {
      entity.removeTag(TAG9);
    }, 20 * 2);
  }
});

// data/system_template_esbuild/subscripts/skyreach.ts
import {
  system as system33,
  world as world34,
  BlockVolume as BlockVolume5,
  GameMode as GameMode6,
  EntityDamageCause as EntityDamageCause2,
  EntityComponentTypes as EntityComponentTypes5
} from "@minecraft/server";
Polyfill.installPlayer();
var ENTITY_HEIGHT = 8.5;
var ENTITY_WIDTH = 4;
var LEAVES_ANIMATION_TIME = 20 * 2;
var STOMP_RADIUS = 5;
var STOMP_DAMAGE = 20;
var STOMP_STRENGTH = 1;
var TAG10 = "shapescape_ext_skyreach_eating";
system33.afterEvents.scriptEventReceive.subscribe((event) => {
  const message = event.message;
  const messageID = event.id;
  const entity = event.sourceEntity;
  if (entity && messageID === "shapescape_ext:skyreach" && message === "start" && !entity.hasComponent("minecraft:is_baby")) {
    entity.triggerEvent("shapescape_ext:look_for_leaves");
  }
  if (entity && messageID === "shapescape_ext:skyreach" && message === "look_for_leaves") {
    lookForLeaves(entity);
  }
  if (entity && messageID === "shapescape_ext:skyreach" && message === "destroy_leaves") {
    system33.runTimeout(() => {
      destroyLeaves(entity);
    }, 10);
  }
  if (entity && messageID === "shapescape_ext:skyreach" && message === "stomp") {
    entity.dimension.playSound(
      "shapescape_ext.skyreach.stomp_start",
      entity.location,
      {
        pitch: 1,
        volume: 1
      }
    );
    system33.runTimeout(() => {
      if (entity.isValid()) {
        entity.dimension.playSound(
          "shapescape_ext.skyreach.stomp_end",
          entity.location,
          {
            pitch: 1,
            volume: 1
          }
        );
      }
    }, 20);
    system33.runTimeout(() => {
      if (entity.isValid()) {
        stomp(entity);
      }
    }, 25);
  }
});
function stomp(entity) {
  const dimension = entity.dimension;
  const location = entity.location;
  const rideableComponent = entity.getComponent(EntityComponentTypes5.Rideable);
  const tag = `shapescape_ext_${entity.id}`;
  let riders = [];
  if (rideableComponent) {
    riders = rideableComponent.getRiders();
    for (const rider of riders) {
      rider.addTag(tag);
    }
  }
  entity.addTag(tag);
  const explosion = {
    entityTargetSelector: {
      excludeTypes: ["minecraft:item", "minecraft:arrow"],
      excludeTags: [tag],
      excludeFamilies: ["inanimate", "projectile"]
    },
    playerTargetSelector: {
      excludeTags: [tag],
      excludeGameModes: [GameMode6.creative, GameMode6.spectator]
    },
    dimension,
    radius: STOMP_RADIUS,
    explosionDamage: [STOMP_DAMAGE, STOMP_DAMAGE],
    knockbackStrength: [STOMP_STRENGTH * 0.9, STOMP_STRENGTH * 1.1],
    knockbackUpBias: 0.8,
    position: {
      x: location.x,
      y: location.y,
      z: location.z
    },
    wallBangRadius: 1,
    damageOptions: {
      damagingEntity: entity,
      cause: EntityDamageCause2.entityExplosion
    }
  };
  createSilentExplosion(explosion);
  for (const rider of riders) {
    rider.removeTag(`shapescape_ext_${entity.id}`);
  }
  entity.removeTag(`shapescape_ext_${entity.id}`);
  entity.triggerEvent("shapescape_ext:stroll");
}
function lookForLeaves(entity) {
  const dimension = entity.dimension;
  const { x, y, z } = {
    x: entity.location.x,
    y: entity.location.y + ENTITY_HEIGHT,
    z: entity.location.z
  };
  const P1 = { x: x - 1, y: y - 2, z: z - 1 };
  const P2 = { x: x + 1, y: y + 2, z: z + 1 };
  const blockVolume = new BlockVolume5(P1, P2).getBlockLocationIterator();
  for (const location of blockVolume) {
    try {
      const blockToCheck = dimension.getBlock(location);
      if (!blockToCheck)
        continue;
      if (blockToCheck.typeId.includes("leaves")) {
        entity.triggerEvent("shapescape_ext:eat");
        entity.teleport(entity.location, {
          facingLocation: location
        });
        system33.runTimeout(() => {
          placeShit(entity);
          return;
        }, LEAVES_ANIMATION_TIME);
      }
    } catch {
    }
  }
}
function destroyLeaves(entity) {
  const blockVolumeLocations = new BlockVolume5(
    {
      x: entity.location.x - ENTITY_WIDTH,
      y: entity.location.y,
      z: entity.location.z - ENTITY_WIDTH
    },
    {
      x: entity.location.x + ENTITY_WIDTH / 2,
      y: entity.location.y + ENTITY_HEIGHT,
      z: entity.location.z + ENTITY_WIDTH / 2
    }
  ).getBlockLocationIterator();
  let index = 0;
  for (const location of blockVolumeLocations) {
    let block;
    try {
      block = entity.dimension.getBlock(location);
    } catch {
    }
    if (!block || !block.typeId.includes("leaves"))
      continue;
    index++;
    system33.runTimeout(() => {
      entity.dimension.runCommandAsync(
        `setblock ${location.x} ${location.y} ${location.z} air [] destroy`
      );
    }, Math.round(index / 5));
  }
  playEatingAnimation(entity);
  if (index > 0)
    placeShit(entity);
  system33.runTimeout(() => {
    if (entity.isValid()) {
      entity.triggerEvent("shapescape_ext:stroll");
    }
  }, 20);
}
function placeShit(entity) {
  if (entity.isValid()) {
    const dimension = entity.dimension;
    entity.triggerEvent("shapescape_ext:stroll");
    playEatingAnimation(entity);
    let viewVector = Vec3.from(entity.getViewDirection());
    let shitVector = Vec3.from(entity.location).add(
      viewVector.multiply(-1).multiply(3)
    );
    let shitVectorBlock;
    try {
      shitVectorBlock = dimension.getBlockFromRay(
        { x: shitVector.x, y: shitVector.y + 1, z: shitVector.z },
        { x: 0, y: -1, z: 0 },
        {
          maxDistance: 6,
          includePassableBlocks: false,
          includeLiquidBlocks: false
        }
      );
    } catch {
    }
    if (shitVectorBlock && shitVectorBlock.block.typeId !== "shapescape_ext:skyreach_manure_block") {
      let blockToReplace;
      try {
        blockToReplace = dimension.getBlock({
          x: shitVectorBlock.block.location.x,
          y: shitVectorBlock.block.location.y + 1,
          z: shitVectorBlock.block.location.z
        });
      } catch {
      }
      if (!blockToReplace)
        return;
      if (blockToReplace.typeId === "minecraft:light_block" || blockToReplace.isAir || blockToReplace.isLiquid) {
        dimension.setBlockType(
          {
            x: shitVectorBlock.block.location.x,
            y: shitVectorBlock.block.location.y + 1,
            z: shitVectorBlock.block.location.z
          },
          "shapescape_ext:skyreach_manure_block"
        );
      }
    }
  }
}
world34.afterEvents.playerInteractWithEntity.subscribe((event) => {
  const player = event.player;
  const itemStack = event.beforeItemStack;
  const entity = event.target;
  if (!itemStack || !player || !entity || entity.typeId !== "shapescape_ext:skyreach" || !itemStack.typeId.includes("leaves") || !itemStack.typeId.includes("minecraft:"))
    return;
  playEatingAnimation(entity);
});
function playEatingAnimation(entity) {
  const baby = entity.getComponent(
    "minecraft:is_baby"
  );
  if (!entity.hasTag(TAG10)) {
    entity.addTag(TAG10);
    if (baby) {
      entity.playAnimation(
        "animation.shapescape_ext.skyreach_baby.breeding_layer",
        {
          blendOutTime: 0.1
        }
      );
    } else {
      entity.playAnimation("animation.shapescape_ext.skyreach.breeding_layer", {
        blendOutTime: 0.1
      });
    }
    system33.runTimeout(() => {
      entity.removeTag(TAG10);
    }, 20 * 2.5);
  }
}

// data/system_template_esbuild/subscripts/skyreach_manure.ts
import {
  system as system34,
  world as world35,
  ItemStack as ItemStack4
} from "@minecraft/server";
var CROPS2 = [
  "minecraft:wheat",
  "minecraft:carrots",
  "minecraft:potatoes",
  "minecraft:beetroot",
  "minecraft:melon_stem",
  "minecraft:pumpkin_stem",
  "minecraft:sweet_berry_bush",
  "minecraft:cocoa",
  "minecraft:pink_petals",
  "minecraft:wildflowers",
  "minecraft:mangrove_propagule"
];
var SAPLINGS2 = [
  "minecraft:acacia_sapling",
  "minecraft:birch_sapling",
  "minecraft:cherry_sapling",
  "minecraft:dark_oak_sapling",
  "minecraft:jungle_sapling",
  "minecraft:oak_sapling",
  "minecraft:pale_oak_sapling",
  "minecraft:spruce_sapling"
];
var VERTICAL_PLANTS_UP2 = [
  "minecraft:reeds",
  "minecraft:bamboo_sapling",
  "minecraft:bamboo",
  "minecraft:kelp",
  "minecraft:twisting_vines"
];
var GROW_FRUITS2 = ["minecraft:cave_vines"];
var VERTICAL_PLANTS_DOWN2 = ["minecraft:weeping_vines"];
var BLOCKS_TO_DROP = [
  "minecraft:sunflower",
  "minecraft:lilac",
  "minecraft:rose_bush",
  "minecraft:peony"
];
var BLOCKS_TO_SPREAD = [
  "minecraft:bush",
  "minecraft:firefly_bush",
  "minecraft:tall_dry_grass"
];
var BLOCKS_TO_REPLACE = [
  {
    oldBlock: "minecraft:short_dry_grass",
    newBlock: "minecraft:tall_dry_grass"
  }
];
world35.beforeEvents.itemUseOn.subscribe((event) => {
  const block = event.block;
  const player = event.source;
  let itemStack = event.itemStack;
  if (event.isFirstEvent && itemStack.typeId === "shapescape_ext:skyreach_manure_item") {
    const dimenstion = block.dimension;
    const locationsToGrow = [];
    locationsToGrow.push(block.location);
    locationsToGrow.push(block.north(1)?.location);
    locationsToGrow.push(block.south(1)?.location);
    locationsToGrow.push(block.north(1)?.east(1)?.location);
    locationsToGrow.push(block.north(1)?.west(1)?.location);
    locationsToGrow.push(block.south(1)?.east(1)?.location);
    locationsToGrow.push(block.south(1)?.west(1)?.location);
    locationsToGrow.push(block.east(1)?.location);
    locationsToGrow.push(block.west(1)?.location);
    locationsToGrow.push(block.above(1)?.location);
    locationsToGrow.push(block.above(1)?.north(1)?.location);
    locationsToGrow.push(block.above(1)?.south(1)?.location);
    locationsToGrow.push(block.above(1)?.north(1)?.east(1)?.location);
    locationsToGrow.push(block.above(1)?.north(1)?.west(1)?.location);
    locationsToGrow.push(block.above(1)?.south(1)?.east(1)?.location);
    locationsToGrow.push(block.above(1)?.south(1)?.west(1)?.location);
    locationsToGrow.push(block.above(1)?.east(1)?.location);
    locationsToGrow.push(block.above(1)?.west(1)?.location);
    locationsToGrow.push(block.below(1)?.location);
    locationsToGrow.push(block.below(1)?.north(1)?.location);
    locationsToGrow.push(block.below(1)?.south(1)?.location);
    locationsToGrow.push(block.below(1)?.north(1)?.east(1)?.location);
    locationsToGrow.push(block.below(1)?.north(1)?.west(1)?.location);
    locationsToGrow.push(block.below(1)?.south(1)?.east(1)?.location);
    locationsToGrow.push(block.below(1)?.south(1)?.west(1)?.location);
    locationsToGrow.push(block.below(1)?.east(1)?.location);
    locationsToGrow.push(block.below(1)?.west(1)?.location);
    system34.run(() => {
      let index = 0;
      if (BLOCKS_TO_DROP.includes(block.typeId)) {
        dropItem(block);
        player.runCommandAsync("/clear @s shapescape_ext:skyreach_manure_item 0 1");
        return;
      }
      for (const location of locationsToGrow) {
        if (!location)
          continue;
        let block2;
        try {
          block2 = dimenstion.getBlock(location);
        } catch {
        }
        if (!block2)
          continue;
        if (BLOCKS_TO_SPREAD.includes(block2.typeId)) {
          spreadBlock(block2);
          index++;
          continue;
        }
        if (BLOCKS_TO_REPLACE.some((object) => object.oldBlock === block2.typeId)) {
          let newBlockId = BLOCKS_TO_REPLACE.find(
            (object) => object.oldBlock === block2.typeId
          ).newBlock;
          replaceBlock(block2, newBlockId);
          index++;
          continue;
        }
        if (CROPS2.includes(block2.typeId)) {
          try {
            growVanillaCrops2(block2);
            index++;
          } catch {
          }
          continue;
        }
        if (SAPLINGS2.includes(block2.typeId)) {
          growVanillaSaplings2(block2);
          index++;
          continue;
        }
        if (VERTICAL_PLANTS_UP2.includes(block2.typeId)) {
          growVerticalPlantsUp2(block2);
          index++;
          continue;
        }
        if (VERTICAL_PLANTS_DOWN2.includes(block2.typeId)) {
          growVerticalPlantsDown2(block2);
          index++;
          continue;
        }
        if (GROW_FRUITS2.includes(block2.typeId)) {
          growFruits2(block2);
          index++;
          continue;
        }
        if (block2.typeId.includes("dripleaf") && block2.typeId.includes("minecraft:")) {
          dripleaf2(block2);
          index++;
          continue;
        }
        if (block2.typeId.includes("minecraft:dirt_with_roots")) {
          rootedDirt2(block2);
          index++;
          continue;
        }
        if (block2.typeId.includes("minecraft:mangrove_leaves")) {
          mangroveLeaves2(block2);
          index++;
          continue;
        }
        if (block2.typeId.includes("minecraft:torchflower") || block2.typeId.includes("minecraft:pitcher")) {
          snifferPlants2(block2);
          index++;
          continue;
        }
      }
      if (index > 0) {
        player.runCommandAsync("/clear @s shapescape_ext:skyreach_manure_item 0 1");
      }
    });
  }
});
function snifferPlants2(block) {
  const dimension = block.dimension;
  const { x, y, z } = block.location;
  const permutations = block.permutation.getAllStates();
  for (const permutation of Object.keys(permutations)) {
    if (permutation !== "growth")
      continue;
    const oldvalue = block.permutation.getState(permutation);
    let newPermutation;
    newPermutation = block.permutation.withState(permutation, oldvalue + 1);
    block.dimension.setBlockPermutation(block.location, newPermutation);
    if (block.permutation.getState(permutation) === 0) {
      newPermutation = block.permutation.withState(permutation, oldvalue);
      block.dimension.setBlockPermutation(block.location, newPermutation);
    } else if (oldvalue + 1 > 1 && block.typeId.includes("torchflower")) {
      block.setType("minecraft:torchflower");
    } else if (oldvalue + 1 > 2 && block.typeId.includes("pitcher") && block.permutation.getState("upper_block_bit") === false) {
      const blockAbove = dimension.getBlock({ x, y: y + 1, z });
      if (!blockAbove)
        return;
      if (blockAbove.isAir) {
        blockAbove.setType("minecraft:pitcher_crop");
        blockAbove.setPermutation(
          blockAbove.permutation.withState("upper_block_bit", true)
        );
        blockAbove.setPermutation(
          blockAbove.permutation.withState("growth", 2)
        );
      }
    }
    VFX2(block);
  }
}
function rootedDirt2(block) {
  const dimension = block.dimension;
  const { x, y, z } = block.location;
  try {
    const blockAbove = dimension.getBlock({ x, y: y + 1, z });
    const blockBelow = dimension.getBlock({ x, y: y - 1, z });
    if (!blockBelow || !blockAbove)
      return;
    VFX2(blockAbove);
    if (blockBelow.isAir) {
      blockBelow.setType("minecraft:hanging_roots");
    }
  } catch {
  }
}
function mangroveLeaves2(block) {
  const dimension = block.dimension;
  const { x, y, z } = block.location;
  try {
    const blockAbove = dimension.getBlock({ x, y: y + 1, z });
    const blockBelow = dimension.getBlock({ x, y: y - 1, z });
    if (!blockBelow || !blockAbove)
      return;
    VFX2(blockAbove);
    if (blockBelow.isAir) {
      blockBelow.setType("minecraft:mangrove_propagule");
      blockBelow.setPermutation(
        blockBelow.permutation.withState("hanging", true)
      );
    }
  } catch {
  }
}
function dripleaf2(block) {
  VFX2(block);
  const dimension = block.dimension;
  const { x, y, z } = block.location;
  if (block.typeId.includes("big")) {
    try {
      for (let i = 0; i < 384; i++) {
        const blockAbove = dimension.getBlock({ x, y: y + i, z });
        if (!blockAbove)
          continue;
        if (blockAbove.isAir || y + i == 320) {
          blockAbove.setType("minecraft:big_dripleaf");
          break;
        }
      }
    } catch {
    }
  } else {
    const upperBlockBit = block.permutation.getState("upper_block_bit");
    if (!upperBlockBit) {
      const blockAbove = dimension.getBlock({ x, y: y + 1, z });
      if (!blockAbove)
        return;
      block.setType("minecraft:big_dripleaf");
      blockAbove.setType("minecraft:big_dripleaf");
    }
  }
}
function growFruits2(block) {
  VFX2(block);
  const dimension = block.dimension;
  const { x, y, z } = block.location;
  if (block.typeId === "minecraft:cave_vines") {
    try {
      const blockBelow = dimension.getBlock({ x, y: y - 1, z });
      if (!blockBelow)
        return;
      if (blockBelow.typeId.includes("cave_vines")) {
        block.setType("minecraft:cave_vines_body_with_berries");
      } else {
        block.setType("minecraft:cave_vines_head_with_berries");
      }
    } catch {
    }
  }
}
function growVerticalPlantsDown2(block) {
  VFX2(block);
  const HEIGHT_TO_GROW = Math.round(16 * Math.random() / 2);
  let blockingBlockLocation;
  blockingBlockLocation = block.dimension.getBlockFromRay(
    block.location,
    { x: 0, y: -1, z: 0 },
    {
      maxDistance: HEIGHT_TO_GROW,
      includePassableBlocks: true,
      includeLiquidBlocks: true
    }
  )?.block.location;
  if (!blockingBlockLocation) {
    blockingBlockLocation = {
      x: block.location.x,
      y: block.location.y - HEIGHT_TO_GROW,
      z: block.location.z
    };
  }
  block.dimension.runCommandAsync(
    `fill ${block.x} ${block.y} ${block.z} ${blockingBlockLocation.x} ${blockingBlockLocation.y} ${blockingBlockLocation.z} ${block.typeId} [] replace air []`
  );
}
function growVerticalPlantsUp2(block) {
  VFX2(block);
  const dimension = block.dimension;
  const { x, y, z } = block.location;
  const HEIGHT = block.typeId.includes("bamboo") || block.typeId.includes("kelp") || block.typeId.includes("twisting_vines") ? 16 : 3;
  let currentHeight = 0;
  for (let i = 1; i < HEIGHT; i++) {
    let blockToCheck;
    try {
      blockToCheck = dimension.getBlock({ x, y: y - i, z });
    } catch {
    }
    if (!blockToCheck)
      continue;
    if (!VERTICAL_PLANTS_UP2.includes(blockToCheck.typeId)) {
      currentHeight = i;
      break;
    }
    currentHeight = HEIGHT;
  }
  const HEIGHT_TO_GROW = block.typeId.includes("bamboo") || block.typeId.includes("kelp") || block.typeId.includes("twisting_vines") ? Math.round((16 - currentHeight) * Math.random()) : 3 - currentHeight;
  let blockTypeID = block.typeId.replace("_sapling", "");
  let blockingBlockLocation;
  if (blockTypeID.includes("kelp")) {
    blockingBlockLocation = block.dimension.getBlockFromRay(
      block.location,
      { x: 0, y: 1, z: 0 },
      {
        maxDistance: HEIGHT_TO_GROW,
        includePassableBlocks: false,
        includeLiquidBlocks: false
      }
    )?.block.location;
  } else {
    blockingBlockLocation = block.dimension.getBlockFromRay(
      block.location,
      { x: 0, y: 1, z: 0 },
      {
        maxDistance: HEIGHT_TO_GROW,
        includePassableBlocks: true,
        includeLiquidBlocks: false
      }
    )?.block.location;
  }
  if (!blockingBlockLocation) {
    blockingBlockLocation = {
      x: block.location.x,
      y: block.location.y + HEIGHT_TO_GROW,
      z: block.location.z
    };
  }
  if (blockTypeID.includes("kelp")) {
    block.dimension.runCommandAsync(
      `fill ${block.x} ${block.y} ${block.z} ${blockingBlockLocation.x} ${blockingBlockLocation.y} ${blockingBlockLocation.z} ${blockTypeID} [] replace water []`
    );
    block.dimension.runCommandAsync(
      `fill ${block.x} ${block.y} ${block.z} ${blockingBlockLocation.x} ${blockingBlockLocation.y} ${blockingBlockLocation.z} ${blockTypeID} [] replace flowing_water []`
    );
  } else {
    block.dimension.runCommandAsync(
      `fill ${block.x} ${block.y} ${block.z} ${blockingBlockLocation.x} ${blockingBlockLocation.y} ${blockingBlockLocation.z} ${blockTypeID} [] replace air []`
    );
  }
}
function growVanillaCrops2(block) {
  const permutations = block.permutation.getAllStates();
  for (const permutation of Object.keys(permutations)) {
    if (permutation !== "growth" && permutation !== "age" && permutation !== "propagule_stage") {
      continue;
    }
    const oldvalue = block.permutation.getState(permutation);
    let newPermutation;
    if ((block.typeId === "minecraft:pink_petals" || block.typeId === "minecraft:wildflowers") && oldvalue > 2) {
      const itemStack = new ItemStack4(block.typeId, 1);
      block.dimension.spawnItem(itemStack, block.center());
    } else {
      newPermutation = block.permutation.withState(permutation, oldvalue + 1);
      block.dimension.setBlockPermutation(block.location, newPermutation);
      if (block.permutation.getState(permutation) === 0) {
        newPermutation = block.permutation.withState(permutation, oldvalue);
        block.dimension.setBlockPermutation(block.location, newPermutation);
      }
    }
    VFX2(block);
  }
}
function growVanillaSaplings2(block) {
  const permutations = block.permutation.getAllStates();
  for (const permutation of Object.keys(permutations)) {
    if (permutation !== "age_bit")
      continue;
    let newPermutation;
    newPermutation = block.permutation.withState(permutation, true);
    block.dimension.setBlockPermutation(block.location, newPermutation);
    VFX2(block);
  }
}
function dropItem(block) {
  VFX2(block);
  const randInt2 = Math.round(Math.random() * 5);
  const itemStack = new ItemStack4(block.typeId, randInt2 < 1 ? 1 : randInt2);
  block.dimension.spawnItem(itemStack, block.center());
}
function spreadBlock(block) {
  VFX2(block);
  const adjacentBlocks = [
    block.north(1),
    block.south(1),
    block.east(1),
    block.west(1)
  ];
  for (const adjacent of adjacentBlocks) {
    if (!adjacent)
      continue;
    const belowBlock = adjacent.below(1);
    if (adjacent.isAir && belowBlock?.typeId.includes("minecraft") && !belowBlock?.typeId.includes("path") && (belowBlock?.typeId.includes("dirt") || belowBlock?.typeId.includes("grass") || belowBlock?.typeId.includes("podzol") || belowBlock?.typeId.includes("farmland"))) {
      if (block.typeId === "minecraft:tall_dry_grass") {
        adjacent.setType("minecraft:short_dry_grass");
      } else {
        adjacent.setType(block.typeId);
      }
      break;
    }
  }
}
function replaceBlock(block, newBlockId) {
  VFX2(block);
  block.setType(newBlockId);
}
function VFX2(block) {
  block.dimension.spawnParticle(
    "minecraft:crop_growth_emitter",
    block.center()
  );
  block.dimension.playSound("item.bone_meal.use", block.center());
}
world35.beforeEvents.worldInitialize.subscribe((event) => {
  event.blockComponentRegistry.registerCustomComponent(
    "shapescape_ext:skyreach_manure_block",
    {
      onTick(event2) {
        const block = event2.block;
        const dimension = block.dimension;
        dimension.spawnParticle(
          `shapescape_ext:skyreach_manure_block`,
          block.center()
        );
      }
    }
  );
});

// data/system_template_esbuild/subscripts/spinosaurus_item.ts
import {
  EasingType,
  system as system35,
  world as world36
} from "@minecraft/server";
var COOLDOWN = 20 * 60 - 1;
var TAG11 = "shapescape_ext:spinosaurus_item";
world36.afterEvents.itemUse.subscribe((event) => {
  const player = event.source;
  const item = event.itemStack;
  if (item.typeId === "shapescape_ext:spinosaurus_item" && player.isValid() && player.getItemCooldown("shapescape_ext:spinosaurus_item") >= COOLDOWN) {
    playerIsDiggingIn(player);
  }
});
function playerIsDiggingIn(player) {
  const position = player.location;
  const location = {
    x: position.x,
    y: position.y - 3,
    z: position.z
  };
  player.dimension.playSound("shapescape_ext.spinosaurus_item.digging_in", {
    x: player.location.x,
    y: player.location.y,
    z: player.location.z
  });
  player.dimension.spawnParticle("shapescape_ext:spinosaurus_item_dig_up", {
    x: position.x,
    y: position.y,
    z: position.z
  });
  player.addTag(TAG11);
  player.addEffect("minecraft:water_breathing", 20 * 10, {
    showParticles: false
  });
  player.addEffect("minecraft:slow_falling", 20 * 10, {
    showParticles: false
  });
  player.teleport(location);
  player.camera.setCamera("minecraft:free", {
    easeOptions: {
      easeType: EasingType.Linear
    },
    location: {
      x: position.x,
      y: position.y + 12,
      z: position.z
    },
    facingEntity: player
  });
  const intervalId = system35.runInterval(() => {
    if (player.isJumping) {
      playerIsDiggingOut(player);
      system35.clearRun(intervalId);
    }
  }, 1);
  system35.runTimeout(() => {
    system35.clearRun(intervalId);
    if (player.hasTag(TAG11)) {
      playerIsDiggingOut(player);
    }
  }, 20 * 10);
}
function playerIsDiggingOut(player) {
  player.removeTag(TAG11);
  player.camera.clear();
  const position = player.location;
  const location = {
    x: position.x,
    y: position.y + 3,
    z: position.z
  };
  player.teleport(location);
  player.addEffect("minecraft:water_breathing", 1, {
    showParticles: false
  });
  player.removeEffect("minecraft:slow_falling");
  player.dimension.playSound("shapescape_ext.spinosaurus_item.digging_out", {
    x: player.location.x,
    y: player.location.y,
    z: player.location.z
  });
}

// data/system_template_esbuild/subscripts/spinosaurus_eating.ts
import { world as world37 } from "@minecraft/server";
var tamingItem5 = ["minecraft:chorus_fruit"];
world37.afterEvents.playerInteractWithEntity.subscribe((event) => {
  const player = event.player;
  const itemStack = event.beforeItemStack;
  const entity = event.target;
  if (!itemStack || !player || !entity || entity.typeId !== "shapescape_ext:spinosaurus" || !tamingItem5.includes(itemStack.typeId))
    return;
  entity.playAnimation("animation.shapescape_ext.spinosaurus.chewing_layer");
});

// data/system_template_esbuild/subscripts/stegosaurus_eating.ts
import { world as world38, system as system36 } from "@minecraft/server";
var TAG12 = "shapescape_ext_stegosaurus_eating";
world38.afterEvents.playerInteractWithEntity.subscribe((event) => {
  const player = event.player;
  const itemStack = event.beforeItemStack;
  const entity = event.target;
  if (!itemStack || !player || !entity || entity.typeId !== "shapescape_ext:stegosaurus" || itemStack.typeId !== "minecraft:apple")
    return;
  const baby = entity.getComponent(
    "minecraft:is_baby"
  );
  if (!entity.hasTag(TAG12)) {
    entity.addTag(TAG12);
    if (baby) {
      entity.playAnimation(
        "animation.shapescape_ext.stegosaurus_baby.chewing_layer",
        {
          blendOutTime: 0.1
        }
      );
    } else {
      entity.playAnimation("animation.shapescape_ext.stegosaurus.chewing_layer", {
        blendOutTime: 0.1
      });
    }
    system36.runTimeout(() => {
      entity.removeTag(TAG12);
    }, 20 * 1.5);
  }
});

// data/system_template_esbuild/subscripts/stegosaurus_harvests_wood.ts
import {
  system as system37,
  world as world39,
  GameMode as GameMode7,
  EntityDamageCause as EntityDamageCause3
} from "@minecraft/server";
var includedBlocks = [
  "minecraft:oak_wood",
  "minecraft:spruce_wood",
  "minecraft:birch_wood",
  "minecraft:jungle_wood",
  "minecraft:acacia_wood",
  "minecraft:dark_oak_wood",
  "minecraft:mangrove_wood",
  "minecraft:cherry_wood",
  "minecraft:pale_oak_wood",
  "minecraft:crimson_hyphae",
  "minecraft:warped_hyphae",
  "minecraft:oak_log",
  "minecraft:spruce_log",
  "minecraft:birch_log",
  "minecraft:jungle_log",
  "minecraft:acacia_log",
  "minecraft:dark_oak_log",
  "minecraft:mangrove_log",
  "minecraft:cherry_log",
  "minecraft:pale_oak_log",
  "minecraft:crimson_stem",
  "minecraft:warped_stem"
];
var leavesBlocks = [
  "minecraft:acacia_leaves",
  "minecraft:azalea_leaves",
  "minecraft:azalea_leaves_flowered",
  "minecraft:birch_leaves",
  "minecraft:cherry_leaves",
  "minecraft:dark_oak_leaves",
  "minecraft:jungle_leaves",
  "minecraft:mangrove_leaves",
  "minecraft:oak_leaves",
  "minecraft:pale_oak_leaves",
  "minecraft:spruce_leaves"
];
system37.afterEvents.scriptEventReceive.subscribe((event) => {
  const { sourceEntity } = event;
  if (event.id !== "shapescape_ext:harvests_wood" || sourceEntity === void 0 || !sourceEntity.isValid() || sourceEntity.typeId !== "shapescape_ext:stegosaurus") {
    return;
  }
  harvestsWood(sourceEntity);
});
function harvestsWood(entity) {
  entity.setProperty("shapescape_ext:harvests_wood", false);
  const dimension = entity.dimension;
  const radius = 6;
  const height = 20;
  const location = entity.location;
  entity.runCommandAsync(
    `playsound shapescape_ext.stegosaurus.harvesting @a ${location.x} ${location.y} ${location.z} 1 1 0.5`
  );
  system37.runTimeout(() => {
    destroyBlocks2(Vec3.from(location), dimension, radius, height, entity);
    dealDeamage(entity);
  }, 20 * 0.2);
  system37.runTimeout(() => {
    entity.triggerEvent("shapescape_ext:movement");
  }, 20 * 1.75);
}
function destroyBlocks2(location, dimension, radius, height, entity) {
  for (let dx = -radius; dx <= radius; dx++) {
    for (let dz = -radius; dz <= radius; dz++) {
      for (let dy = -2; dy <= height; dy++) {
        const distance = Math.sqrt(dx * dx + dz * dz);
        if (distance > radius)
          continue;
        const blockPos1 = {
          x: Math.floor(location.x + dx),
          y: Math.floor(location.y + dy),
          z: Math.floor(location.z + dz)
        };
        const blockPos2 = {
          x: Math.floor(location.x - dx),
          y: Math.floor(location.y + dy),
          z: Math.floor(location.z - dz)
        };
        const block1 = dimension.getBlock(blockPos1);
        const block2 = dimension.getBlock(blockPos2);
        try {
          if (block1 && includedBlocks.includes(block1.typeId)) {
            entity.runCommandAsync(
              `setblock ${blockPos1.x} ${blockPos1.y} ${blockPos1.z} air [] destroy`
            );
          }
          if (block2 && includedBlocks.includes(block2.typeId)) {
            entity.runCommandAsync(
              `setblock ${blockPos2.x} ${blockPos2.y} ${blockPos2.z} air [] destroy`
            );
          }
          if (block1 && leavesBlocks.includes(block1.typeId)) {
            entity.runCommandAsync(
              `setblock ${blockPos1.x} ${blockPos1.y} ${blockPos1.z} air []`
            );
          }
          if (block2 && leavesBlocks.includes(block2.typeId)) {
            entity.runCommandAsync(
              `setblock ${blockPos2.x} ${blockPos2.y} ${blockPos2.z} air []`
            );
          }
        } catch {
        }
      }
    }
  }
}
function dealDeamage(entity) {
  const dimension = entity.dimension;
  const radius = 5;
  const rotation = entity.getRotation();
  const angle = (rotation.y + 180) * Math.PI / 180;
  const attackLocation = {
    x: entity.location.x + 2 * Math.sin(angle),
    // Front of the entity
    y: entity.location.y,
    z: entity.location.z - 2 * Math.cos(angle)
    // Front of the entity
  };
  const ownerName = getOwnerName2(entity);
  const riderName = getRider2(entity);
  const explosion = {
    entityTargetSelector: {
      excludeTypes: [
        "minecraft:item",
        "minecraft:arrow",
        "shapescape_ext:stegosaurus"
      ],
      excludeFamilies: ["inanimate"],
      excludeNames: [ownerName]
    },
    playerTargetSelector: {
      excludeGameModes: [GameMode7.creative, GameMode7.spectator],
      excludeNames: [ownerName, riderName]
    },
    dimension,
    radius,
    explosionDamage: [15, 20],
    knockbackStrength: [0.8, 0.9],
    knockbackUpBias: 1.6,
    position: {
      x: attackLocation.x,
      y: attackLocation.y + 1,
      z: attackLocation.z
    },
    wallBangRadius: 2,
    damageOptions: {
      damagingEntity: entity,
      cause: EntityDamageCause3.entityExplosion
    }
  };
  createSilentExplosion(explosion);
}
function getOwnerName2(entity) {
  const tameable = entity.getComponent(
    "minecraft:tameable"
  );
  if (tameable && tameable.tamedToPlayer) {
    const players = world39.getAllPlayers();
    const owner = players.find(
      (player) => player.id === tameable.tamedToPlayerId
    );
    return owner ? owner.name : "Unknown";
  }
  return "Unknown";
}
function getRider2(entity) {
  const rideableComp = entity.getComponent(
    "minecraft:rideable"
  );
  if (rideableComp === void 0)
    return "Unknown";
  if (rideableComp.getRiders().length > 0) {
    const players = world39.getAllPlayers();
    const rider = players.find(
      (player) => player.id === rideableComp.getRiders()[0].id
    );
    return rider ? rider.name : "Unknown";
  }
  return "Unknown";
}

// data/system_template_esbuild/subscripts/thorncrest.ts
import { system as system39 } from "@minecraft/server";

// data/system_template_esbuild/piston-breakable-block/index.ts
import {
  system as system38
} from "@minecraft/server";
var blocksPlacedByPlayer = /* @__PURE__ */ new Set();
function pistonBreakableBeforeOnPlayerPlace(event) {
  const { x, y, z } = event.block.location;
  const locationStr = `${x} ${y} ${z}`;
  blocksPlacedByPlayer.add(locationStr);
  system38.runTimeout(() => {
    blocksPlacedByPlayer.delete(locationStr);
  }, 1);
}
function pistonBreakableCommandPlace(location) {
  const { x, y, z } = location;
  const locationStr = `${x} ${y} ${z}`;
  blocksPlacedByPlayer.add(locationStr);
  system38.runTimeout(() => {
    blocksPlacedByPlayer.delete(locationStr);
  }, 1);
}
function pistonBreakableOnPlace(event) {
  const { x, y, z } = event.block.location;
  const locationStr = `${x} ${y} ${z}`;
  if (!blocksPlacedByPlayer.has(locationStr)) {
    event.block.dimension.runCommand(`setblock ${x} ${y} ${z} air[] destroy`);
    return false;
  }
  return true;
}

// data/system_template_esbuild/subscripts/thorncrest.ts
var thorncrestCanPlaceOn = ["minecraft:grass_block", "minecraft:dirt", "minecraft:coarse_dirt", "minecraft:podzol", "minecraft:farmland", "minecraft:mycelium", "minecraft:grass", "minecraft:dirt_with_roots", "minecraft:mud", "minecraft:moss_block"];
var thorncrestCanReplace = ["minecraft:air", "minecraft:light_block", "minecraft:water", "minecraft:flowing_water", "minecraft:short_grass", "minecraft:tall_grass"];
var ATTACK_DISTANCE3 = 4;
var ATTACK_RADIUS3 = 3.5;
var ATTACK_DAMAGE3 = 15;
system39.afterEvents.scriptEventReceive.subscribe((event) => {
  const entity = event.sourceEntity;
  if (event.id !== "shapescape_ext:thorncrest_place_block" || entity === void 0 || !entity.isValid() || entity.typeId !== "shapescape_ext:thorncrest") {
    return;
  }
  const location = entity.location;
  const dimension = entity.dimension;
  const block = dimension.getBlock(location);
  if (block === void 0) {
    return;
  }
  const blockBelow = block.below(1);
  if (blockBelow === void 0) {
    return;
  }
  if (thorncrestCanReplace.includes(block.typeId) && thorncrestCanPlaceOn.includes(blockBelow.typeId)) {
    pistonBreakableCommandPlace(block.location);
    dimension.setBlockType(location, "shapescape_ext:thorncrest_bush");
  }
});
system39.afterEvents.scriptEventReceive.subscribe((event) => {
  const message = event.message;
  const messageID = event.id;
  const entity = event.sourceEntity;
  if (entity && messageID === "shapescape_ext:thorncrest" && message === "attack") {
    system39.runTimeout(() => {
      tamedAttack3(entity);
      entity.playAnimation("animation.shapescape_ext.thorncrest.attack", {
        blendOutTime: 1
      });
    }, 20 * 0.29);
  }
});
function tamedAttack3(entity) {
  const viewDirection = entity.getViewDirection();
  const dimension = entity.dimension;
  const location = entity.location;
  const positionInFront = Vec3.from(viewDirection).multiply({ x: ATTACK_DISTANCE3, y: 0, z: ATTACK_DISTANCE3 }).add(location);
  const entitiesToDamage = dimension.getEntities({
    location: positionInFront,
    maxDistance: ATTACK_RADIUS3,
    excludeFamilies: ["projectile", "inanimate"],
    excludeTypes: ["minecraft:item", "minecraft:arrow"]
  });
  for (const entity2 of entitiesToDamage) {
    entity2.applyDamage(ATTACK_DAMAGE3);
    entity2.applyImpulse(
      Vec3.from(viewDirection).multiply({
        x: 2,
        y: 2,
        z: 2
      })
    );
  }
  system39.runTimeout(() => {
    entity.setProperty("shapescape_ext:state", "default");
  }, 20 * 0.6);
}

// data/system_template_esbuild/subscripts/thorncrest_eating.ts
import { world as world41, system as system40 } from "@minecraft/server";
var TAG13 = "shapescape_ext_thorncrest_eating";
world41.afterEvents.playerInteractWithEntity.subscribe((event) => {
  const player = event.player;
  const itemStack = event.beforeItemStack;
  const entity = event.target;
  if (!itemStack || !player || !entity || entity.typeId !== "shapescape_ext:thorncrest" || itemStack.typeId !== "shapescape_ext:thorncrest_bush_berry")
    return;
  const baby = entity.getComponent(
    "minecraft:is_baby"
  );
  if (!entity.hasTag(TAG13)) {
    entity.addTag(TAG13);
    if (baby) {
      entity.playAnimation(
        "animation.shapescape_ext.thorncrest_baby.chewing_layer",
        {
          blendOutTime: 0.1
        }
      );
    } else {
      entity.playAnimation("animation.shapescape_ext.thorncrest.chewing_layer", {
        blendOutTime: 0.1
      });
    }
    system40.runTimeout(() => {
      entity.removeTag(TAG13);
    }, 20 * 2);
  }
});

// data/system_template_esbuild/subscripts/velociraptor_nether_eat.ts
import { world as world42, system as system41 } from "@minecraft/server";
var TAG14 = "shapescape_ext_velociraptor_nether_eating";
var tamingItem6 = [
  "minecraft:chicken",
  "minecraft:cooked_chicken",
  "minecraft:beef",
  "minecraft:cooked_beef",
  "minecraft:muttonRaw",
  "minecraft:muttonCooked",
  "minecraft:porkchop",
  "minecraft:cooked_porkchop",
  "minecraft:rotten_flesh"
];
world42.afterEvents.playerInteractWithEntity.subscribe((event) => {
  const { player, target, itemStack } = event;
  if (!itemStack || !player || !target || target.typeId !== "shapescape_ext:velociraptor_nether" || !tamingItem6.includes(itemStack.typeId))
    return;
  const baby = target.getComponent("minecraft:is_baby");
  if (!target.hasTag(TAG14)) {
    target.addTag(TAG14);
    if (baby) {
      target.playAnimation("animation.shapescape_ext.velociraptor_nether_baby.chewing_layer", {
        blendOutTime: 0.2
      });
    } else {
      target.playAnimation("animation.shapescape_ext.velociraptor_nether.chewing_layer", {
        blendOutTime: 0.2
      });
    }
    system41.runTimeout(() => {
      target.removeTag(TAG14);
    }, 20 * 1.2);
  }
});
world42.afterEvents.entityLoad.subscribe((event) => {
  if (event.entity.hasTag(TAG14)) {
    event.entity.removeTag(TAG14);
  }
});

// data/system_template_esbuild/subscripts/velociraptor_nether_gliding.ts
import {
  world as world43,
  system as system42,
  TicksPerSecond as TicksPerSecond5,
  EntityComponentTypes as EntityComponentTypes6
} from "@minecraft/server";
system42.afterEvents.scriptEventReceive.subscribe((event) => {
  const message = event.message;
  const messageID = event.id;
  const entity = event.sourceEntity;
  if (entity && messageID === "shapescape_ext:velociraptor_nether" && message === "gliding") {
    glide(entity);
  }
});
function glide(entity) {
  const baby = entity.getComponent(
    "minecraft:is_baby"
  );
  if (baby) {
    entity.playAnimation(
      `animation.shapescape_ext.velociraptor_nether.glide_start_layer`,
      {
        blendOutTime: 0.75
      }
    );
  } else {
    entity.playAnimation(
      `animation.shapescape_ext.velociraptor_nether_baby.glide_start_layer`,
      {
        blendOutTime: 0.75
      }
    );
  }
  entity.addEffect("minecraft:slow_falling", 5 * TicksPerSecond5, {
    amplifier: 1,
    showParticles: false
  });
  entity.addEffect("minecraft:speed", 3 * TicksPerSecond5, {
    amplifier: 1,
    showParticles: false
  });
  const yRot = entity.getRotation().y;
  let newRotation = Math.random() > 0.5 ? Math.random() * 360 : yRot;
  const riders = entity.getComponent(EntityComponentTypes6.Rideable)?.getRiders();
  if (riders && riders.length > 0) {
    newRotation = yRot;
  }
  entity.setRotation({ x: 0, y: newRotation });
  const viewDir = entity.getViewDirection();
  const direction = Vec3.from(viewDir).setY(1).multiply(3);
  entity.applyImpulse(direction);
}
world43.afterEvents.entityLoad.subscribe((event) => {
  if (event.entity.typeId === "shapescape_ext:velociraptor_nether") {
    event.entity.setProperty("shapescape_ext:gliding", false);
  }
});

// data/system_template_esbuild/subscripts/venomfang_potion.ts
import {
  system as system43,
  world as world44,
  Player as Player17,
  ItemStack as ItemStack5
} from "@minecraft/server";
world44.beforeEvents.playerInteractWithEntity.subscribe((event) => {
  const player = event.player;
  const target = event.target;
  const itemStack = event.itemStack;
  if (!(player instanceof Player17) || !itemStack)
    return;
  if (itemStack.typeId !== "shapescape_ext:venomfang_potion")
    return;
  system43.run(() => {
    player.runCommand(`clear @s shapescape_ext:venomfang_potion 0 1`);
    player.dimension.spawnItem(
      new ItemStack5("minecraft:glass_bottle", 1),
      player.location
    );
    target.addEffect("minecraft:slowness", 10 * 20, {
      amplifier: 2,
      showParticles: true
    });
    target.addEffect("minecraft:weakness", 10 * 20, {
      amplifier: 1,
      showParticles: true
    });
    target.addEffect("minecraft:darkness", 3 * 20, {
      amplifier: 0,
      showParticles: true
    });
  });
});
world44.beforeEvents.itemUse.subscribe((event) => {
  const player = event.source;
  const itemStack = event.itemStack;
  if (!(player instanceof Player17) || !itemStack)
    return;
  if (itemStack.typeId !== "shapescape_ext:venomfang_splash_potion")
    return;
  system43.run(() => {
    player.runCommand(`clear @s shapescape_ext:venomfang_splash_potion 0 1`);
    shoot(player);
  });
});
function shoot(player) {
  const viewDirection = Vec3.from(player.getViewDirection());
  const location = viewDirection.multiply(1.25).add(player.getHeadLocation());
  const projectile = player.dimension.spawnEntity(
    "shapescape_ext:venomfang_splash_potion",
    location
  );
  projectile.applyImpulse(
    viewDirection.add({ x: 0, y: 0.4, z: 0 }).multiply({ x: 0.6, y: 0.6, z: 0.6 })
  );
}
world44.afterEvents.projectileHitEntity.subscribe((event) => {
  const projectile = event.projectile;
  if (projectile.typeId !== "shapescape_ext:venomfang_splash_potion")
    return;
  projectileHit(projectile);
});
world44.afterEvents.projectileHitBlock.subscribe((event) => {
  const projectile = event.projectile;
  if (projectile.typeId !== "shapescape_ext:venomfang_splash_potion")
    return;
  projectileHit(projectile);
});
function projectileHit(projectile) {
  const location = projectile.location;
  const dimension = projectile.dimension;
  projectile.remove();
  const affectedEntities = dimension.getEntities({
    location,
    maxDistance: 4
  });
  dimension.spawnParticle("shapescape_ext:venomfang_splash_potion", location);
  for (const entity of affectedEntities) {
    entity.addEffect("minecraft:slowness", 10 * 20, {
      amplifier: 2,
      showParticles: true
    });
    entity.addEffect("minecraft:poison", 10 * 20, {
      amplifier: 0,
      showParticles: true
    });
    entity.addEffect("minecraft:darkness", 3 * 20, {
      amplifier: 0,
      showParticles: true
    });
  }
}

// data/system_template_esbuild/subscripts/venomfang.ts
import {
  system as system44,
  world as world45
} from "@minecraft/server";
var ANIM_TIME = 0.5;
system44.afterEvents.scriptEventReceive.subscribe((event) => {
  const message = event.message;
  const messageID = event.id;
  const entity = event.sourceEntity;
  if (entity?.isValid() && messageID === "shapescape_ext:venomfang" && message === "spit") {
    entity.setProperty("shapescape_ext:state", "spit");
    system44.runTimeout(() => {
      for (let i = 0; i < 5; i++) {
        system44.runTimeout(() => {
          if (entity?.isValid()) {
            spit(entity);
            entity.dimension.playSound(
              "shapescape_ext.venomfang.ranged_attack",
              entity.location,
              {
                pitch: randInt(9, 11) / 10
              }
            );
          }
        }, i * 2);
      }
    }, ANIM_TIME * 20);
    system44.runTimeout(() => {
      if (entity?.isValid()) {
        entity.setProperty("shapescape_ext:state", "stroll");
      }
    }, 3 * 20);
  }
});
function spit(entity) {
  const viewDirection = Vec3.from(entity.getViewDirection());
  const location = viewDirection.multiply(1.75).add(entity.getHeadLocation());
  const projectile = entity.dimension.spawnEntity(
    "shapescape_ext:venomfang_spit",
    location
  );
  let shootVector = Vec3.from(
    viewDirection.add({ x: 0, y: 0.2, z: 0 }).add({
      x: randInt(-15, 15) / 100,
      y: randInt(-15, 15) / 100,
      z: randInt(-15, 15) / 100
    }).multiply({ x: 0.8, y: 0.8, z: 0.8 })
  );
  projectile.applyImpulse(shootVector);
}
world45.afterEvents.projectileHitEntity.subscribe((event) => {
  const projectile = event.projectile;
  const target = event.getEntityHit().entity;
  if (projectile.typeId !== "shapescape_ext:venomfang_spit" || target?.typeId == "shapescape_ext:venomfang" || !target || !target.isValid())
    return;
  target.addEffect("minecraft:slowness", 3 * 20, {
    amplifier: 1,
    showParticles: true
  });
  target.addEffect("minecraft:weakness", 5 * 20, {
    amplifier: 0,
    showParticles: true
  });
  target.addEffect("minecraft:darkness", 3 * 20, {
    amplifier: 0,
    showParticles: true
  });
});

// data/system_template_esbuild/subscripts/venomfang_eating.ts
import { world as world46, system as system45 } from "@minecraft/server";
var tamingItem7 = ["minecraft:echo_shard", "minecraft:sculk_vein"];
var TAG15 = "shapescape_ext_venomfang_eating";
world46.afterEvents.playerInteractWithEntity.subscribe((event) => {
  const player = event.player;
  const itemStack = event.beforeItemStack;
  const entity = event.target;
  if (!itemStack || !player || !entity || entity.typeId !== "shapescape_ext:venomfang" || !tamingItem7.includes(itemStack.typeId))
    return;
  const baby = entity.getComponent(
    "minecraft:is_baby"
  );
  if (!entity.hasTag(TAG15)) {
    entity.addTag(TAG15);
    if (baby) {
      entity.playAnimation(
        "animation.shapescape_ext.venomfang_baby.chewing_layer",
        {
          blendOutTime: 0.2
        }
      );
    } else {
      entity.playAnimation("animation.shapescape_ext.venomfang.chewing_layer", {
        blendOutTime: 0.2
      });
    }
    system45.runTimeout(() => {
      entity.removeTag(TAG15);
    }, 20 * 2.08);
  }
});

// data/system_template_esbuild/subscripts/flocking_behavior.ts
import {
  system as system46,
  world as world47,
  EntityInitializationCause
} from "@minecraft/server";
var VANILLA_DIMENSIONS = [
  world47.getDimension("overworld"),
  world47.getDimension("nether"),
  world47.getDimension("the_end")
];
var FLOCK_MIN_SIZE = 2;
world47.afterEvents.entitySpawn.subscribe((event) => {
  const { cause, entity } = event;
  if (cause === EntityInitializationCause.Spawned && entity.typeId == "shapescape_ext:void_runner" && !entity.hasTag("shapescape_ext_INITIALIZED")) {
    system46.runTimeout(() => {
      if (!entity || !entity.isValid())
        return;
      const location = entity.location;
      const dimension = entity.dimension;
      entity.addTag("shapescape_ext_INITIALIZED");
      entity.triggerEvent("shapescape_ext:leader");
      let flockSize = Math.floor(Math.random() * 3 + FLOCK_MIN_SIZE);
      for (let i = 0; i < flockSize; i++) {
        let follower = dimension.spawnEntity(
          "shapescape_ext:void_runner",
          location
        );
        follower.triggerEvent("shapescape_ext:follower");
        follower.addTag("shapescape_ext_INITIALIZED");
      }
    }, 1);
  }
});

// data/system_template_esbuild/subscripts/void_runner_eating.ts
import { world as world48, system as system47 } from "@minecraft/server";
var TAG16 = "shapescape_ext_void_runner_eating";
world48.afterEvents.playerInteractWithEntity.subscribe((event) => {
  const player = event.player;
  const itemStack = event.beforeItemStack;
  const entity = event.target;
  if (!itemStack || !player || !entity || entity.typeId !== "shapescape_ext:void_runner" || itemStack.typeId !== "minecraft:chorus_fruit")
    return;
  const baby = entity.getComponent(
    "minecraft:is_baby"
  );
  if (!entity.hasTag(TAG16)) {
    entity.addTag(TAG16);
    if (baby) {
      entity.playAnimation(
        "animation.shapescape_ext.void_runner_baby.chewing_layer",
        {
          blendOutTime: 0.2
        }
      );
    } else {
      entity.playAnimation("animation.shapescape_ext.void_runner.chewing_layer", {
        blendOutTime: 0.2
      });
    }
    system47.runTimeout(() => {
      entity.removeTag(TAG16);
    }, 20 * 1.9);
  }
});

// data/system_template_esbuild/subscripts/void_wing_eating.ts
import { world as world49, system as system48 } from "@minecraft/server";
var TAG17 = "shapescape_ext_void_wing_eating";
world49.afterEvents.playerInteractWithEntity.subscribe((event) => {
  const player = event.player;
  const itemStack = event.beforeItemStack;
  const entity = event.target;
  if (!itemStack || !player || !entity || entity.typeId !== "shapescape_ext:void_wing" || itemStack.typeId !== "minecraft:chorus_fruit")
    return;
  const baby = entity.getComponent(
    "minecraft:is_baby"
  );
  if (!entity.hasTag(TAG17)) {
    entity.addTag(TAG17);
    if (baby) {
      entity.playAnimation(
        "animation.shapescape_ext.void_wing_baby.chewing_layer",
        {
          blendOutTime: 0.2
        }
      );
    } else {
      entity.playAnimation("animation.shapescape_ext.void_wing.chewing_layer", {
        blendOutTime: 0.2
      });
    }
    system48.runTimeout(() => {
      entity.removeTag(TAG17);
    }, 20 * 1.9);
  }
});

// data/system_template_esbuild/subscripts/void_wing.ts
import { system as system49 } from "@minecraft/server";
var ATTACK_DISTANCE4 = 3;
var ATTACK_RADIUS4 = 3;
var ATTACK_DAMAGE4 = 15;
system49.afterEvents.scriptEventReceive.subscribe((event) => {
  const message = event.message;
  const messageID = event.id;
  const entity = event.sourceEntity;
  if (entity && messageID === "shapescape_ext:void_wing" && message === "attack") {
    system49.runTimeout(() => {
      tamedAttack4(entity);
      entity.playAnimation("animation.shapescape_ext.void_wing.attack_layer", {
        blendOutTime: 1
      });
    }, 20 * 0.13);
  }
});
function tamedAttack4(entity) {
  const viewDirection = entity.getViewDirection();
  const dimension = entity.dimension;
  const location = entity.location;
  const tag = `shapescape_ext_${entity.id}`;
  entity.addTag(tag);
  const positionInFront = Vec3.from(viewDirection).multiply({ x: ATTACK_DISTANCE4, y: 0, z: ATTACK_DISTANCE4 }).add(location);
  const entitiesToDamage = dimension.getEntities({
    location: positionInFront,
    maxDistance: ATTACK_RADIUS4,
    excludeFamilies: ["projectile", "inanimate"],
    excludeTypes: ["minecraft:item", "minecraft:arrow"],
    excludeTags: [tag]
  });
  for (const entity2 of entitiesToDamage) {
    entity2.applyDamage(ATTACK_DAMAGE4);
    entity2.applyImpulse(
      Vec3.from(viewDirection).multiply({
        x: 2,
        y: 2,
        z: 2
      })
    );
  }
  system49.runTimeout(() => {
    entity.removeTag(tag);
    entity.setProperty("shapescape_ext:state", "default");
  }, 20 * 0.58);
}

// data/system_template_esbuild/subscripts/wooly_rhino.ts
import {
  system as system50,
  world as world51,
  ItemComponentTypes as ItemComponentTypes2,
  BlockVolume as BlockVolume9
} from "@minecraft/server";
var BIOME_VISUALS_ANIM_TIME = 60;
system50.afterEvents.scriptEventReceive.subscribe((event) => {
  const { id, message, sourceEntity } = event;
  if (id === "shapescape_ext:wooly_rhino" && message === "freeze_water" && sourceEntity) {
    freezeWater(sourceEntity);
  }
  if (id === "shapescape_ext:wooly_rhino" && message === "biome_visuals_switch" && sourceEntity) {
    biomeVisualsSwitch(sourceEntity);
  }
});
function freezeWater(entity) {
  const volumeCenter = Vec3.from(entity.getViewDirection()).multiply(2).setY(0).add(entity.location);
  const from = {
    x: volumeCenter.x - 2,
    y: volumeCenter.y - 1,
    z: volumeCenter.z - 2
  };
  const to = {
    x: volumeCenter.x + 2,
    y: volumeCenter.y + 1,
    z: volumeCenter.z + 2
  };
  const blockVolumeLocations = new BlockVolume9(
    from,
    to
  ).getBlockLocationIterator();
  for (const location of blockVolumeLocations) {
    if (Math.random() < 0.15)
      continue;
    let block;
    try {
      block = entity.dimension.getBlock(location);
    } catch {
    }
    if (!block)
      continue;
    if (block.typeId === "minecraft:water" || block.typeId === "minecraft:flowing_water") {
      block.setType("minecraft:frosted_ice");
    } else {
      continue;
    }
  }
}
function biomeVisualsSwitch(entity) {
  const property = entity.getProperty("shapescape_ext:biome_visuals");
  let newVisualsEvent = "shapescape_ext:biome_visuals_0";
  switch (property) {
    case 0:
      newVisualsEvent = "shapescape_ext:biome_visuals_1";
      break;
    case 1:
      newVisualsEvent = "shapescape_ext:biome_visuals_0";
      break;
    default:
      break;
  }
  system50.runTimeout(() => {
    if (!entity || !entity.isValid())
      return;
    entity.triggerEvent(newVisualsEvent);
  }, BIOME_VISUALS_ANIM_TIME);
}
world51.beforeEvents.playerInteractWithEntity.subscribe((event) => {
  const { player, target, itemStack } = event;
  if (player && itemStack && !itemStack.typeId.includes("frozen") && target && target.typeId === "shapescape_ext:wooly_rhino") {
    const itemFoodComp = itemStack.getComponent(ItemComponentTypes2.Food);
    if (itemFoodComp) {
      system50.run(() => {
        target.dimension.playSound("mob.horse.angry", target.location, {
          pitch: 0.6
        });
        const entities2 = target.dimension.getEntities({
          location: target.location,
          maxDistance: 10
        });
        for (const entity of entities2) {
          if (!entity)
            continue;
          entity.addTag(`shapescape_ext_WOOLY_RHINO_UNFROZEN_ITEM`);
          system50.runTimeout(() => {
            entity.removeTag(`shapescape_ext_WOOLY_RHINO_UNFROZEN_ITEM`);
          }, 100);
        }
      });
    }
  }
});
world51.afterEvents.entityLoad.subscribe((event) => {
  if (event.entity && event.entity.hasTag(`shapescape_ext_WOOLY_RHINO_UNFROZEN_ITEM`)) {
    event.entity.removeTag(`shapescape_ext_WOOLY_RHINO_UNFROZEN_ITEM`);
  }
});
world51.afterEvents.playerSpawn.subscribe((event) => {
  if (event.player && event.player.hasTag(`shapescape_ext_WOOLY_RHINO_UNFROZEN_ITEM`)) {
    event.player.removeTag(`shapescape_ext_WOOLY_RHINO_UNFROZEN_ITEM`);
  }
});

// data/system_template_esbuild/subscripts/wooly_rhino_pickaxe.ts
import {
  system as system51,
  world as world52,
  ItemStack as ItemStack7,
  EntityComponentTypes as EntityComponentTypes8,
  EquipmentSlot as EquipmentSlot7
} from "@minecraft/server";
var BLOCKS_TO_MINE = [
  "minecraft:ice",
  "minecraft:blue_ice",
  "minecraft:frosted_ice",
  "minecraft:packed_ice"
];
world52.beforeEvents.playerBreakBlock.subscribe((event) => {
  const player = event.player;
  const block = event.block;
  const dimension = event.dimension;
  const itemStack = event.itemStack;
  if (!player || !itemStack || itemStack.typeId !== "shapescape_ext:wooly_rhino_horn_pickaxe") {
    return;
  }
  if (BLOCKS_TO_MINE.includes(block.typeId)) {
    const itemToDropID = block.typeId;
    event.cancel = true;
    system51.run(() => {
      dimension.runCommandAsync(
        `/setblock ${block.location.x} ${block.location.y} ${block.location.z} air [] destroy`
      );
      const location = block.center();
      const itemToDrop = new ItemStack7(itemToDropID, 1);
      dimension.spawnItem(itemToDrop, location);
      decreaseDurbility(player, itemStack, 1);
      return;
    });
  } else {
    system51.run(() => {
      decreaseDurbility(player, itemStack, 2);
    });
  }
});
function decreaseDurbility(player, itemStack, value) {
  const playerEqComponent = player.getComponent(EntityComponentTypes8.Equippable);
  const oldItemDurabilityComponent = itemStack.getComponent("minecraft:durability");
  const newDurability = oldItemDurabilityComponent.damage + value;
  if (newDurability >= oldItemDurabilityComponent.maxDurability) {
    playerEqComponent.setEquipment(EquipmentSlot7.Mainhand);
    player.playSound("random.break", {
      location: player.location
    });
  } else {
    const newItemDurabilityComponent = itemStack.getComponent("minecraft:durability");
    newItemDurabilityComponent.damage = newDurability;
    playerEqComponent.setEquipment(EquipmentSlot7.Mainhand, itemStack);
  }
}

// data/system_template_esbuild/subscripts/wooly_rhino_eating.ts
import { world as world53, system as system52 } from "@minecraft/server";
var TAG18 = "shapescape_ext_wooly_rhino_eating";
world53.afterEvents.playerInteractWithEntity.subscribe((event) => {
  const player = event.player;
  const itemStack = event.beforeItemStack;
  const entity = event.target;
  if (!itemStack || !player || !entity || entity.typeId !== "shapescape_ext:wooly_rhino" || itemStack.typeId !== "shapescape_ext:frozen_carrot")
    return;
  const baby = entity.getComponent(
    "minecraft:is_baby"
  );
  if (!entity.hasTag(TAG18)) {
    entity.addTag(TAG18);
    if (baby) {
      entity.playAnimation(
        "animation.shapescape_ext.wooly_rhino_baby.chewing_layer",
        {
          blendOutTime: 0.2
        }
      );
    } else {
      entity.playAnimation("animation.shapescape_ext.wooly_rhino.chewing_layer", {
        blendOutTime: 0.2
      });
    }
    system52.runTimeout(() => {
      entity.removeTag(TAG18);
    }, 20 * 1.5);
  }
});

// data/system_template_esbuild/subscripts/guide_book.ts
import { system as system53 } from "@minecraft/server";

// data/system_template_esbuild/subscripts/guide_book_page_access.ts
import { world as world54 } from "@minecraft/server";
var bookName = "guide_book";
var pageIdxGroupIdxAndGroupItemIdx = [[0, 0], [1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0], [10, 0], [11, 0], [12, 0], [13, 0], [14, 0], [15, 0], [16, 0], [17, 0], [18, 0], [19, 0], [20, 0], [21, 0], [22, 0], [23, 0], [24, 0], [25, 0], [26, 0], [27, 0], [28, 0], [29, 0], [30, 0], [31, 0], [32, 0]];
var groupIdxGroupName = ["first_page", "contents", "bestiary_start", "overworld_start", "10", "12", "14", "16", "18", "20", "22", "24", "26", "28", "30", "32", "nether_start", "36", "the_end_start", "40", "42", "taming", "crafting_start", "48", "50", "52", "54", "56", "58", "60", "62", "64", "last_page"];
var groupInfo = { "first_page": [{ "page_index": 0, "group_index": 0, "group_name": "first_page" }], "contents": [{ "page_index": 1, "group_index": 1, "group_name": "contents" }], "bestiary_start": [{ "page_index": 2, "group_index": 2, "group_name": "bestiary_start" }], "overworld_start": [{ "page_index": 3, "group_index": 3, "group_name": "overworld_start" }], "10": [{ "page_index": 4, "group_index": 4, "group_name": "10" }], "12": [{ "page_index": 5, "group_index": 5, "group_name": "12" }], "14": [{ "page_index": 6, "group_index": 6, "group_name": "14" }], "16": [{ "page_index": 7, "group_index": 7, "group_name": "16" }], "18": [{ "page_index": 8, "group_index": 8, "group_name": "18" }], "20": [{ "page_index": 9, "group_index": 9, "group_name": "20" }], "22": [{ "page_index": 10, "group_index": 10, "group_name": "22" }], "24": [{ "page_index": 11, "group_index": 11, "group_name": "24" }], "26": [{ "page_index": 12, "group_index": 12, "group_name": "26" }], "28": [{ "page_index": 13, "group_index": 13, "group_name": "28" }], "30": [{ "page_index": 14, "group_index": 14, "group_name": "30" }], "32": [{ "page_index": 15, "group_index": 15, "group_name": "32" }], "nether_start": [{ "page_index": 16, "group_index": 16, "group_name": "nether_start" }], "36": [{ "page_index": 17, "group_index": 17, "group_name": "36" }], "the_end_start": [{ "page_index": 18, "group_index": 18, "group_name": "the_end_start" }], "40": [{ "page_index": 19, "group_index": 19, "group_name": "40" }], "42": [{ "page_index": 20, "group_index": 20, "group_name": "42" }], "taming": [{ "page_index": 21, "group_index": 21, "group_name": "taming" }], "crafting_start": [{ "page_index": 22, "group_index": 22, "group_name": "crafting_start" }], "48": [{ "page_index": 23, "group_index": 23, "group_name": "48" }], "50": [{ "page_index": 24, "group_index": 24, "group_name": "50" }], "52": [{ "page_index": 25, "group_index": 25, "group_name": "52" }], "54": [{ "page_index": 26, "group_index": 26, "group_name": "54" }], "56": [{ "page_index": 27, "group_index": 27, "group_name": "56" }], "58": [{ "page_index": 28, "group_index": 28, "group_name": "58" }], "60": [{ "page_index": 29, "group_index": 29, "group_name": "60" }], "62": [{ "page_index": 30, "group_index": 30, "group_name": "62" }], "64": [{ "page_index": 31, "group_index": 31, "group_name": "64" }], "last_page": [{ "page_index": 32, "group_index": 32, "group_name": "last_page" }] };
var pageInteractions = [{ "min": [-0.85, 0.23], "max": [-0.66, 0.3], "responses": [{ "type": "set_page_group", "group_name": "first_page" }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }], "group_name": ["contents", "bestiary_start", "overworld_start", "10", "12", "14", "16", "18", "20", "22", "24", "26", "28", "nether_start", "the_end_start", "34", "36", "taming", "crafting_start", "42", "44", "46", "48", "50", "52", "last_page"] }, { "min": [-0.85, 0.07], "max": [-0.66, 0.23], "responses": [{ "type": "set_page_group", "group_name": "contents" }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }], "group_name": ["bestiary_start", "overworld_start", "10", "12", "14", "16", "18", "20", "22", "24", "26", "28", "nether_start", "the_end_start", "34", "36", "taming", "crafting_start", "42", "44", "46", "48", "50", "52", "last_page"] }, { "min": [0.66, 0.07], "max": [0.85, 0.23], "responses": [{ "type": "set_page_group", "group_name": "contents" }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }], "group_name": ["first_page"] }, { "min": [-0.85, -0.04], "max": [-0.66, 0.07], "responses": [{ "type": "set_page_group", "group_name": "bestiary_start" }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }], "group_name": ["overworld_start", "10", "12", "14", "16", "18", "20", "22", "24", "26", "28", "nether_start", "the_end_start", "34", "36", "taming", "crafting_start", "42", "44", "46", "48", "50", "52", "last_page"] }, { "min": [0.66, -0.04], "max": [0.85, 0.07], "responses": [{ "type": "set_page_group", "group_name": "bestiary_start" }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }], "group_name": ["first_page", "contents"] }, { "min": [-0.85, -0.19], "max": [-0.66, -0.04], "responses": [{ "type": "set_page_group", "group_name": "taming" }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }], "group_name": ["crafting_start", "42", "44", "46", "48", "50", "52", "last_page"] }, { "min": [0.66, -0.19], "max": [0.85, -0.04], "responses": [{ "type": "set_page_group", "group_name": "taming" }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }], "group_name": ["first_page", "contents", "bestiary_start", "overworld_start", "10", "12", "14", "16", "18", "20", "22", "24", "26", "28", "nether_start", "the_end_start", "34", "36"] }, { "min": [-0.85, -0.33], "max": [-0.66, -0.19], "responses": [{ "type": "set_page_group", "group_name": "crafting_start" }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }], "group_name": ["42", "44", "46", "48", "50", "52", "last_page"] }, { "min": [0.66, -0.33], "max": [0.85, -0.19], "responses": [{ "type": "set_page_group", "group_name": "crafting_start" }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }], "group_name": ["first_page", "contents", "bestiary_start", "overworld_start", "10", "12", "14", "16", "18", "20", "22", "24", "26", "28", "nether_start", "the_end_start", "34", "36", "taming"] }, { "min": [0.66, -0.49], "max": [0.85, -0.33], "responses": [{ "type": "set_page_group", "group_name": "last_page" }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }], "group_name": ["first_page", "contents", "bestiary_start", "overworld_start", "10", "12", "14", "16", "18", "20", "22", "24", "26", "28", "nether_start", "the_end_start", "34", "36", "taming", "crafting_start", "42", "44", "46", "48", "50", "52"] }, { "min": [0.3, 0.38], "max": [0.38, 0.44], "responses": [{ "type": "set_page_group", "group_name": "overworld_start" }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }], "group_name": ["first_page", "contents", "bestiary_start"] }, { "min": [-0.38, 0.38], "max": [-0.3, 0.44], "responses": [{ "type": "set_page_group", "group_name": "overworld_start" }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }], "group_name": ["10", "12", "14", "16", "18", "20", "22", "24", "26", "28", "nether_start", "the_end_start", "34", "36", "taming", "crafting_start", "42", "44", "46", "48", "50", "52", "last_page"] }, { "min": [0.38, 0.38], "max": [0.49, 0.44], "responses": [{ "type": "set_page_group", "group_name": "nether_start" }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }], "group_name": ["first_page", "contents", "bestiary_start", "overworld_start", "10", "12", "14", "16", "18", "20", "22", "24", "26", "28"] }, { "min": [-0.49, 0.38], "max": [-0.38, 0.44], "responses": [{ "type": "set_page_group", "group_name": "nether_start" }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }], "group_name": ["the_end_start", "34", "36", "taming", "crafting_start", "42", "44", "46", "48", "50", "52", "last_page"] }, { "min": [0.49, 0.38], "max": [0.58, 0.44], "responses": [{ "type": "set_page_group", "group_name": "the_end_start" }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }], "group_name": ["first_page", "contents", "bestiary_start", "overworld_start", "10", "12", "14", "16", "18", "20", "22", "24", "26", "28", "nether_start"] }, { "min": [-0.58, 0.38], "max": [-0.49, 0.44], "responses": [{ "type": "set_page_group", "group_name": "the_end_start" }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }], "group_name": ["34", "36", "taming", "crafting_start", "42", "44", "46", "48", "50", "52", "last_page"] }, { "min": [-0.85, -0.6], "max": [0.85, 0.45], "responses": [{ "type": "run_command", "as": "book", "command": "/particle shapescape_ext:click" }] }, { "min": [-0.65, -0.6], "max": [0, 0.37], "responses": [{ "type": "previous_page_group", "wrap": false }, { "type": "run_command", "as": "book", "command": 'titleraw @a[r=10] actionbar {"rawtext":[{"translate":"shapescape_ext.actionbar.guide_book.hint_previous", "with": ["\\n"]}]}' }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }] }, { "min": [0, -0.6], "max": [0.65, 0.37], "responses": [{ "type": "next_page_group", "wrap": false }, { "type": "run_command", "as": "book", "command": 'titleraw @a[r=10] actionbar {"rawtext":[{"translate":"shapescape_ext.actionbar.guide_book.hint_next", "with": ["\\n"]}]}' }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }] }, { "min": [-0.65, -0.6], "max": [0, 0.37], "group_name": ["first_page"], "responses": [{ "type": "previous_page_group", "wrap": true }, { "type": "run_command", "as": "book", "command": 'titleraw @a[r=10] actionbar {"rawtext":[{"translate":"shapescape_ext.actionbar.guide_book.hint_last", "with": ["\\n"]}]}' }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }] }, { "min": [0, -0.6], "max": [0.65, 0.37], "group_name": ["last_page"], "responses": [{ "type": "next_page_group", "wrap": true }, { "type": "run_command", "as": "book", "command": 'titleraw @a[r=10] actionbar {"rawtext":[{"translate":"shapescape_ext.actionbar.guide_book.hint_first", "with": ["\\n"]}]}' }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }] }];
function getGroupInfo(groupName) {
  const group = groupInfo[groupName];
  if (!Array.isArray(group)) {
    return void 0;
  }
  return group;
}
function getGroupName(entity) {
  const index = entity.getProperty("shapescape_ext:active_texture")?.valueOf();
  if (typeof index != "number") {
    return void 0;
  }
  const [groupIdx, pageIdx] = pageIdxGroupIdxAndGroupItemIdx[index];
  return [groupIdxGroupName[groupIdx], pageIdx];
}
function setGroup(entity, groupName) {
  const group = getGroupInfo(groupName);
  if (group == void 0) {
    return;
  }
  if (group.length == 1) {
    entity.setProperty("shapescape_ext:active_texture", group[0].page_index);
    return;
  }
  entity.runCommand(`function ${bookName}/get_${groupName}_state_value`);
  const stateIdx = world54.scoreboard.getObjective("shapescape_ext_tmp_var")?.getScore("STATE")?.valueOf();
  if (typeof stateIdx != "number") {
    return;
  }
  entity.setProperty("shapescape_ext:active_texture", group[stateIdx].page_index);
}
function setNextGroup(entity, wrap) {
  const groupNameAndPageIndex = getGroupName(entity);
  if (groupNameAndPageIndex == void 0) {
    return;
  }
  const groupName = groupNameAndPageIndex[0];
  const group = getGroupInfo(groupName);
  if (group == void 0) {
    return;
  }
  let nextGroupIdx = group[0].group_index + 1;
  if (nextGroupIdx >= groupIdxGroupName.length) {
    if (!wrap) {
      return;
    }
    nextGroupIdx = 0;
  }
  setGroup(entity, groupIdxGroupName[nextGroupIdx]);
}
function setPreviousGroup(entity, wrap) {
  const groupNameAndPageIndex = getGroupName(entity);
  if (groupNameAndPageIndex == void 0) {
    return;
  }
  const groupName = groupNameAndPageIndex[0];
  const group = getGroupInfo(groupName);
  if (group == void 0) {
    return;
  }
  let prevGroupIdx = group[0].group_index - 1;
  if (prevGroupIdx < 0) {
    if (!wrap) {
      return;
    }
    prevGroupIdx = groupIdxGroupName.length - 1;
  }
  setGroup(entity, groupIdxGroupName[prevGroupIdx]);
}
function runPageInteraction(entity, player, x, y, interactionPoint) {
  const group = getGroupName(entity);
  if (group == void 0) {
    return;
  }
  const [groupName, pageIndex] = group;
  for (const pageInteraction of pageInteractions) {
    const [minX, minY] = pageInteraction.min;
    const [maxX, maxY] = pageInteraction.max;
    if (pageInteraction.group_name != void 0 && pageInteraction.group_name.includes(groupName) == false) {
      continue;
    }
    if (pageInteraction.group_item_index != void 0 && pageInteraction.group_item_index.includes(pageIndex) == false) {
      continue;
    }
    if (x >= minX && x <= maxX && y >= minY && y <= maxY) {
      for (const event of pageInteraction.responses) {
        switch (event.type) {
          case "previous_page_group":
            setPreviousGroup(entity, event.wrap ?? false);
            break;
          case "next_page_group":
            setNextGroup(entity, event.wrap ?? false);
            break;
          case "run_command":
            let { x: ipx, y: ipy, z: ipz } = interactionPoint;
            ipx = Math.round(ipx * 100) / 100;
            ipy = Math.round(ipy * 100) / 100;
            ipz = Math.round(ipz * 100) / 100;
            if (event.as == "book") {
              const command = `execute positioned ${ipx} ${ipy} ${ipz} run ${event.command}`;
              entity.runCommand(command);
            } else {
              const command = `execute positioned ${ipx} ${ipy} ${ipz} run ${event.command}`;
              player.runCommand(command);
            }
            break;
          case "set_page_group":
            setGroup(entity, event.group_name);
            break;
        }
      }
      if (pageInteraction.break) {
        break;
      }
    }
  }
}

// data/system_template_esbuild/subscripts/guide_book_coordinates.ts
var Cartesian3D = class {
  /**
   * Creates a new Cartesian3D coordinate system
   * @param origin the origin point of the coordinate system
   * @param x the x-axis of the coordinate system
   * @param y the y-axis of the coordinate system (must be perpendicular to x)
   */
  constructor(origin, x, y) {
    __publicField(this, "origin");
    __publicField(this, "x");
    __publicField(this, "y");
    __publicField(this, "z");
    x = x.normalize();
    y = y.normalize();
    if (Math.abs(x.dot(y)) > 1e-5) {
      throw new Error("X and Y are not perpendicular");
    }
    this.origin = origin;
    this.x = x.normalize();
    this.y = y.normalize();
    this.z = x.cross(y).normalize();
  }
  /**
   * Converts a point from the coordinate system of this object to another
   * coordinate system
   * @param point a point expressed in the coordinate system of this object
   * @param otherCoordinates a target coordinate system to convert the
   * point to.
   * @returns coordinates of the point in the target coordinate system
   */
  convertToOtherCoordinates(point, otherCoordinates) {
    let originTranslation = point.subtract(otherCoordinates.origin);
    let xLocal = originTranslation.dot(otherCoordinates.x);
    let yLocal = originTranslation.dot(otherCoordinates.y);
    let zLocal = originTranslation.dot(otherCoordinates.z);
    let newPointX = this.x.multiply(xLocal);
    let newPointY = this.y.multiply(yLocal);
    let newPointZ = this.z.multiply(zLocal);
    let newPoint = newPointX.add(newPointY).add(newPointZ);
    return newPoint.add(this.origin);
  }
};
var globalCartesianSpace = new Cartesian3D(
  Vec3.from(0, 0, 0),
  Vec3.from(1, 0, 0),
  Vec3.from(0, 1, 0)
);
function linePlaneCollisionCoords(lineOrigin, lineDirection, planeOrigin, planeNormal) {
  const pointA = lineOrigin;
  const pointB = lineOrigin.add(lineDirection);
  const pointP = planeOrigin;
  const normal = planeNormal;
  const x1 = pointA.x;
  const y1 = pointA.y;
  const z1 = pointA.z;
  const x2 = pointB.x;
  const y2 = pointB.y;
  const z2 = pointB.z;
  const x0 = pointP.x;
  const y0 = pointP.y;
  const z0 = pointP.z;
  const a = normal.x;
  const b = normal.y;
  const c = normal.z;
  const d = a * x0 + b * y0 + c * z0;
  const denominator = a * (x2 - x1) + b * (y2 - y1) + c * (z2 - z1);
  if (denominator == 0) {
    return void 0;
  }
  const t = (d - a * x1 - b * y1 - c * z1) / denominator;
  const intersection = Vec3.from({
    x: x1 + t * (x2 - x1),
    y: y1 + t * (y2 - y1),
    z: z1 + t * (z2 - z1)
  });
  return intersection;
}

// data/system_template_esbuild/subscripts/guide_book.ts
function getBookInteractionCoordinates(book, player) {
  const bookOrigin = Vec3.from(book.location).add(0, 1.5, 0);
  let sourceEntityDirection = Vec3.from(book.location).subtract(player.location).setY(0).normalize();
  let sourceEntityYaw = Math.atan2(sourceEntityDirection.z, sourceEntityDirection.x) * (180 / Math.PI);
  const bookX = sourceEntityDirection.rotate(Vec3.from(0, 1, 0), -90);
  const bookY = Vec3.from(0, 1, 0).rotate(Vec3.from(0, 0, 1), -22.5).rotate(Vec3.from(0, 1, 0), -sourceEntityYaw);
  const bookZ = bookX.cross(bookY);
  const interactionPoint = linePlaneCollisionCoords(
    Vec3.from(player.getHeadLocation()),
    Vec3.from(player.getViewDirection()),
    bookOrigin,
    bookZ
  );
  if (interactionPoint == void 0) {
    return void 0;
  }
  let bookCartesianSpace;
  try {
    bookCartesianSpace = new Cartesian3D(bookOrigin, bookX, bookY);
  } catch (e) {
    return void 0;
  }
  const bookInteractionPoint = globalCartesianSpace.convertToOtherCoordinates(
    interactionPoint,
    bookCartesianSpace
  );
  if (bookInteractionPoint == void 0) {
    return void 0;
  }
  return { local: bookInteractionPoint, global: interactionPoint };
}
system53.afterEvents.scriptEventReceive.subscribe((event) => {
  if (event.id != `shapescape_ext:${bookName}_interaction`) {
    return;
  }
  const sourceEntity = event.sourceEntity;
  if (sourceEntity == void 0) {
    return;
  }
  const player = sourceEntity.dimension.getPlayers({
    location: sourceEntity.location,
    closest: 1
  })[0];
  const bookInteractionPoint = getBookInteractionCoordinates(
    sourceEntity,
    player
  );
  if (bookInteractionPoint == void 0) {
    return;
  }
  const { local, global } = bookInteractionPoint;
  runPageInteraction(sourceEntity, player, local.x, local.y, global);
});

// data/system_template_esbuild/subscripts/give_book_to_player.ts
import { world as world56 } from "@minecraft/server";
var DEBUG3 = false;
var NAMESPACE = "shapescape_ext:";
var PATH_NAMESPACE = "shapescape/ext/";
world56.afterEvents.playerSpawn.subscribe((event) => {
  givePlayerBook(event.player);
});
function givePlayerBook(player) {
  player.runCommand(
    `execute as @s[tag=!${NAMESPACE.substring(
      0,
      NAMESPACE.length - 1
    )}] at @s run loot spawn ~ ~ ~ loot "${PATH_NAMESPACE}guide_book"`
  );
  player.runCommand(
    `tag @s[tag=!${NAMESPACE.substring(
      0,
      NAMESPACE.length - 1
    )}] add ${NAMESPACE.substring(0, NAMESPACE.length - 1)}`
  );
  if (DEBUG3) {
    world56.sendMessage(`Given Player Book`);
  }
}

// data/system_template_esbuild/subscripts/thorncrest_bush.ts
import {
  EntityComponentTypes as EntityComponentTypes9,
  EntityDamageCause as EntityDamageCause4,
  EquipmentSlot as EquipmentSlot8,
  system as system54,
  world as world57
} from "@minecraft/server";
var registeredBlocks = /* @__PURE__ */ new Set();
function thorncrestOnStepOn(event) {
  const entity = event.entity;
  if (entity === void 0 || entity.typeId === "shapescape_ext:thorncrest") {
    return;
  }
  const block = event.block;
  const blockLocationString = `${block.location.x} ${block.location.y} ${block.location.z} ${entity?.typeId}`;
  const blockLocationF = new Vec3(block.location).add(0.5, 0.5, 0.5);
  if (registeredBlocks.has(blockLocationString)) {
    return;
  }
  registeredBlocks.add(blockLocationString);
  const handleId = system54.runInterval(() => {
    if (entity === void 0 || !entity.isValid() || !block.isValid() || block.typeId !== "shapescape_ext:thorncrest_bush") {
      system54.clearRun(handleId);
      registeredBlocks.delete(blockLocationString);
      return;
    }
    const entityLocation = entity.location;
    if (blockLocationF.distance(entityLocation) > 1.8) {
      system54.clearRun(handleId);
      registeredBlocks.delete(blockLocationString);
      return;
    }
    if (Math.abs(entityLocation.x - blockLocationF.x) < 0.7 && Math.floor(entityLocation.y) === Math.floor(blockLocationF.y) && Math.abs(entityLocation.z - blockLocationF.z) < 0.7) {
      entity.addEffect("minecraft:slowness", 5, {
        showParticles: false,
        amplifier: 1
      });
      if (Vec3.from(entity.getVelocity()).length() > 0.03) {
        entity.applyDamage(1, { cause: EntityDamageCause4.contact });
      }
    }
  });
}
world57.beforeEvents.worldInitialize.subscribe((event) => {
  event.blockComponentRegistry.registerCustomComponent(
    "shapescape_ext:thorncrest_bush_small",
    {
      onStepOn: thorncrestOnStepOn,
      beforeOnPlayerPlace: pistonBreakableBeforeOnPlayerPlace,
      onPlace: (event2) => {
        const blockPlaceSuccessful = pistonBreakableOnPlace(event2);
        if (!blockPlaceSuccessful) {
          const { x, y, z } = event2.block.location;
          const dimension = event2.block.dimension;
          dimension.runCommand(
            `loot spawn ${x} ${y} ${z} loot "shapescape/ext/thorncrest_bush.loot"`
          );
        }
      },
      onPlayerDestroy: (event2) => {
        const { x, y, z } = event2.block.location;
        const dimension = event2.block.dimension;
        const player = event2.player;
        if (player === void 0) {
          return;
        }
        const equipment = player.getComponent(
          EntityComponentTypes9.Equippable
        );
        const mainHandItem = equipment.getEquipment(
          EquipmentSlot8.Mainhand
        )?.typeId;
        if (mainHandItem === "minecraft:shears") {
          dimension.runCommand(
            `loot spawn ${x} ${y} ${z} loot "shapescape/ext/thorncrest_bush_shears.loot"`
          );
        } else {
          dimension.runCommand(
            `loot spawn ${x} ${y} ${z} loot "empty"`
            // No loot for thorncrest bush small
          );
        }
      },
      onPlayerInteract: (event2) => {
        const { x, y, z } = event2.block.location;
        const player = event2.player;
        const block = event2.block;
        const dimension = event2.block.dimension;
        if (player === void 0) {
          return;
        }
        const equipment = player.getComponent(
          EntityComponentTypes9.Equippable
        );
        const mainHandItem = equipment.getEquipment(
          EquipmentSlot8.Mainhand
        )?.typeId;
        if (mainHandItem === "minecraft:bone_meal" || mainHandItem === "shapescape_ext:skyreach_manure_item") {
          dimension.runCommand(
            `particle minecraft:crop_growth_emitter ${block.location.x} ${block.location.y} ${block.location.z}`
          );
          dimension.runCommand(
            `particle minecraft:crop_growth_emitter ${block.location.x} ${block.location.y + 0.5} ${block.location.z}`
          );
          dimension.runCommand(
            `playsound item.bone_meal.use @a ${x} ${y} ${z}`
          );
          block.setPermutation(
            block.permutation.withState("shapescape_ext:state", "without_berries")
          );
        }
      },
      onTick: (event2) => {
        const block = event2.block;
        block.setPermutation(
          block.permutation.withState("shapescape_ext:state", "without_berries")
        );
      }
    }
  );
});
world57.beforeEvents.worldInitialize.subscribe((event) => {
  event.blockComponentRegistry.registerCustomComponent(
    "shapescape_ext:thorncrest_bush_without_berries",
    {
      onStepOn: thorncrestOnStepOn,
      beforeOnPlayerPlace: pistonBreakableBeforeOnPlayerPlace,
      onPlace: (event2) => {
        const blockPlaceSuccessful = pistonBreakableOnPlace(event2);
        if (!blockPlaceSuccessful) {
          const { x, y, z } = event2.block.location;
          const dimension = event2.block.dimension;
          dimension.runCommand(
            `loot spawn ${x} ${y} ${z} loot "shapescape/ext/thorncrest_bush.loot"`
          );
        }
      },
      onPlayerDestroy: (event2) => {
        const { x, y, z } = event2.block.location;
        const dimension = event2.block.dimension;
        const player = event2.player;
        if (player === void 0) {
          return;
        }
        const equipment = player.getComponent(
          EntityComponentTypes9.Equippable
        );
        const mainHandItem = equipment.getEquipment(
          EquipmentSlot8.Mainhand
        )?.typeId;
        if (mainHandItem === "minecraft:shears") {
          dimension.runCommand(
            `loot spawn ${x} ${y} ${z} loot "shapescape/ext/thorncrest_bush_shears.loot"`
          );
        } else {
          dimension.runCommand(
            `loot spawn ${x} ${y} ${z} loot "shapescape/ext/thorncrest_bush_thorn.loot"`
          );
        }
      },
      onPlayerInteract: (event2) => {
        const { x, y, z } = event2.block.location;
        const player = event2.player;
        const block = event2.block;
        const dimension = event2.block.dimension;
        if (player === void 0) {
          return;
        }
        const equipment = player.getComponent(
          EntityComponentTypes9.Equippable
        );
        const mainHandItem = equipment.getEquipment(
          EquipmentSlot8.Mainhand
        )?.typeId;
        if (mainHandItem === "minecraft:bone_meal" || mainHandItem === "shapescape_ext:skyreach_manure_item") {
          dimension.runCommand(
            `particle minecraft:crop_growth_emitter ${block.location.x} ${block.location.y} ${block.location.z}`
          );
          dimension.runCommand(
            `particle minecraft:crop_growth_emitter ${block.location.x} ${block.location.y + 0.5} ${block.location.z}`
          );
          dimension.runCommand(
            `playsound item.bone_meal.use @a ${x} ${y} ${z}`
          );
          block.setPermutation(
            block.permutation.withState("shapescape_ext:state", "with_berries")
          );
        }
      },
      onTick: (event2) => {
        const block = event2.block;
        block.setPermutation(
          block.permutation.withState("shapescape_ext:state", "with_berries")
        );
      }
    }
  );
});
world57.beforeEvents.worldInitialize.subscribe((event) => {
  event.blockComponentRegistry.registerCustomComponent(
    "shapescape_ext:thorncrest_bush_with_berries",
    {
      onStepOn: thorncrestOnStepOn,
      beforeOnPlayerPlace: pistonBreakableBeforeOnPlayerPlace,
      onPlace: (event2) => {
        const blockPlaceSuccessful = pistonBreakableOnPlace(event2);
        if (!blockPlaceSuccessful) {
          const { x, y, z } = event2.block.location;
          const dimension = event2.block.dimension;
          dimension.runCommand(
            `loot spawn ${x} ${y} ${z} loot "shapescape/ext/thorncrest_bush.loot"`
          );
        }
      },
      onPlayerDestroy: (event2) => {
        const { x, y, z } = event2.block.location;
        const dimension = event2.block.dimension;
        const player = event2.player;
        if (player === void 0) {
          return;
        }
        const equipment = player.getComponent(
          EntityComponentTypes9.Equippable
        );
        const mainHandItem = equipment.getEquipment(
          EquipmentSlot8.Mainhand
        )?.typeId;
        if (mainHandItem === "minecraft:shears") {
          dimension.runCommand(
            `loot spawn ${x} ${y} ${z} loot "shapescape/ext/thorncrest_bush_shears.loot"`
          );
        } else {
          dimension.runCommand(
            `loot spawn ${x} ${y} ${z} loot "shapescape/ext/thorncrest_bush.loot"`
          );
        }
      },
      onPlayerInteract: (event2) => {
        const { x, y, z } = event2.block.location;
        const dimension = event2.block.dimension;
        const player = event2.player;
        const block = event2.block;
        if (player === void 0) {
          return;
        }
        const equipment = player.getComponent(
          EntityComponentTypes9.Equippable
        );
        const mainHandItem = equipment.getEquipment(
          EquipmentSlot8.Mainhand
        )?.typeId;
        if (mainHandItem === "minecraft:bone_meal" || mainHandItem === "shapescape_ext:skyreach_manure_item") {
          dimension.runCommand(
            `playsound item.bone_meal.use @a ${x} ${y} ${z}`
          );
          dimension.runCommand(
            `particle minecraft:crop_growth_emitter ${block.location.x} ${block.location.y} ${block.location.z}`
          );
          dimension.runCommand(
            `particle minecraft:crop_growth_emitter ${block.location.x} ${block.location.y + 0.5} ${block.location.z}`
          );
          block.setPermutation(
            block.permutation.withState("shapescape_ext:state", "big_with_berries")
          );
        } else {
          dimension.runCommand(
            `loot spawn ${x} ${y} ${z} loot "shapescape/ext/thorncrest_bush_berry.loot"`
          );
          dimension.runCommand(
            `playsound block.sweet_berry_bush.pick @a ${x} ${y} ${z}`
          );
          block.setPermutation(
            block.permutation.withState("shapescape_ext:state", "without_berries")
          );
        }
      },
      onTick: (event2) => {
        const block = event2.block;
        block.setPermutation(
          block.permutation.withState("shapescape_ext:state", "big_with_berries")
        );
      }
    }
  );
});
world57.beforeEvents.worldInitialize.subscribe((event) => {
  event.blockComponentRegistry.registerCustomComponent(
    "shapescape_ext:thorncrest_bush_big_with_berries",
    {
      onStepOn: thorncrestOnStepOn,
      beforeOnPlayerPlace: pistonBreakableBeforeOnPlayerPlace,
      onPlace: (event2) => {
        const blockPlaceSuccessful = pistonBreakableOnPlace(event2);
        if (!blockPlaceSuccessful) {
          const { x, y, z } = event2.block.location;
          const dimension = event2.block.dimension;
          dimension.runCommand(
            `loot spawn ${x} ${y} ${z} loot "shapescape/ext/thorncrest_bush.loot"`
          );
        }
      },
      onPlayerDestroy: (event2) => {
        const { x, y, z } = event2.block.location;
        const dimension = event2.block.dimension;
        const player = event2.player;
        if (player === void 0) {
          return;
        }
        const equipment = player.getComponent(
          EntityComponentTypes9.Equippable
        );
        const mainHandItem = equipment.getEquipment(
          EquipmentSlot8.Mainhand
        )?.typeId;
        if (mainHandItem === "minecraft:shears") {
          dimension.runCommand(
            `loot spawn ${x} ${y} ${z} loot "shapescape/ext/thorncrest_bush_shears.loot"`
          );
        } else {
          dimension.runCommand(
            `loot spawn ${x} ${y} ${z} loot "shapescape/ext/thorncrest_bush.loot"`
          );
        }
      },
      onPlayerInteract: (event2) => {
        const { x, y, z } = event2.block.location;
        const dimension = event2.block.dimension;
        const player = event2.player;
        const block = event2.block;
        if (player === void 0) {
          return;
        }
        const equipment = player.getComponent(
          EntityComponentTypes9.Equippable
        );
        const mainHandItem = equipment.getEquipment(
          EquipmentSlot8.Mainhand
        )?.typeId;
        dimension.runCommand(
          `loot spawn ${x} ${y} ${z} loot "shapescape/ext/thorncrest_bush_berry_big.loot"`
        );
        dimension.runCommand(
          `playsound block.sweet_berry_bush.pick @a ${x} ${y} ${z}`
        );
        block.setPermutation(
          block.permutation.withState("shapescape_ext:state", "without_berries")
        );
      }
    }
  );
});

// data/system_template_esbuild/subscripts/thorncrest_fence.ts
import { GameMode as GameMode12, world as world59 } from "@minecraft/server";

// data/system_template_esbuild/thorncrest-fence/block_checking.ts
var plants = [
  "minecraft:double_plant",
  "minecraft:short_grass",
  "minecraft:tall_grass",
  "minecraft:seagrass",
  "minecraft:sunflower",
  "minecraft:torchflower_crop",
  "minecraft:torchflower",
  "minecraft:orange_tulip",
  "minecraft:pink_tulip",
  "minecraft:white_tulip",
  "minecraft:red_tulip",
  "minecraft:blue_orchid",
  "minecraft:allium",
  "minecraft:azure_bluet",
  "minecraft:cornflower",
  "minecraft:dandelion",
  "minecraft:lily_of_the_valley",
  "minecraft:oxeye_daisy",
  "minecraft:poppy",
  "minecraft:rose_bush",
  "minecraft:peony",
  "minecraft:lilac",
  "minecraft:fern",
  "minecraft:wither_rose",
  "minecraft:crimson_roots",
  "minecraft:warped_roots",
  "minecraft:nether_sprouts",
  "minecraft:brain_coral",
  "minecraft:bubble_coral",
  "minecraft:fire_coral",
  "minecraft:horn_coral",
  "minecraft:tube_coral",
  "minecraft:dead_brain_coral",
  "minecraft:dead_bubble_coral",
  "minecraft:dead_fire_coral",
  "minecraft:dead_horn_coral",
  "minecraft:dead_tube_coral"
];
function isReplaceableByFence(block) {
  return block.isAir || block.isLiquid || block.hasTag("plant") || block.hasTag("snow") || plants.includes(block.typeId);
}
function isConnectingToFence(block) {
  return !block.isAir && !block.isLiquid && !block.hasTag("plant") && !block.hasTag("rail") && !block.hasTag("minecraft:crop") && !block.hasTag("one_way_collidable") && !block.hasTag("snow") && !block.hasTag("text_sign") && !block.hasTag("trapdoors") && !plants.includes(block.typeId) && block.typeId !== "shapescape_ext:thorncrest_gate_extension";
}
function isFenceBlock(block) {
  return [
    "shapescape_ext:thorncrest_fence_top",
    "shapescape_ext:thorncrest_fence_bottom",
    "shapescape_ext:thorncrest_fence_stone_top",
    "shapescape_ext:thorncrest_fence_stone_bottom"
  ].includes(block.typeId);
}

// data/system_template_esbuild/thorncrest-fence/direction.ts
function oppositeDirection(direction) {
  const directionOppositeMap = {
    north: "south",
    south: "north",
    east: "west",
    west: "east",
    "x+": "x-",
    "x-": "x+",
    "z+": "z-",
    "z-": "z+"
  };
  return directionOppositeMap[direction];
}
function cardinalToAxisDirection(cardinal) {
  switch (cardinal) {
    case "south":
      return "z+";
    case "north":
      return "z-";
    case "east":
      return "x+";
    case "west":
      return "x-";
  }
}

// data/system_template_esbuild/thorncrest-fence/fence_connections.ts
import { BlockPermutation as BlockPermutation4 } from "@minecraft/server";
function updateFenceConnections(block) {
  if (block == void 0 || !block.isValid() || !isFenceBlock(block)) {
    return;
  }
  const blockStates = {};
  for (const [funcName, state] of [
    // north, south, east and west are names of the functions. Minecraft
    // is dumb and didn't allow me to pass functions directly, because
    // it causes crashes.
    ["north", "shapescape_ext:side_zm"],
    ["south", "shapescape_ext:side_zp"],
    ["east", "shapescape_ext:side_xp"],
    ["west", "shapescape_ext:side_xm"]
  ]) {
    blockStates[state] = false;
    let neightbourBlock;
    try {
      neightbourBlock = block[funcName]();
    } catch {
      continue;
    }
    if (neightbourBlock === void 0 || !neightbourBlock.isValid()) {
      continue;
    }
    blockStates[state] = isConnectingToFence(neightbourBlock);
  }
  block.setPermutation(BlockPermutation4.resolve(block.typeId, blockStates));
}
function updateFenceConnectionsAround(block) {
  updateFenceConnections(block);
  try {
    updateFenceConnections(block.north());
  } catch {
  }
  try {
    updateFenceConnections(block.south());
  } catch {
  }
  try {
    updateFenceConnections(block.east());
  } catch {
  }
  try {
    updateFenceConnections(block.west());
  } catch {
  }
}

// data/system_template_esbuild/thorncrest-fence/two_block_struct.ts
import { system as system55 } from "@minecraft/server";
function tryAddFenceTop(fenceBottom, topFenceId) {
  const aboveBlock = fenceBottom.above();
  if (aboveBlock === void 0 || !aboveBlock.isValid() || !isReplaceableByFence(aboveBlock)) {
    system55.run(() => {
      const { x, y, z } = fenceBottom.location;
      fenceBottom.dimension.runCommand(`setblock ${x} ${y} ${z} air[] destroy`);
      updateFenceConnectionsAround(fenceBottom);
    });
    return false;
  }
  system55.run(() => {
    aboveBlock.setType(topFenceId);
    updateFenceConnectionsAround(aboveBlock);
  });
  return true;
}
function breakTopFenceOfBottomFence(fenceBottom, topFenceId) {
  const aboveBlock = fenceBottom.above();
  if (aboveBlock === void 0 || !aboveBlock.isValid()) {
    return;
  }
  if (aboveBlock.typeId === topFenceId) {
    aboveBlock.setType("minecraft:air");
    updateFenceConnectionsAround(aboveBlock);
  }
}
function breakBottomFenceOfTopFence(fenceTop, dropLoot, bottomFenceId) {
  const belowBlock = fenceTop.below();
  if (belowBlock === void 0 || !belowBlock.isValid()) {
    return;
  }
  if (belowBlock.typeId === bottomFenceId) {
    if (dropLoot) {
      const { x, y, z } = belowBlock.location;
      belowBlock.dimension.runCommand(`setblock ${x} ${y} ${z} air[] destroy`);
    } else {
      belowBlock.setType("minecraft:air");
    }
    updateFenceConnectionsAround(belowBlock);
  }
}
function validateTopFence(fenceTop, bottomFenceId) {
  const belowBlock = fenceTop.below();
  if (belowBlock === void 0 || !belowBlock.isValid() || belowBlock.typeId !== bottomFenceId) {
    fenceTop.setType("minecraft:air");
    updateFenceConnections(fenceTop);
  }
}
function validateBottomFence(fenceBottom, topFenceId) {
  const aboveBlock = fenceBottom.above();
  if (aboveBlock === void 0 || !aboveBlock.isValid() || aboveBlock.typeId !== topFenceId) {
    const { x, y, z } = fenceBottom.location;
    fenceBottom.dimension.runCommand(`setblock ${x} ${y} ${z} air[] destroy`);
    updateFenceConnectionsAround(fenceBottom);
  }
}

// data/system_template_esbuild/thorncrest-fence/gate.ts
import { BlockPermutation as BlockPermutation5, system as system56 } from "@minecraft/server";
var GateExtensionBlock = class _GateExtensionBlock {
  constructor(block, gateBlockId, gateExtensionBlockId, maxGateLength3) {
    /** This gate_extension block. */
    __publicField(this, "gateExtensionBlock");
    __publicField(this, "gateBlockId");
    __publicField(this, "gateExtensionBlockId");
    __publicField(this, "maxGateLength");
    this.gateExtensionBlock = block;
    this.gateBlockId = gateBlockId;
    this.gateExtensionBlockId = gateExtensionBlockId;
    this.maxGateLength = maxGateLength3;
  }
  setAir() {
    this.gateExtensionBlock.setType("minecraft:air");
  }
  breakBlock() {
    const dimension = this.gateExtensionBlock.dimension;
    const { x, y, z } = this.gateExtensionBlock.location;
    dimension.runCommand(`/setblock ${x} ${y} ${z} minecraft:air[] destroy`);
  }
  /**
   * Checks if the gate extension block should still be on the world.
   * The gate extension blocks can't exist without a connection to the gate.
   *
   * If the block is not valid it gets removed.
   */
  validateFromRandomTick() {
    const blockStates = this.gateExtensionBlock.permutation.getAllStates();
    const backDirection = blockStates["shapescape_ext:facing_direction"];
    const facingDirection = oppositeDirection(backDirection);
    const distance = blockStates["shapescape_ext:gate_distance"];
    if (distance === void 0) {
      return;
    }
    const gateBlock = this.gateExtensionBlock[facingDirection](distance);
    if (gateBlock === void 0 || !gateBlock.isValid()) {
      return;
    }
    if (gateBlock.typeId === this.gateBlockId) {
      return;
    }
    this.setAir();
    const forwardCount = distance - 1;
    const backwardCount = this.maxGateLength - distance;
    for (let i = 1; i <= forwardCount; i++) {
      const block = this.gateExtensionBlock[facingDirection](i);
      _GateExtensionBlock.setAirIfMatches(
        block,
        backDirection,
        distance - i,
        this.gateBlockId,
        this.gateExtensionBlockId,
        this.maxGateLength
      );
    }
    for (let i = 1; i <= backwardCount; i++) {
      const block = this.gateExtensionBlock[backDirection](i);
      _GateExtensionBlock.setAirIfMatches(
        block,
        backDirection,
        distance + i,
        this.gateBlockId,
        this.gateExtensionBlockId,
        this.maxGateLength
      );
    }
  }
  /**
   * Breaks the block that matches the expected direction and distance and
   * is a gate_extension block.
   */
  static setAirIfMatches(block, expectedDirection, expectedDistance, gateBlockId, gateExtensionBlockId, maxGateLength3) {
    if (block === void 0 || !block.isValid() || block.typeId !== gateExtensionBlockId) {
      return;
    }
    const blockStates = block.permutation.getAllStates();
    const direction = blockStates["shapescape_ext:facing_direction"];
    const distance = blockStates["shapescape_ext:gate_distance"];
    if (direction === expectedDirection && distance === expectedDistance) {
      new _GateExtensionBlock(
        block,
        gateBlockId,
        gateExtensionBlockId,
        maxGateLength3
      ).setAir();
    }
  }
  /**
   * Breaks the gate_extension blocks that are part of the same barrier as
   * the broken block. The broken block should be a gate_extension block.
   *
   * @param brokenBlock the block that was broken.
   * @param brokenBlockStates the permutation states of a block before it
   * was broken.
   */
  static breakNeighbours(brokenBlock, brokenBlockStates, gateBlockId, gateExtensionBlockId, maxGateLength3) {
    const facingDirection = oppositeDirection(
      brokenBlockStates["shapescape_ext:facing_direction"]
    );
    const distance = brokenBlockStates["shapescape_ext:gate_distance"];
    const gateBlock = brokenBlock[facingDirection](distance);
    if (gateBlock !== void 0 && gateBlock.isValid() && gateBlock.typeId === gateBlockId) {
      gateBlock.setPermutation(
        gateBlock.permutation.withState("shapescape_ext:state", "open")
      );
    }
    const forwardCount = distance - 1;
    const backwardCount = maxGateLength3 - distance;
    for (let i = 1; i <= forwardCount; i++) {
      const neighbour = brokenBlock[facingDirection](i);
      if (neighbour !== void 0 && neighbour.isValid() && neighbour.typeId === gateExtensionBlockId) {
        new _GateExtensionBlock(
          neighbour,
          gateBlockId,
          gateExtensionBlockId,
          maxGateLength3
        ).breakBlock();
      }
    }
    const directionBack = oppositeDirection(facingDirection);
    for (let i = 1; i <= backwardCount; i++) {
      const neighbour = brokenBlock[directionBack](i);
      if (neighbour !== void 0 && neighbour.isValid() && neighbour.typeId === gateExtensionBlockId) {
        new _GateExtensionBlock(
          neighbour,
          gateBlockId,
          gateExtensionBlockId,
          maxGateLength3
        ).breakBlock();
      }
    }
  }
};
var GatePlacementSpace = class {
  constructor(block, facingDirection, gateDistance, gateExtensionBlockId) {
    __publicField(this, "block");
    __publicField(this, "facingDirection");
    __publicField(this, "gateDistance");
    __publicField(this, "gateExtensionBlockId");
    this.block = block;
    this.facingDirection = facingDirection;
    this.gateDistance = gateDistance;
    this.gateExtensionBlockId = gateExtensionBlockId;
  }
  canPlaceBlock() {
    if (!this.block.isValid() || !isReplaceableByFence(this.block)) {
      return false;
    }
    return true;
  }
  tryPlaceGate() {
    if (!this.canPlaceBlock()) {
      return false;
    }
    try {
      this.block.setPermutation(
        BlockPermutation5.resolve(this.gateExtensionBlockId, {
          "shapescape_ext:facing_direction": this.facingDirection,
          "shapescape_ext:gate_distance": this.gateDistance
        })
      );
    } catch {
      return false;
    }
    return true;
  }
};
var _GateBlock = class _GateBlock {
  constructor(gate, gateBlockId, gateExtensionBlockId, openCloseTickRate3, maxGateLength3, maxGateStack3) {
    __publicField(this, "location");
    __publicField(this, "locationStr");
    __publicField(this, "gateBlock");
    __publicField(this, "gateBlockId");
    __publicField(this, "gateExtensionBlockId");
    __publicField(this, "openCloseTickRate");
    __publicField(this, "maxGateLength");
    __publicField(this, "maxGateStack");
    __publicField(this, "gateStates");
    this.location = Vec3.from(gate.location);
    const { x, y, z } = this.location;
    this.locationStr = `${x}, ${y}, ${z}`;
    this.gateBlock = gate;
    this.gateStates = gate.permutation.getAllStates();
    this.gateBlockId = gateBlockId;
    this.gateExtensionBlockId = gateExtensionBlockId;
    this.openCloseTickRate = openCloseTickRate3;
    this.maxGateLength = maxGateLength3;
    this.maxGateStack = maxGateStack3;
  }
  /**
   * Used for handling the player interaction with the gate.
   */
  handleGateInteraction() {
    if (!this.tryAcquireLockAction()) {
      return;
    }
    const gateState = this.getGateState();
    if (gateState == "open" || gateState == "opening") {
      this.closeGate();
    } else {
      this.openGate();
    }
  }
  /**
   * Handles the event of the player breaking the gate.
   *
   * @param brokenBlock the block that was broken (after breaking it's air).
   * @param brokenBlockStates the states of the broken block (
   * before breaking happened).
   */
  static onBreak(brokenBlock, brokenBlockStates, gateBlockId, gateExtensionBlockId, maxGateLength3) {
    const gateExtensions = _GateBlock.getGateExtensions(
      brokenBlock,
      oppositeDirection(
        // Facing direction is reversed to "cardinal_direction"
        brokenBlockStates["minecraft:cardinal_direction"]
      ),
      gateBlockId,
      gateExtensionBlockId,
      maxGateLength3
    );
    for (const extension of gateExtensions) {
      extension.breakBlock();
    }
  }
  /**
   * Checks if the gateBlock is still valid and is a gate block.
   */
  isGateBlockValid() {
    return this.gateBlock.isValid() && this.gateBlock.typeId === this.gateBlockId;
  }
  /**
   * Tries to acquire a lock for performing gate action (opening or closing).
   * Returns a value indicating if the lock was acquired.
   */
  tryAcquireLockAction() {
    if (_GateBlock.managedGates.has(this.locationStr)) {
      return false;
    }
    _GateBlock.managedGates.add(this.locationStr);
    return true;
  }
  /**
   * Gets the direction this gate is facing. It's opposite ot the
   * cardinal_direction property of the block, because cardinal direction
   * represents the direction of the player, when placing the block.
   */
  getFacingDirection() {
    const cardinalDirection = oppositeDirection(
      this.gateStates["minecraft:cardinal_direction"]
    );
    const axisDirection = cardinalToAxisDirection(cardinalDirection);
    return {
      cardinal: cardinalDirection,
      axis: axisDirection
    };
  }
  /**
   * Get the current state of the gate (open, closed, opening, closing).
   */
  getGateState() {
    return this.gateStates["shapescape_ext:state"];
  }
  /**
   * Sets the gate state to the provided value.
   */
  setGateState(state) {
    this.gateBlock.setPermutation(
      this.gateBlock.permutation.withState("shapescape_ext:state", state)
    );
    this.gateStates["shapescape_ext:state"] = state;
  }
  /**
   * Returns the gate extension blocks in front of the gate or broken gate
   * (block). Static, because sometimes it's needed when the gate block is
   * broken already.
   *
   * @param block the gate block or Block object representing a broken gate.
   * @param facingDirection the direction the gate is/was facing.
   */
  static getGateExtensions(block, facingDirection, gateBlockId, gateExtensionBlockId, maxGateLength3) {
    const expectedDirection = facingDirection;
    const directionFunc = (count) => {
      return block[facingDirection](count);
    };
    const result = [];
    for (let expectedDistance = 1; expectedDistance <= maxGateLength3; expectedDistance++) {
      const block2 = directionFunc(expectedDistance);
      if (block2 === void 0 || !block2.isValid() || block2.typeId !== gateExtensionBlockId) {
        break;
      }
      const blockStates = block2.permutation.getAllStates();
      const direction = blockStates["shapescape_ext:facing_direction"];
      const distance = blockStates["shapescape_ext:gate_distance"];
      if (direction !== expectedDirection || distance !== expectedDistance) {
        break;
      }
      result.push(
        new GateExtensionBlock(
          block2,
          gateBlockId,
          gateExtensionBlockId,
          maxGateLength3
        )
      );
    }
    return result;
  }
  /**
   * Returns empty space in front of the gate, for closing the gate.
   */
  getEmptySpace() {
    const facingDirection = this.getFacingDirection().cardinal;
    const directionFunc = (count) => {
      return this.gateBlock[facingDirection](count);
    };
    const result = [];
    for (let distance = 1; distance <= this.maxGateLength; distance++) {
      const block = directionFunc(distance);
      if (block === void 0) {
        break;
      }
      const gatePlacementSpace = new GatePlacementSpace(
        block,
        facingDirection,
        distance,
        this.gateExtensionBlockId
      );
      if (!gatePlacementSpace.canPlaceBlock()) {
        break;
      }
      result.push(gatePlacementSpace);
    }
    return result;
  }
  /**
   * Schedules a task of opening the gate, block by block.
   */
  openGate(recursionLimit = this.maxGateStack, recursionDirection = "both") {
    this._recursiveGateAction(recursionLimit, recursionDirection, "open");
    const gateExtensions = _GateBlock.getGateExtensions(
      this.gateBlock,
      this.getFacingDirection().cardinal,
      this.gateBlockId,
      this.gateExtensionBlockId,
      this.maxGateLength
    );
    const onFinish = () => {
      _GateBlock.managedGates.delete(this.locationStr);
      if (this.isGateBlockValid()) {
        this.setGateState("open");
      }
    };
    if (gateExtensions.length === 0) {
      _GateBlock.managedGates.delete(this.locationStr);
      if (this.isGateBlockValid()) {
        this.setGateState("open");
      }
      return;
    }
    const taskId = system56.runInterval(() => {
      if (!this.gateBlock.isValid() || this.gateBlock.typeId !== this.gateBlockId) {
        system56.clearRun(taskId);
        onFinish();
        return;
      }
      const extension = gateExtensions.pop();
      if (extension === void 0) {
        system56.clearRun(taskId);
        onFinish();
        return;
      }
      extension.setAir();
    }, this.openCloseTickRate);
  }
  /**
   * Schedules a task of closing the gate, block by block.
   */
  closeGate(recursionLimit = this.maxGateStack, recursionDirection = "both") {
    this._recursiveGateAction(recursionLimit, recursionDirection, "close");
    const emptySpaceBlocks = this.getEmptySpace();
    if (emptySpaceBlocks.length == 0) {
      _GateBlock.managedGates.delete(this.locationStr);
      return;
    }
    const onFinish = () => {
      _GateBlock.managedGates.delete(this.locationStr);
      if (this.isGateBlockValid()) {
        this.setGateState("closed");
      }
    };
    const taskId = system56.runInterval(() => {
      if (!this.gateBlock.isValid() || this.gateBlock.typeId !== this.gateBlockId) {
        system56.clearRun(taskId);
        onFinish();
        return;
      }
      const emptySpace = emptySpaceBlocks.shift();
      if (emptySpace === void 0) {
        system56.clearRun(taskId);
        onFinish();
        return;
      }
      const breakSuccess = emptySpace.tryPlaceGate();
      if (!breakSuccess) {
        system56.clearRun(taskId);
        onFinish();
        return;
      }
    }, this.openCloseTickRate);
  }
  /**
   * Used for opening/closing gates above/below the gate that player
   * interacted with.
   */
  _recursiveGateAction(recursionLimit = this.maxGateStack, recursionDirection = "both", action) {
    if (recursionLimit <= 0) {
      return;
    }
    const f = (neighbour, direction) => {
      if (neighbour === void 0) {
        return;
      }
      const neighbourGate = new _GateBlock(
        neighbour,
        this.gateBlockId,
        this.gateExtensionBlockId,
        this.openCloseTickRate,
        this.maxGateLength,
        this.maxGateStack
      );
      if (!neighbourGate.isGateBlockValid()) {
        return;
      }
      if (!neighbourGate.tryAcquireLockAction()) {
        return;
      }
      if (action === "open") {
        neighbourGate.openGate(recursionLimit - 1, direction);
      } else {
        neighbourGate.closeGate(recursionLimit - 1, direction);
      }
    };
    if (["up", "both"].includes(recursionDirection)) {
      const aboveBlock = this.gateBlock.above();
      f(aboveBlock, "up");
    }
    if (["down", "both"].includes(recursionDirection)) {
      const belowBlock = this.gateBlock.below();
      f(belowBlock, "down");
    }
  }
};
__publicField(_GateBlock, "managedGates", /* @__PURE__ */ new Set());
var GateBlock = _GateBlock;

// data/system_template_esbuild/subscripts/thorncrest_fence.ts
world59.afterEvents.playerBreakBlock.subscribe((event) => {
  updateFenceConnectionsAround(event.block);
});
world59.afterEvents.playerPlaceBlock.subscribe((event) => {
  updateFenceConnectionsAround(event.block);
});
world59.beforeEvents.worldInitialize.subscribe((event) => {
  event.blockComponentRegistry.registerCustomComponent(
    "shapescape_ext:thorncrest_fence_top",
    {
      onPlayerDestroy(block) {
        breakBottomFenceOfTopFence(
          block.block,
          block.player?.getGameMode() !== GameMode12.creative,
          "shapescape_ext:thorncrest_fence_bottom"
        );
      },
      onRandomTick(block) {
        validateTopFence(block.block, "shapescape_ext:thorncrest_fence_bottom");
      }
    }
  );
  event.blockComponentRegistry.registerCustomComponent(
    "shapescape_ext:thorncrest_fence_bottom",
    {
      beforeOnPlayerPlace(event2) {
        const success = tryAddFenceTop(
          event2.block,
          "shapescape_ext:thorncrest_fence_top"
        );
        if (success) {
          pistonBreakableBeforeOnPlayerPlace(event2);
        }
      },
      onPlace: pistonBreakableOnPlace,
      onPlayerDestroy(block) {
        breakTopFenceOfBottomFence(
          block.block,
          "shapescape_ext:thorncrest_fence_top"
        );
      },
      onRandomTick(block) {
        validateBottomFence(block.block, "shapescape_ext:thorncrest_fence_top");
      }
    }
  );
});

// data/system_template_esbuild/subscripts/thorncrest_fence_damage.ts
import {
  EntityDamageCause as EntityDamageCause5,
  system as system57,
  world as world60
} from "@minecraft/server";
var registeredBlocks2 = /* @__PURE__ */ new Set();
function thorncrestFenceDamageOnStepOn(event) {
  const entity = event.entity;
  if (entity === void 0) {
    return;
  }
  const block = event.block;
  const blockLocationString = `${block.location.x} ${block.location.y} ${block.location.z} ${entity?.typeId}`;
  const blockLocationF = new Vec3(block.location).add(0.5, 0.5, 0.5);
  if (registeredBlocks2.has(blockLocationString)) {
    return;
  }
  registeredBlocks2.add(blockLocationString);
  const handleId = system57.runInterval(() => {
    if (entity === void 0 || !entity.isValid() || !block.isValid()) {
      system57.clearRun(handleId);
      registeredBlocks2.delete(blockLocationString);
      return;
    }
    const entityLocation = entity.location;
    if (blockLocationF.distance(entityLocation) > 1.8) {
      system57.clearRun(handleId);
      registeredBlocks2.delete(blockLocationString);
      return;
    }
    if (Math.abs(entityLocation.x - blockLocationF.x) < 0.7 && Math.abs(entityLocation.y - (blockLocationF.y + 0.5)) < 0.1 && Math.abs(entityLocation.z - blockLocationF.z) < 0.7 && entity.isOnGround) {
      entity.addEffect("minecraft:slowness", 5, {
        showParticles: false,
        amplifier: 1
      });
      entity.applyDamage(1, { cause: EntityDamageCause5.contact });
    }
  });
}
world60.beforeEvents.worldInitialize.subscribe((event) => {
  event.blockComponentRegistry.registerCustomComponent(
    "shapescape_ext:thorncrest_fence_damage",
    {
      onStepOn: thorncrestFenceDamageOnStepOn
    }
  );
});

// data/system_template_esbuild/subscripts/thorncrest_fence_stone.ts
import { GameMode as GameMode13, world as world61 } from "@minecraft/server";
world61.afterEvents.playerBreakBlock.subscribe((event) => {
  updateFenceConnectionsAround(event.block);
});
world61.afterEvents.playerPlaceBlock.subscribe((event) => {
  updateFenceConnectionsAround(event.block);
});
world61.beforeEvents.worldInitialize.subscribe((event) => {
  event.blockComponentRegistry.registerCustomComponent(
    "shapescape_ext:thorncrest_fence_stone_top",
    {
      onPlayerDestroy(block) {
        breakBottomFenceOfTopFence(
          block.block,
          block.player?.getGameMode() !== GameMode13.creative,
          "shapescape_ext:thorncrest_fence_stone_bottom"
        );
      },
      onRandomTick(block) {
        validateTopFence(
          block.block,
          "shapescape_ext:thorncrest_fence_stone_bottom"
        );
      }
    }
  );
  event.blockComponentRegistry.registerCustomComponent(
    "shapescape_ext:thorncrest_fence_stone_bottom",
    {
      beforeOnPlayerPlace(event2) {
        const success = tryAddFenceTop(
          event2.block,
          "shapescape_ext:thorncrest_fence_stone_top"
        );
        if (success) {
          pistonBreakableBeforeOnPlayerPlace(event2);
        }
      },
      onPlace: pistonBreakableOnPlace,
      onPlayerDestroy(block) {
        breakTopFenceOfBottomFence(
          block.block,
          "shapescape_ext:thorncrest_fence_stone_top"
        );
      },
      onRandomTick(block) {
        validateBottomFence(
          block.block,
          "shapescape_ext:thorncrest_fence_stone_top"
        );
      }
    }
  );
});

// data/system_template_esbuild/subscripts/thorncrest_gate.ts
import { world as world62 } from "@minecraft/server";
var openCloseTickRate = 2;
var maxGateLength = 4;
var maxGateStack = 4;
world62.beforeEvents.worldInitialize.subscribe((event) => {
  event.blockComponentRegistry.registerCustomComponent(
    "shapescape_ext:thorncrest_gate",
    {
      beforeOnPlayerPlace: pistonBreakableBeforeOnPlayerPlace,
      onPlace: pistonBreakableOnPlace,
      onPlayerInteract: (event2) => {
        new GateBlock(
          event2.block,
          "shapescape_ext:thorncrest_gate",
          "shapescape_ext:thorncrest_gate_extension",
          openCloseTickRate,
          maxGateLength,
          maxGateStack
        ).handleGateInteraction();
        const block = event2.block;
        block.dimension.runCommandAsync(
          `playsound dig.stem @a ${block.x} ${block.y} ${block.z}`
        );
      },
      onPlayerDestroy: (event2) => {
        GateBlock.onBreak(
          event2.block,
          event2.destroyedBlockPermutation.getAllStates(),
          "shapescape_ext:thorncrest_gate",
          "shapescape_ext:thorncrest_gate_extension",
          maxGateLength
        );
      }
    }
  );
  event.blockComponentRegistry.registerCustomComponent(
    "shapescape_ext:thorncrest_gate_extension",
    {
      onRandomTick(event2) {
        new GateExtensionBlock(
          event2.block,
          "shapescape_ext:thorncrest_gate",
          "shapescape_ext:thorncrest_gate_extension",
          maxGateLength
        ).validateFromRandomTick();
      },
      onPlayerDestroy(event2) {
        GateExtensionBlock.breakNeighbours(
          event2.block,
          event2.destroyedBlockPermutation.getAllStates(),
          "shapescape_ext:thorncrest_gate",
          "shapescape_ext:thorncrest_gate_extension",
          maxGateLength
        );
      }
    }
  );
});

// data/system_template_esbuild/subscripts/thorncrest_gate_stone.ts
import { world as world63 } from "@minecraft/server";
var openCloseTickRate2 = 2;
var maxGateLength2 = 4;
var maxGateStack2 = 4;
world63.beforeEvents.worldInitialize.subscribe((event) => {
  event.blockComponentRegistry.registerCustomComponent(
    "shapescape_ext:thorncrest_gate_stone",
    {
      beforeOnPlayerPlace: pistonBreakableBeforeOnPlayerPlace,
      onPlace: pistonBreakableOnPlace,
      onPlayerInteract: (event2) => {
        new GateBlock(
          event2.block,
          "shapescape_ext:thorncrest_gate_stone",
          "shapescape_ext:thorncrest_gate_stone_extension",
          openCloseTickRate2,
          maxGateLength2,
          maxGateStack2
        ).handleGateInteraction();
        const block = event2.block;
        block.dimension.runCommandAsync(
          `playsound dig.stone @a ${block.x} ${block.y} ${block.z}`
        );
      },
      onPlayerDestroy: (event2) => {
        GateBlock.onBreak(
          event2.block,
          event2.destroyedBlockPermutation.getAllStates(),
          "shapescape_ext:thorncrest_gate_stone",
          "shapescape_ext:thorncrest_gate_stone_extension",
          maxGateLength2
        );
      }
    }
  );
  event.blockComponentRegistry.registerCustomComponent(
    "shapescape_ext:thorncrest_gate_stone_extension",
    {
      onRandomTick(event2) {
        new GateExtensionBlock(
          event2.block,
          "shapescape_ext:thorncrest_gate_stone",
          "shapescape_ext:thorncrest_gate_stone_extension",
          maxGateLength2
        ).validateFromRandomTick();
      },
      onPlayerDestroy(event2) {
        GateExtensionBlock.breakNeighbours(
          event2.block,
          event2.destroyedBlockPermutation.getAllStates(),
          "shapescape_ext:thorncrest_gate_stone",
          "shapescape_ext:thorncrest_gate_stone_extension",
          maxGateLength2
        );
      }
    }
  );
});
