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/altitude_sickness.ts
import {
  system,
  world,
  EquipmentSlot,
  EntityComponentTypes,
  TicksPerSecond,
  EntityDamageCause,
  MolangVariableMap,
  GameMode
} from "@minecraft/server";
var DATA = [{ "altitude": { "min": 115, "max": 115 }, "delay": 30, "effects_frequency": 10, "effects": { "damage": 0, "nausea_duration": 3 } }, { "altitude": { "min": 120, "max": 120 }, "delay": 10, "effects_frequency": 5, "effects": { "damage": 0, "nausea_duration": 5 } }, { "altitude": { "min": 130, "max": 130 }, "delay": 10, "effects_frequency": 5, "effects": { "damage": 1, "nausea_duration": 6 } }, { "altitude": { "min": 140, "max": 140 }, "delay": 10, "effects_frequency": 5, "effects": { "damage": 1, "nausea_duration": 7 } }];
var INTERVAL = 1 * TicksPerSecond;
var DEBUG = false;
var TIP_TAG = "shapescape_bewe_ALTITUDE_SICKNESS_TIP";
var TAG_PREFIX = `shapescape_bewe_ALTITUDE_SICKNESS`;
system.runInterval(() => {
  if (system.currentTick % INTERVAL === 0) {
    const players = world.getPlayers();
    for (const player of players) {
      checkAltitude(player);
    }
  }
}, 1);
world.afterEvents.playerSpawn.subscribe((event) => {
  if (event.initialSpawn === false) {
    const tags = event.player.getTags();
    for (const tag of tags) {
      if (tag.includes(TAG_PREFIX)) {
        event.player.removeTag(tag);
      }
    }
    const initArray = [];
    for (const threshold of DATA) {
      initArray.push({
        altitude: {
          min: threshold.altitude.min,
          max: threshold.altitude.max
        },
        duration: 0
        // Start with 0 exposure time
      });
    }
    event.player.setDynamicProperty(`altitude_sickness_data`, JSON.stringify(initArray));
    event.player.setDynamicProperty(`altitude_sickness`, false);
  }
});
function checkAltitude(player) {
  const allowedGamemode = player.getGameMode() !== GameMode.Creative && player.getGameMode() !== GameMode.Spectator;
  if (!allowedGamemode)
    return;
  const property = player.getDynamicProperty(`altitude_sickness_data`);
  if (property === void 0) {
    const initArray = [];
    for (const threshold of DATA) {
      initArray.push({
        altitude: {
          min: threshold.altitude.min,
          max: threshold.altitude.max
        },
        duration: 0
        // Start with 0 exposure time
      });
    }
    player.setDynamicProperty(`altitude_sickness_data`, JSON.stringify(initArray));
  }
  const playerData = JSON.parse(player.getDynamicProperty(`altitude_sickness_data`));
  const setting = player.getDynamicProperty(`shapescape_bewe:settings.states.altitude_sickness`) ?? true;
  let altitude = player.location.y;
  const freeAltitudeEntities = player.dimension.getEntities({
    maxDistance: 8,
    type: "shapescape_bewe:hiker_cabin_entity",
    location: player.location
  });
  if (freeAltitudeEntities.length > 0) {
    altitude = 0;
  }
  if (player.dimension.id === "minecraft:nether")
    altitude = 0;
  const newPlayerData = [];
  let index = -1;
  for (const threshold of DATA) {
    index++;
    const EFFECT_TAG = `${TAG_PREFIX}_${index}`;
    let currentData = playerData.find(
      (data) => data.altitude.min === threshold.altitude.min && data.altitude.max === threshold.altitude.max
    );
    if (currentData !== void 0) {
      const hasHelmet = player.getComponent(EntityComponentTypes.Equippable)?.getEquipment(EquipmentSlot.Head)?.typeId === "shapescape_bewe:altitude_helmet";
      if ((!setting || altitude < threshold.altitude.min || hasHelmet) && currentData.duration > 0) {
        currentData.duration -= INTERVAL / TicksPerSecond;
        if (currentData.duration <= 0 && player.hasTag(EFFECT_TAG)) {
          player.setDynamicProperty(`altitude_sickness`, false);
          player.removeTag(EFFECT_TAG);
        }
      } else if (altitude > threshold.altitude.min && currentData.duration <= threshold.delay) {
        currentData.duration += INTERVAL / TicksPerSecond;
        if (currentData.duration >= threshold.delay && !player.hasTag(EFFECT_TAG)) {
          player.setDynamicProperty(`altitude_sickness`, true);
          player.addTag(EFFECT_TAG);
        }
      }
      if (setting && player.hasTag(EFFECT_TAG) && system.currentTick % (Math.round(threshold.effects_frequency / 2) * TicksPerSecond) === 0) {
        particles(player);
      }
      if (setting && player.hasTag(EFFECT_TAG) && system.currentTick % (threshold.effects_frequency * TicksPerSecond) === 0) {
        if (!player.hasTag(TIP_TAG)) {
          player.sendMessage({ translate: `shapescape_bewe.altitude_sickness.tip` });
          player.playSound(`note.bass`, { location: player.location });
          player.addTag(TIP_TAG);
        }
        if (threshold.effects.damage > 0) {
          player.applyDamage(threshold.effects.damage, {
            cause: EntityDamageCause.drowning
            // For some reason suffocation doesn't work here
          });
        }
        player.addEffect("minecraft:nausea", threshold.effects.nausea_duration * TicksPerSecond, {
          amplifier: 0,
          showParticles: false
        });
      }
    } else {
      currentData = {
        altitude: {
          min: threshold.altitude.min,
          max: threshold.altitude.max
        },
        duration: 0
        // Start with 0 exposure time
      };
    }
    newPlayerData.push(currentData);
  }
  if (DEBUG) {
    world.sendMessage(`=============
=============`);
    for (const data of playerData) {
      world.sendMessage(`Altitude: ${JSON.stringify(data.altitude)} <=> Duration: ${JSON.stringify(data.duration)}`);
    }
  }
  player.setDynamicProperty(`altitude_sickness_data`, JSON.stringify(newPlayerData));
}
function particles(player) {
  const headLocation = player.getHeadLocation();
  const direction = player.getViewDirection();
  const velocity = player.getVelocity();
  const particleLocation = {
    x: headLocation.x + direction.x + velocity.x * 8,
    y: headLocation.y + 0.1 + direction.y + velocity.y * 8,
    z: headLocation.z + direction.z + velocity.z * 8
  };
  const molang = new MolangVariableMap();
  molang.setFloat("variable.direction_x", velocity.x);
  molang.setFloat("variable.direction_y", velocity.y);
  molang.setFloat("variable.direction_z", velocity.z);
  try {
    player.spawnParticle("shapescape_bewe:altitude_sickness_dots", particleLocation, molang);
  } catch {
  }
}

// data/node_modules/@bedrock-oss/bedrock-boost/dist/index.mjs
import { Direction } from "@minecraft/server";
import { system as system2, world as world2 } from "@minecraft/server";
import { system as system22 } from "@minecraft/server";
import { BlockPermutation, world as world22 } from "@minecraft/server";
import { world as world3 } 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, 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);
  }
  static createPlain() {
    const plain = new _a2();
    plain.OpenCloseObjectColor = "";
    plain.OpenCloseArrayColor = "";
    plain.NumberColor = "";
    plain.StringColor = "";
    plain.BooleanColor = "";
    plain.NullColor = "";
    plain.KeyColor = "";
    plain.EscapeColor = "";
    plain.FunctionColor = "";
    plain.ClassColor = "";
    plain.ClassStyle = "";
    plain.CycleColor = "";
    return plain;
  }
  /**
   * Transforms a value into a chat-friendly, colored JSON representation.
   * @param value - The value to transform.
   */
  stringify(value) {
    return this.stringifyValue(value, {
      indentLevel: 0,
      visited: /* @__PURE__ */ new WeakSet()
    });
  }
  /**
   * 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, ctx) {
    const indentSpace = this.Indent.repeat(ctx.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, this.indent(ctx));
      result += index < value.length - 1 ? this.Comma + this.NewLine : this.NewLine;
      compactResult += this.stringifyValue(item, this.indent(ctx));
      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, ctx) {
    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, ctx) {
    const indentSpace = this.Indent.repeat(ctx.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, this.indent(ctx));
      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, ctx) {
    return !(className === "Object" || ctx.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, ctx) {
    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, ctx)) {
      return this.stringifyCycle();
    }
    this.markCycle(value, ctx);
    if (Array.isArray(value)) {
      const result = this.stringifyArray(value, ctx.indentLevel ? this.indent(ctx) : ctx);
      this.clearCycle(value, ctx);
      return result;
    }
    if (typeof value === "object") {
      const name = value.constructor.name;
      if (!this.shouldTruncateObject(value, name, ctx)) {
        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, ctx);
        this.clearCycle(value, ctx);
        return result;
      } else {
        const result = this.stringifyTruncatedObject(value, name, ctx);
        this.clearCycle(value, ctx);
        return result;
      }
    }
    this.clearCycle(value, ctx);
    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, ctx) {
    ctx.visited.add(value);
  }
  isCycle(value, ctx) {
    return ctx.visited.has(value);
  }
  clearCycle(value, ctx) {
    ctx.visited.delete(value);
  }
  indent(ctx) {
    return { ...ctx, indentLevel: ctx.indentLevel + 1 };
  }
}, /**
 * The default ColorJSON instance
 */
__publicField(_a2, "DEFAULT", new _a2()), /**
 * A ColorJSON instance that does not colorize anything.
 */
__publicField(_a2, "PLAIN", _a2.createPlain()), _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;
            world2.sendMessage(
              `${ChatColor.AQUA}Logging level set to ${ChatColor.BOLD}${loggingSettings.level}`
            );
          } else {
            const level = LogLevel.parse(ev.message);
            if (level) {
              loggingSettings.level = level;
              world2.sendMessage(
                `${ChatColor.AQUA}Logging level set to ${ChatColor.BOLD}${loggingSettings.level}`
              );
            } else {
              world2.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(",");
          }
          world2.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 */
      )) {
        try {
          world2.sendMessage(formatted);
        } catch (_) {
          system2.run(() => {
            world2.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);
  }
  static fromRotation(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.
   * @deprecated Use toRotation() instead. This method returns inverted values and will be removed in the future.
   */
  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
    };
  }
  /**
   * Converts the normal vector to yaw and pitch values.
   *
   * @returns A Vector2 containing the yaw and pitch values.
   */
  toRotation() {
    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.hypot(this.x, this.y, this.z);
  }
  /**
   * 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 this.subtract(v).length();
  }
  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 lenSq1 = this.lengthSquared();
    if (lenSq1 === 0) {
      return 0;
    }
    const lenSq2 = v.lengthSquared();
    if (lenSq2 === 0) {
      return 0;
    }
    const denom = Math.sqrt(lenSq1 * lenSq2);
    const cosAngle = Math.min(1, Math.max(-1, dotProduct / denom));
    return Math.acos(cosAngle);
  }
  projectOnto(x, y, z) {
    const v = _a5._from(x, y, z);
    if (v.isZero()) {
      return _a5.Zero;
    }
    const denom = v.dot(v);
    if (denom === 0) {
      return _a5.Zero;
    }
    const scale = this.dot(v) / denom;
    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;
  }
  /**
   * Parses a string representation of a vector.
   *
   * @param str - The string representation of the vector.
   * @param format - The format of the string representation. Defaults to "long".
   * @param separator - The separator to use between components. Defaults to ", ".
   * @returns The vector parsed from the string.
   * @throws {Error} If the string format is invalid.
   */
  static fromString(str, format = "long", separator = ", ") {
    if (format === "long") {
      const match = str.match(/^Vec3\((.*)\)$/);
      if (!match) {
        throw new Error("Invalid string format");
      }
      const components = match[1].split(separator);
      if (components.length !== 3) {
        throw new Error("Invalid string format");
      }
      return _a5.from(Number(components[0]), Number(components[1]), Number(components[2]));
    } else {
      const components = str.split(separator);
      if (components.length !== 3) {
        throw new Error("Invalid string format");
      }
      return _a5.from(Number(components[0]), Number(components[1]), Number(components[2]));
    }
  }
}, __publicField(_a5, "log", Logger.getLogger(
  "vec3",
  "vec3",
  "bedrock-boost"
)), /**
 * Zero vector
 */
__publicField(_a5, "Zero", new _a5(0, 0, 0)), /**
 * Down vector, negative towards Y
 */
__publicField(_a5, "Down", new _a5(Direction.Down)), /**
 * Up vector, positive towards Y
 */
__publicField(_a5, "Up", new _a5(Direction.Up)), /**
 * North vector, negative towards Z
 */
__publicField(_a5, "North", new _a5(Direction.North)), /**
 * South vector, positive towards Z
 */
__publicField(_a5, "South", new _a5(Direction.South)), /**
 * East vector, positive towards X
 */
__publicField(_a5, "East", new _a5(Direction.East)), /**
 * West vector, negative towards X
 */
__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 isValid(entity) {
  const f = Object.getPrototypeOf(entity).isValid;
  if (typeof f === "function") {
    return f.call(entity);
  }
  return entity.isValid;
}
var log = Logger.getLogger("jobUtils", "bedrock-boost", "jobUtils");
var _a7;
var PulseScheduler = (_a7 = 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) {
      _a7.log.trace("No items to process.");
      return;
    }
    const scheduledExecutions = this.executionSchedule[this.currentTick];
    if (scheduledExecutions === 0) {
      _a7.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) {
        _a7.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(_a7, "log", Logger.getLogger("PulseScheduler", "bedrock-boost", "pulse-scheduler")), _a7);
var _a8;
var EntityPulseScheduler = (_a8 = 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) {
      _a8.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(_a8, "logger", Logger.getLogger(
  "EntityPulseScheduler",
  "bedrock-boost",
  "entity-pulse-scheduler"
)), _a8);
var _a9;
var PlayerPulseScheduler = (_a9 = 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) {
          _a9.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) {
          _a9.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(_a9, "logger", Logger.getLogger("PlayerPulseScheduler", "bedrock-boost", "player-pulse-scheduler")), _a9);
var _a10;
var DirectionUtils = (_a10 = class {
}, /**
 * The opposite directions of the given directions.
 */
__publicField(_a10, "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(_a10, "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(_a10, "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(_a10, "Values", [
  Direction2.Down,
  Direction2.Up,
  Direction2.North,
  Direction2.South,
  Direction2.East,
  Direction2.West
]), _a10);
var log2 = Logger.getLogger("itemUtils", "bedrock-boost", "itemUtils");

// data/system_template_esbuild/subscripts/hiker_cabin_block.ts
import { system as system8, world as world7 } from "@minecraft/server";
var lastEventLocation = new Vec3(0, 0, 0);
function placeHikerCabinBlockAndDespawn(event) {
  const dimension = event.dimension;
  const location = event.block.location;
  const scoreboard = world7.scoreboard.getObjective("shapescape_bewe_hiker_cabin_block");
  if (scoreboard !== void 0)
    return;
  if (lastEventLocation.equals(location)) {
    return;
  }
  try {
    dimension.setBlockType(location, "minecraft:air");
  } catch {
    return;
  }
  lastEventLocation = Vec3.from(location);
  dimension.runCommand(`summon shapescape_bewe:hiker_cabin_entity ${location.x} ${location.y} ${location.z} ~~`);
}
system8.beforeEvents.startup.subscribe((event) => {
  event.blockComponentRegistry.registerCustomComponent("shapescape_bewe:hiker_cabin_block", {
    onTick: (event2) => {
      placeHikerCabinBlockAndDespawn(event2);
    }
  });
});

// data/system_template_esbuild/subscripts/ambient_sounds.ts
import { system as system9, world as world8 } from "@minecraft/server";
var REFRESH_RATE = 1 * 20;
var COOLDOWN_BIRDS = "shapescape_bewe_ambient_birds_cooldown";
var COOLDOWN_OWL = "shapescape_bewe_ambient_owl_cooldown";
var COOLDOWN_CRICKETS = "shapescape_bewe_ambient_crickets_cooldown";
var COOLDOWN_SWAMP = "shapescape_bewe_ambient_swamp_cooldown";
var COOLDOWN_JUNGLE = "shapescape_bewe_ambient_jungle_cooldown";
var COOLDOWN_JUNGLE_NIGHT = "shapescape_bewe_ambient_jungle_night_cooldown";
var COOLDOWN_RIVER = "shapescape_bewe_ambient_river_cooldown";
var COOLDOWN_BEACH = "shapescape_bewe_ambient_beach_cooldown";
var COOLDOWN_OCEAN = "shapescape_bewe_ambient_ocean_cooldown";
var cooldown_tags = [
  COOLDOWN_BIRDS,
  COOLDOWN_OWL,
  COOLDOWN_CRICKETS,
  COOLDOWN_SWAMP,
  COOLDOWN_JUNGLE,
  COOLDOWN_JUNGLE_NIGHT,
  COOLDOWN_RIVER,
  COOLDOWN_BEACH,
  COOLDOWN_OCEAN
];
world8.afterEvents.playerSpawn.subscribe((event) => {
  clear_cooldowns(event.player);
});
function clear_cooldowns(player) {
  for (let tag of cooldown_tags) {
    player.removeTag(tag);
  }
}
function random_int(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
system9.runInterval(() => {
  const WEATHER = world8.getDynamicProperty("shapescape_bewe:environment_detection.weather") ?? "clear";
  const TIME_OF_DAY = world8.getTimeOfDay();
  let players = world8.getPlayers();
  for (let player of players) {
    const biome = player.getDynamicProperty("shapescape_bewe:environment_detection.biome") ?? "";
    const biomeTagsProperty = player.getDynamicProperty("shapescape_bewe:environment_detection.biome_tags") ?? "[]";
    const biomeTags = JSON.parse(biomeTagsProperty);
    if (biomeTags.length === 0 || biome === "")
      continue;
    let time = "day";
    if (TIME_OF_DAY > 23500 && TIME_OF_DAY < 24e3 || TIME_OF_DAY >= 0 && TIME_OF_DAY < 12500) {
      time = "day";
    } else {
      time = "night";
    }
    if (biomeTags.includes("forest") || biome === "forest") {
      if (biomeTags.includes("cold"))
        continue;
      if (WEATHER !== "clear")
        continue;
      if (player.location.y > 50 && player.location.y < 100) {
        if (time === "day") {
          if ((player.getDynamicProperty("shapescape_bewe:settings.sounds.forest_day") ?? true) === false)
            continue;
          birds_sounds(player);
        } else {
          if ((player.getDynamicProperty("shapescape_bewe:settings.sounds.forest_night") ?? true) === false)
            continue;
          owl_sounds(player);
          crickets_sounds(player);
        }
      }
    }
    if (biomeTags.includes("plains") || biome === "plain") {
      if (WEATHER !== "clear")
        continue;
      if (player.location.y > 50 && player.location.y < 100) {
        if (time === "night") {
          if ((player.getDynamicProperty("shapescape_bewe:settings.sounds.plains_night") ?? true) === false)
            continue;
          crickets_sounds(player);
        }
      }
    }
    if (biomeTags.includes("swamp") || biomeTags.includes("mangrove_swamp") || biome === "swamp") {
      if (WEATHER !== "clear")
        continue;
      if (player.location.y > 50 && player.location.y < 100) {
        swamp_sounds(player, time);
      }
    }
    if (biomeTags.includes("jungle") || biome === "jungle") {
      if (WEATHER !== "clear")
        continue;
      if (player.location.y > 50 && player.location.y < 100) {
        if (time === "day") {
          if ((player.getDynamicProperty("shapescape_bewe:settings.sounds.jungle_day") ?? true) === false)
            continue;
          birds_sounds(player);
          jungle_sounds(player);
        } else {
          if ((player.getDynamicProperty("shapescape_bewe:settings.sounds.jungle_night") ?? true) === false)
            continue;
          jungle_night_sounds(player);
          crickets_sounds(player);
        }
      }
    }
    if (biomeTags.includes("river") || biome === "river") {
      if (biomeTags.includes("frozen"))
        continue;
      if ((player.getDynamicProperty("shapescape_bewe:settings.sounds.river") ?? true) === false)
        continue;
      if (player.location.y > 50 && player.location.y < 100) {
        river_sounds(player);
      }
    }
    if (biomeTags.includes("beach") || biome === "beach" || biome === "stone_beach") {
      if (biomeTags.includes("cold"))
        continue;
      if (WEATHER !== "clear")
        continue;
      if ((player.getDynamicProperty("shapescape_bewe:settings.sounds.beach") ?? true) === false)
        continue;
      if (player.location.y > 50 && player.location.y < 100) {
        beach_sounds(player);
      }
    }
    if (biomeTags.includes("ocean") || biome === "ocean") {
      if (biomeTags.includes("frozen"))
        continue;
      if ((player.getDynamicProperty("shapescape_bewe:settings.sounds.ocean") ?? true) === false)
        continue;
      if (player.location.y > 50 && player.location.y < 100) {
        ocean_sounds(player);
      }
    }
  }
}, REFRESH_RATE);
function ocean_sounds(player) {
  if (!player.hasTag(COOLDOWN_OCEAN)) {
    player.addTag(COOLDOWN_OCEAN);
    let location = {
      x: player.location.x + (Math.random() < 0.5 ? -1 : 1) * random_int(8, 16),
      y: player.location.y,
      z: player.location.z + (Math.random() < 0.5 ? -1 : 1) * random_int(8, 16)
    };
    let volume = 4;
    let pitch = 1.05 - random_int(0, 5) * 0.01;
    player.playSound("shapescape_bewe.ocean", {
      location,
      volume,
      pitch
    });
    let COOLDOWN3 = random_int(3, 4);
    system9.runTimeout(() => {
      player.removeTag(COOLDOWN_OCEAN);
    }, COOLDOWN3 * 20);
  }
}
function beach_sounds(player) {
  if (!player.hasTag(COOLDOWN_BEACH)) {
    player.addTag(COOLDOWN_BEACH);
    let location = {
      x: player.location.x + (Math.random() < 0.5 ? -1 : 1) * random_int(8, 16),
      y: player.location.y,
      z: player.location.z + (Math.random() < 0.5 ? -1 : 1) * random_int(8, 16)
    };
    let volume = 4;
    let pitch = 1.05 - random_int(0, 5) * 0.01;
    player.playSound("shapescape_bewe.beach", {
      location,
      volume,
      pitch
    });
    let COOLDOWN3 = random_int(3, 5);
    system9.runTimeout(() => {
      player.removeTag(COOLDOWN_BEACH);
    }, COOLDOWN3 * 20);
  }
}
function river_sounds(player) {
  if (!player.hasTag(COOLDOWN_RIVER)) {
    player.addTag(COOLDOWN_RIVER);
    let location = {
      x: player.location.x + (Math.random() < 0.5 ? -1 : 1) * random_int(16, 22),
      y: player.location.y,
      z: player.location.z + (Math.random() < 0.5 ? -1 : 1) * random_int(16, 22)
    };
    let volume = 4;
    let pitch = 1.05 - random_int(0, 5) * 0.01;
    player.playSound("shapescape_bewe.river", {
      location,
      volume,
      pitch
    });
    let COOLDOWN3 = random_int(3, 5);
    system9.runTimeout(() => {
      player.removeTag(COOLDOWN_RIVER);
    }, COOLDOWN3 * 20);
  }
}
function jungle_sounds(player) {
  if (!player.hasTag(COOLDOWN_JUNGLE)) {
    player.addTag(COOLDOWN_JUNGLE);
    let location = {
      x: player.location.x + (Math.random() < 0.5 ? -1 : 1) * random_int(16, 22),
      y: player.location.y,
      z: player.location.z + (Math.random() < 0.5 ? -1 : 1) * random_int(16, 22)
    };
    let volume = 4;
    let pitch = 1.05 - random_int(0, 5) * 0.01;
    player.playSound("shapescape_bewe.jungle", {
      location,
      volume,
      pitch
    });
    let COOLDOWN3 = random_int(3, 5);
    system9.runTimeout(() => {
      player.removeTag(COOLDOWN_JUNGLE);
    }, COOLDOWN3 * 20);
  }
}
function jungle_night_sounds(player) {
  if (!player.hasTag(COOLDOWN_JUNGLE_NIGHT)) {
    player.addTag(COOLDOWN_JUNGLE_NIGHT);
    let location = {
      x: player.location.x + (Math.random() < 0.5 ? -1 : 1) * random_int(8, 16),
      y: player.location.y,
      z: player.location.z + (Math.random() < 0.5 ? -1 : 1) * random_int(8, 16)
    };
    let volume = 4;
    let pitch = 1.05 - random_int(0, 5) * 0.01;
    player.playSound("shapescape_bewe.jungle_night", {
      location,
      volume,
      pitch
    });
    let COOLDOWN3 = random_int(3, 5);
    system9.runTimeout(() => {
      player.removeTag(COOLDOWN_JUNGLE_NIGHT);
    }, COOLDOWN3 * 20);
  }
}
function swamp_sounds(player, time) {
  if (!player.hasTag(COOLDOWN_SWAMP)) {
    player.addTag(COOLDOWN_SWAMP);
    let location = player.location;
    if (time === "day") {
      location = {
        x: player.location.x + (Math.random() < 0.5 ? -1 : 1) * random_int(16, 22),
        y: player.location.y,
        z: player.location.z + (Math.random() < 0.5 ? -1 : 1) * random_int(16, 22)
      };
    } else {
      location = {
        x: player.location.x + (Math.random() < 0.5 ? -1 : 1) * random_int(8, 16),
        y: player.location.y,
        z: player.location.z + (Math.random() < 0.5 ? -1 : 1) * random_int(8, 16)
      };
    }
    let volume = 8;
    let pitch = 1.15 - random_int(0, 30) * 0.01;
    if (time === "day") {
      if (player.getDynamicProperty("shapescape_bewe:settings.sounds.swamp_day") ?? true) {
        player.playSound("shapescape_bewe.swamp", {
          location,
          volume,
          pitch
        });
      }
    }
    if (time !== "day") {
      if (player.getDynamicProperty("shapescape_bewe:settings.sounds.swamp_night") ?? true) {
        player.playSound("shapescape_bewe.swamp", {
          location,
          volume,
          pitch
        });
      }
    }
    let COOLDOWN3 = random_int(5, 8);
    system9.runTimeout(() => {
      player.removeTag(COOLDOWN_SWAMP);
    }, COOLDOWN3 * 20);
  }
}
function birds_sounds(player) {
  if (!player.hasTag(COOLDOWN_BIRDS)) {
    player.addTag(COOLDOWN_BIRDS);
    let location = {
      x: player.location.x + (Math.random() < 0.5 ? -1 : 1) * random_int(8, 16),
      y: player.location.y,
      z: player.location.z + (Math.random() < 0.5 ? -1 : 1) * random_int(8, 16)
    };
    let volume = 2 - random_int(0, 10) * 0.01;
    let pitch = 1.15 - random_int(0, 30) * 0.01;
    player.playSound("shapescape_bewe.bird", {
      location,
      volume,
      pitch
    });
    let COOLDOWN3 = random_int(5, 8);
    system9.runTimeout(() => {
      player.removeTag(COOLDOWN_BIRDS);
    }, COOLDOWN3 * 20);
  }
}
function owl_sounds(player) {
  if (!player.hasTag(COOLDOWN_OWL)) {
    player.addTag(COOLDOWN_OWL);
    let location = {
      x: player.location.x + (Math.random() < 0.5 ? -1 : 1) * random_int(8, 16),
      y: player.location.y,
      z: player.location.z + (Math.random() < 0.5 ? -1 : 1) * random_int(8, 16)
    };
    let volume = 2;
    let pitch = 1 - random_int(0, 5) * 0.01;
    player.playSound("shapescape_bewe.owl", {
      location,
      volume,
      pitch
    });
    let COOLDOWN3 = random_int(10, 20);
    system9.runTimeout(() => {
      player.removeTag(COOLDOWN_OWL);
    }, COOLDOWN3 * 20);
  }
}
function crickets_sounds(player) {
  if (!player.hasTag(COOLDOWN_CRICKETS)) {
    player.addTag(COOLDOWN_CRICKETS);
    let location = {
      x: player.location.x + (Math.random() < 0.5 ? -1 : 1) * random_int(8, 16),
      y: player.location.y,
      z: player.location.z + (Math.random() < 0.5 ? -1 : 1) * random_int(8, 16)
    };
    let volume = 2;
    let pitch = 1 - random_int(0, 5) * 0.01;
    player.playSound("shapescape_bewe.crickets", {
      location,
      volume,
      pitch
    });
    let COOLDOWN3 = random_int(4, 6);
    system9.runTimeout(() => {
      player.removeTag(COOLDOWN_CRICKETS);
    }, COOLDOWN3 * 20);
  }
}

// data/system_template_esbuild/subscripts/aurora.ts
import { system as system10, world as world9 } from "@minecraft/server";
system10.runInterval(() => {
  if ((world9.getDynamicProperty("shapescape_bewe:settings.particles.aurora") ?? true) === false)
    return;
  const timeOfDay = world9.getTimeOfDay();
  if (timeOfDay >= 2e4 || timeOfDay < 14e3) {
    return;
  }
  const players = world9.getPlayers();
  for (const player of players) {
    try {
      player.dimension.spawnParticle("shapescape_bewe:aurora_beams", {
        x: player.location.x,
        y: 100,
        z: player.location.z
      });
    } catch {
    }
  }
}, 600);

// data/system_template_esbuild/subscripts/backpack.ts
import {
  EntityComponentTypes as EntityComponentTypes2,
  EquipmentSlot as EquipmentSlot3,
  Player as Player4,
  system as system11,
  world as world10
} from "@minecraft/server";
var CARRY_TAG = "shapescape_bewe_BACKPACK_CARRYING";
var DETACH_TAG = "shapescape_bewe_BACKPACK_DETACHING";
var DETACH_SOUND_TAG = "shapescape_bewe_BACKPACK_DETACHING_SOUND";
var MAX_HITS_TO_DESPAWN = 3;
var TICK_INTERVAL = 5;
var DETACH_TIME = 2;
var colors = [
  "white",
  "light_gray",
  "gray",
  "black",
  "brown",
  "red",
  "orange",
  "yellow",
  "lime",
  "green",
  "cyan",
  "light_blue",
  "blue",
  "purple",
  "magenta",
  "pink"
];
world10.afterEvents.playerSpawn.subscribe((event) => {
  detach(event.player);
});
world10.afterEvents.playerInteractWithBlock.subscribe((event) => {
  const player = event.player;
  const item = event.itemStack?.typeId;
  const block = event.block;
  if (!item)
    return;
  if (item.startsWith("shapescape_bewe:backpack_") && !item.endsWith("default")) {
    player.runCommand(
      `execute positioned ${block.location.x} ${block.location.y} ${block.location.z} if block ~~~ minecraft:cauldron run function shapescape/bewe/backpack/undye`
    );
  }
});
system11.afterEvents.scriptEventReceive.subscribe((event) => {
  if (event.sourceEntity == void 0)
    return;
  if (event.id == "shapescape_bewe:backpack_get_name") {
    let name = event.sourceEntity.typeId;
    var letters = name.replace("shapescape_bewe:", "").split("");
    var result = letters.map(function(letter) {
      return "\xA7" + letter;
    });
    var formatted_name = result.join("").toUpperCase();
    event.sourceEntity.nameTag = `\xA7S\xA7H\xA7A\xA7P\xA7E\xA7S\xA7C\xA7A\xA7P\xA7E\xA7.\xA7I\xA7N\xA7V\xA7E\xA7N\xA7T\xA7O\xA7R\xA7Y\xA7.${formatted_name}\xA7.\xA7N\xA7A\xA7M\xA7E`;
  }
  if (event.id == "shapescape_bewe:backpack_undye") {
    const player = event.sourceEntity;
    const item = player.getComponent("equippable")?.getEquipment(EquipmentSlot3.Mainhand)?.typeId;
    if (item && item.startsWith("shapescape_bewe:backpack_") && !item.endsWith("default")) {
      let new_item = item;
      colors.forEach((color) => {
        if (new_item.includes(color)) {
          new_item = new_item.replace(color, "default");
        }
      });
      try {
        player.runCommand(`replaceitem entity @s slot.weapon.mainhand 0 ${new_item}`);
      } catch {
      }
    }
  }
});
function detaching(player) {
  player.addTag(DETACH_TAG);
  let cooldown = Date.now() + DETACH_TIME * 1e3;
  let detach_sound = 1.5;
  let detaching2 = system11.runInterval(() => {
    if (player.isValid && player.isSneaking) {
      if (cooldown < Date.now()) {
        detach(player);
        player.removeTag(DETACH_TAG);
        system11.clearRun(detaching2);
      }
      if (player.hasTag(CARRY_TAG) && !player.hasTag(DETACH_SOUND_TAG) && detach_sound > 0.5) {
        player.addTag(DETACH_SOUND_TAG);
        let detach_sound_loop = system11.runInterval(() => {
          player.runCommand(`/playsound armor.equip_leather @s ~ ~ ~ 1 ${detach_sound}`);
          detach_sound -= 0.2;
          player.removeTag(DETACH_SOUND_TAG);
          system11.clearRun(detach_sound_loop);
        }, DETACH_TIME / 5 * 20);
      }
    } else {
      player.removeTag(DETACH_TAG);
      player.removeTag(DETACH_SOUND_TAG);
      system11.clearRun(detaching2);
    }
  });
}
function detach(player) {
  const riders = player.getComponent("rideable")?.getRiders() ?? [];
  player.removeTag(CARRY_TAG);
  player.removeTag(DETACH_TAG);
  player.removeTag(DETACH_SOUND_TAG);
  for (const rider of riders) {
    if (rider.typeId.includes("shapescape_bewe:backpack")) {
      rider.runCommand(`ride @s stop_riding`);
      const playerLoc = { x: player.location.x, y: player.location.y, z: player.location.z };
      const viewDir = Vec3.from(player.getViewDirection()).multiply(1.5).setY(0);
      const tpLocation = Vec3.from(playerLoc).add(viewDir);
      try {
        const block = player.dimension.getBlock(tpLocation);
        if (block && (block.isAir || block.typeId === "minecraft:water" || block.typeId === "minecraft:flowing_water" || block.typeId.includes("minecraft:light_block"))) {
          rider.teleport(tpLocation);
        }
      } catch {
        continue;
      }
      system11.runTimeout(() => {
        try {
          rider.dimension.spawnParticle(`shapescape_bewe:backpack_impact`, rider.location);
        } catch {
        }
      }, 2);
    }
  }
}
function main() {
  for (let player of world10.getAllPlayers()) {
    if (player.hasTag(CARRY_TAG)) {
      if (!player.hasTag(DETACH_TAG) && player.isSneaking) {
        detaching(player);
      }
      const standing_space = player.getHeadLocation().y - player.location.y;
      if (player.isGliding) {
        player.runCommand(
          "execute positioned ~ ~1.5 ~ run event entity @e[family=shapescape_bewe:backpack,c=1] horizontal_glide"
        );
      } else if (standing_space < 1 || player.isSwimming || player.isSleeping) {
        player.runCommand("execute positioned ~ ~1.5 ~ run event entity @e[family=shapescape_bewe:backpack,c=1] horizontal");
      } else {
        player.runCommand("execute positioned ~ ~1.5 ~ run event entity @e[family=shapescape_bewe:backpack,c=1] vertical");
      }
    }
  }
}
world10.afterEvents.entityHitEntity.subscribe((event) => {
  const { damagingEntity, hitEntity: backpack } = event;
  if (!(damagingEntity instanceof Player4) || !backpack.typeId.includes(`shapescape_bewe:backpack`) || !backpack)
    return;
  const ignitedComp = backpack.getComponent(EntityComponentTypes2.IsIgnited);
  if (ignitedComp) {
    backpack.playAnimation(`animation.shapescape_bewe.backpack.hit`);
    let hitCount = backpack.getDynamicProperty("hits_to_despawn") ?? MAX_HITS_TO_DESPAWN;
    hitCount--;
    if (hitCount === MAX_HITS_TO_DESPAWN - 1) {
      system11.runTimeout(() => {
        if (!backpack.isValid)
          return;
        backpack.setDynamicProperty("hits_to_despawn", MAX_HITS_TO_DESPAWN);
      }, 60);
    }
    if (hitCount <= 0) {
      backpack.dimension.playSound(`armor.equip_leather`, backpack.location);
      backpack.triggerEvent(`shapescape_bewe:despawning`);
      return;
    } else {
      backpack.dimension.playSound(`armor.equip_leather`, backpack.location, {
        pitch: 1 + hitCount * 0.2
      });
      backpack.setDynamicProperty("hits_to_despawn", hitCount);
    }
  }
});
world10.afterEvents.entityLoad.subscribe((event) => {
  const entity = event.entity;
  if (!entity.typeId.includes(`shapescape_bewe:backpack`))
    return;
  entity.setDynamicProperty("hits_to_despawn", MAX_HITS_TO_DESPAWN);
});
system11.runInterval(main, TICK_INTERVAL);

// data/system_template_esbuild/subscripts/better_rain.ts
import { system as system12, world as world11, MolangVariableMap as MolangVariableMap2 } from "@minecraft/server";
var REFRESH_RATE2 = 1 * 20;
system12.runInterval(() => {
  let players = world11.getPlayers();
  let alreadyProcessed = /* @__PURE__ */ new Set();
  const setting_rain_ripples = world11.getDynamicProperty("shapescape_bewe:settings.weather.rain_ripples") ?? true;
  const setting_wind_driven_rain = world11.getDynamicProperty("shapescape_bewe:settings.weather.wind_driven_rain") ?? true;
  const WEATHER = world11.getDynamicProperty("shapescape_bewe:environment_detection.weather") ?? "clear";
  const WIND_DIRECTION = world11.getDynamicProperty("shapescape_bewe:wind_direction") ?? { x: 1, y: 0, z: 0 };
  if (WEATHER === "clear")
    return;
  for (let player of players) {
    try {
      if (alreadyProcessed.has(player))
        continue;
      const nearbyPlayers = player.dimension.getEntities({
        location: player.location,
        maxDistance: 16,
        type: "minecraft:player"
      });
      for (let otherPlayer of nearbyPlayers) {
        if (otherPlayer.nameTag !== player.nameTag) {
          alreadyProcessed.add(otherPlayer);
        }
      }
      const BIOME_TEMPERATURE = player.getDynamicProperty("shapescape_bewe:environment_detection.biome_temperature") ?? 0.5;
      if (player.location.y < 40 || player.dimension.id !== "minecraft:overworld" || BIOME_TEMPERATURE >= 1 || BIOME_TEMPERATURE <= 0.15)
        continue;
      const windDrivenRain_molang = new MolangVariableMap2();
      windDrivenRain_molang.setVector3("wind_direction", WIND_DIRECTION);
      if (setting_rain_ripples) {
        try {
          player.dimension.spawnParticle("shapescape_bewe:water_circle_rain", player.location);
        } catch {
        }
      }
      if (setting_wind_driven_rain) {
        try {
          player.dimension.spawnParticle("shapescape_bewe:rain_wind", player.location, windDrivenRain_molang);
        } catch {
        }
      }
    } catch {
    }
  }
}, REFRESH_RATE2);
var LastWeather = "clear";
var CurrentWeather = "clear";
world11.afterEvents.worldLoad.subscribe(() => {
  LastWeather = world11.getDynamicProperty("shapescape_bewe:environment_detection.weather") ?? "clear";
  CurrentWeather = world11.getDynamicProperty("shapescape_bewe:environment_detection.weather") ?? "clear";
});
system12.runInterval(() => {
  let Weather = world11.getDynamicProperty("shapescape_bewe:environment_detection.weather") ?? "clear";
  if (Weather != CurrentWeather) {
    LastWeather = CurrentWeather;
    CurrentWeather = Weather;
    if (LastWeather === "rain" && CurrentWeather === "clear") {
      spawn_rainbow();
    }
  }
}, REFRESH_RATE2);
function getRandomNumber(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}
function spawn_rainbow() {
  const timeOfDay = world11.getTimeOfDay();
  if (timeOfDay > 12e3)
    return;
  const setting_rainbow = world11.getDynamicProperty("shapescape_bewe:settings.weather.rainbow") ?? true;
  if (!setting_rainbow)
    return;
  let players = world11.getPlayers();
  let alreadyProcessed = /* @__PURE__ */ new Set();
  for (let player of players) {
    try {
      if (alreadyProcessed.has(player))
        continue;
      const nearbyPlayers = player.dimension.getEntities({
        location: player.location,
        maxDistance: 128,
        type: "minecraft:player"
      });
      for (let otherPlayer of nearbyPlayers) {
        if (otherPlayer.nameTag !== player.nameTag) {
          alreadyProcessed.add(otherPlayer);
        }
      }
      const BIOME_TEMPERATURE = player.getDynamicProperty("shapescape_bewe:environment_detection.biome_temperature") ?? 0.5;
      if (player.dimension.id !== "minecraft:overworld" || BIOME_TEMPERATURE >= 1 || BIOME_TEMPERATURE <= 0.15)
        continue;
      const rainbow_rng = getRandomNumber(1, 10);
      if (rainbow_rng > 8)
        continue;
      const angle = getRandomNumber(1, 360);
      const rainbow_location = {
        x: player.location.x,
        y: 64,
        z: player.location.z
      };
      const rainbowMolang = new MolangVariableMap2();
      const lifetime = getRandomNumber(32, 60);
      rainbowMolang.setFloat("lifetime", lifetime);
      rainbowMolang.setFloat("size", 32);
      rainbowMolang.setFloat("range", 128);
      rainbowMolang.setFloat("angle", angle);
      player.dimension.spawnParticle("shapescape_bewe:rainbow", rainbow_location, rainbowMolang);
    } catch {
    }
  }
}

// data/system_template_esbuild/subscripts/blizzard.ts
import {
  system as system13,
  world as world12,
  MolangVariableMap as MolangVariableMap3,
  EntityDamageCause as EntityDamageCause2,
  GameMode as GameMode2
} from "@minecraft/server";
var REFRESH_RATE3 = 1 * 20;
system13.runInterval(() => {
  if (system13.currentTick % REFRESH_RATE3 !== 0)
    return;
  if ((world12.getDynamicProperty(
    "shapescape_bewe:settings.weather.blizzard"
  ) ?? true) === false)
    return;
  let players = world12.getPlayers();
  let alreadyProcessed = /* @__PURE__ */ new Set();
  const WEATHER = world12.getDynamicProperty(
    "shapescape_bewe:environment_detection.weather"
  ) ?? "clear";
  const WIND_DIRECTION = world12.getDynamicProperty(
    "shapescape_bewe:wind_direction"
  ) ?? { x: 1, y: 0, z: 0 };
  if (WEATHER !== "thunderstorm")
    return;
  for (let player of players) {
    const allowedGamemode = player.getGameMode() !== GameMode2.Creative && player.getGameMode() !== GameMode2.Spectator;
    if (!allowedGamemode)
      continue;
    const dimension = player.dimension;
    const location = player.location;
    try {
      if (alreadyProcessed.has(player))
        continue;
      const nearbyPlayers = dimension.getEntities({
        location,
        maxDistance: 32,
        type: "minecraft:player"
      });
      for (let otherPlayer of nearbyPlayers) {
        if (otherPlayer.nameTag !== player.nameTag) {
          alreadyProcessed.add(otherPlayer);
        }
      }
      const BIOME_TEMPERATURE = player.getDynamicProperty(
        "shapescape_bewe:environment_detection.biome_temperature"
      ) ?? 0.5;
      if (BIOME_TEMPERATURE > 0.15)
        continue;
      if (location.y < 40 || dimension.id !== "minecraft:overworld")
        continue;
      const windDrivenRain_molang = new MolangVariableMap3();
      windDrivenRain_molang.setVector3("wind_direction", WIND_DIRECTION);
      dimension.spawnParticle(
        "shapescape_bewe:blizzard",
        location,
        windDrivenRain_molang
      );
    } catch {
    }
    if (system13.currentTick % 40 === 0) {
      const entitiesToSlow = dimension.getEntities({
        location,
        maxDistance: 32,
        excludeFamilies: ["player"]
      });
      for (const entity of entitiesToSlow) {
        entity.removeEffect("minecraft:slowness");
        entity.addEffect("minecraft:slowness", 50, {
          amplifier: 1,
          // Random level between 0 and 2
          showParticles: false
        });
      }
    }
    let blockToCheck = void 0;
    if (system13.currentTick % 120 === 0 && Math.random() < 0.6) {
      const playerVelocity = player.getVelocity();
      if (Math.abs(playerVelocity.x) < 0.1 && Math.abs(playerVelocity.z) < 0.1) {
        try {
          blockToCheck = player.dimension.getBlock({
            x: player.location.x,
            y: player.location.y - 1,
            z: player.location.z
          });
          if (blockToCheck?.isAir || blockToCheck === void 0) {
            continue;
          }
          let northBlock = blockToCheck.north(1)?.above(1);
          let southBlock = blockToCheck.south(1)?.above(1);
          let eastBlock = blockToCheck.east(1)?.above(1);
          let westBlock = blockToCheck.west(1)?.above(1);
          let blocks = [northBlock, southBlock, eastBlock, westBlock];
          for (let block of blocks) {
            if (block === void 0 || block.isLiquid) {
              continue;
            }
            if ((block.isAir || block.typeId.includes("minecraft:light_block") || block.typeId.includes("minecraft:snow_layer")) && !block.below(1)?.typeId.includes("minecraft:air")) {
              block.setType("minecraft:snow");
              system13.runTimeout(() => {
                if (block.typeId.includes("minecraft:snow")) {
                  block.setType("minecraft:air");
                }
              }, 500);
              continue;
            }
            if ((block.above(1)?.isAir || block.above(1)?.typeId.includes("minecraft:light_block") || block.above(1)?.typeId.includes("minecraft:snow_layer")) && !block.below(1)?.typeId.includes("minecraft:air")) {
              block.above(1)?.setType("minecraft:snow");
              system13.runTimeout(() => {
                if (block.above(1)?.typeId.includes("minecraft:snow")) {
                  block.above(1)?.setType("minecraft:air");
                }
              }, 500);
            }
          }
        } catch (error) {
          continue;
        }
      }
    }
  }
}, 1);
var SOUND_COOLDOWN = 9.5 * 20;
var COOLDOWN_NORMAL = "shapescape_bewe_blizzard_normal";
var COOLDOWN_SHELTER = "shapescape_bewe_blizzard_shelter";
world12.afterEvents.playerSpawn.subscribe((event) => {
  clear_cooldowns2(event.player);
});
function clear_cooldowns2(player) {
  player.removeTag(COOLDOWN_NORMAL);
  player.removeTag(COOLDOWN_SHELTER);
}
system13.runInterval(() => {
  blizzard_sound();
}, 1);
function blizzard_sound() {
  if ((world12.getDynamicProperty(
    "shapescape_bewe:settings.weather.blizzard"
  ) ?? true) === false)
    return;
  let players = world12.getPlayers();
  const WEATHER = world12.getDynamicProperty(
    "shapescape_bewe:environment_detection.weather"
  ) ?? "clear";
  if (WEATHER !== "thunderstorm")
    return;
  for (let player of players) {
    try {
      let in_shelter = false;
      let ray_location = {
        x: player.location.x,
        y: player.location.y + 1.5,
        z: player.location.z
      };
      let block = player.dimension.getBlockFromRay(
        ray_location,
        { x: 0, y: 1, z: 0 },
        { maxDistance: 16, includePassableBlocks: false }
      );
      if (player.dimension.getBlock(ray_location)?.isLiquid)
        in_shelter = true;
      if (block !== void 0)
        in_shelter = true;
      if (player.location.y < 55)
        in_shelter = true;
      if (player.hasTag(COOLDOWN_NORMAL)) {
        if (in_shelter === true) {
          player.removeTag(COOLDOWN_NORMAL);
          player.runCommand("/stopsound @s shapescape_bewe.blizzard");
        }
      }
      if (player.hasTag(COOLDOWN_SHELTER)) {
        if (in_shelter === false) {
          player.removeTag(COOLDOWN_SHELTER);
          player.runCommand("/stopsound @s shapescape_bewe.blizzard");
        }
      }
      const BIOME_TEMPERATURE = player.getDynamicProperty(
        "shapescape_bewe:environment_detection.biome_temperature"
      ) ?? 0.5;
      if (BIOME_TEMPERATURE > 0.15)
        continue;
      if (player.location.y < 50 || player.dimension.id !== "minecraft:overworld")
        continue;
      if (player.hasTag(COOLDOWN_NORMAL) || player.hasTag(COOLDOWN_SHELTER))
        continue;
      if (!in_shelter) {
        player.addTag(COOLDOWN_NORMAL);
        player.playSound("shapescape_bewe.blizzard", { volume: 0.7 });
      } else {
        player.addTag(COOLDOWN_SHELTER);
        player.playSound("shapescape_bewe.blizzard", { volume: 0.3 });
      }
      system13.runTimeout(() => {
        player.removeTag(COOLDOWN_NORMAL);
        player.removeTag(COOLDOWN_SHELTER);
      }, SOUND_COOLDOWN);
    } catch {
    }
  }
}

// data/system_template_esbuild/subscripts/broken_leg.ts
import {
  EntityComponentTypes as EntityComponentTypes3,
  EntityDamageCause as EntityDamageCause3,
  Player as Player5,
  system as system14,
  TicksPerSecond as TicksPerSecond2,
  world as world13
} from "@minecraft/server";
var DEBUG2 = false;
var slownessTime = 80;
var FALL_DAMAGE = 5;
var TAG = "shapescape_bewe_BROKEN_LEG_TIP";
world13.afterEvents.playerSpawn.subscribe((event) => {
  if (event.initialSpawn === false) {
    const player = event.player;
    player.setDynamicProperty("break_leg", false);
    player.removeTag(TAG);
    const movementComp = player.getComponent(EntityComponentTypes3.Movement);
    if (!movementComp)
      return;
    movementComp.setCurrentValue(movementComp?.defaultValue);
  }
});
world13.afterEvents.entityHurt.subscribe((event) => {
  const { damage, damageSource, hurtEntity } = event;
  if (damageSource.cause !== EntityDamageCause3.fall || !(hurtEntity instanceof Player5) || damage < FALL_DAMAGE)
    return;
  const player = hurtEntity;
  const setting = player.getDynamicProperty(
    `shapescape_bewe:settings.states.broken_leg`
  ) ?? true;
  if (!setting)
    return;
  if (player.getDynamicProperty("break_leg"))
    return;
  if (!player.hasTag(TAG)) {
    player.sendMessage({ translate: `shapescape_bewe.broken_leg.tip` });
    player.addTag(TAG);
  }
  player.playSound("shapescape_bewe.broken_leg.break", {
    volume: 0.75,
    pitch: 1.75
  });
  player.setDynamicProperty("break_leg", true);
  for (let index = 1; index < slownessTime * 4 + 1; index++) {
    if (index === 1) {
      const movementComp = player.getComponent(EntityComponentTypes3.Movement);
      if (!movementComp)
        return;
      player.playAnimation("animation.shapescape_bewe.player.hobbling");
      const newValue = movementComp.defaultValue * (index / (slownessTime * 4)) < 0.045 ? 0.045 : movementComp.defaultValue * (index / (slownessTime * 4));
      movementComp.setCurrentValue(newValue);
    }
    system14.runTimeout(() => {
      if (!player || player.getDynamicProperty("break_leg") === false)
        return;
      const setting2 = player.getDynamicProperty(
        `shapescape_bewe:settings.states.broken_leg`
      ) ?? true;
      const movementComp = player.getComponent(EntityComponentTypes3.Movement);
      if (!movementComp)
        return;
      const newValue = movementComp.defaultValue * (index / (slownessTime * 4)) < 0.045 ? 0.045 : movementComp.defaultValue * (index / (slownessTime * 4));
      movementComp.setCurrentValue(newValue);
      if (DEBUG2) {
        world13.sendMessage(JSON.stringify(newValue));
        world13.sendMessage(JSON.stringify(movementComp.defaultValue));
      }
      if (!setting2) {
        player.setDynamicProperty("break_leg", false);
        movementComp.setCurrentValue(movementComp.defaultValue);
        return;
      }
      if (newValue >= movementComp.defaultValue) {
        player.setDynamicProperty("break_leg", false);
      }
    }, index / 4 * TicksPerSecond2);
  }
});

// data/system_template_esbuild/subscripts/cracking_ice.ts
import {
  EntityComponentTypes as EntityComponentTypes4,
  EquipmentSlot as EquipmentSlot4,
  ItemComponentTypes,
  system as system15,
  TicksPerSecond as TicksPerSecond3,
  world as world14
} from "@minecraft/server";
var DATA2 = { "crack_cooldown": 1, "crack_around_chance": 0.5 };
var INTERVAL2 = DATA2.crack_cooldown * TicksPerSecond3;
var OFFSETS = [
  { x: 1, y: 0, z: 0 },
  { x: -1, y: 0, z: 0 },
  { x: 0, y: 0, z: 1 },
  { x: 0, y: 0, z: -1 },
  { x: 1, y: 0, z: 1 },
  { x: -1, y: 0, z: -1 },
  { x: 1, y: 0, z: -1 },
  { x: -1, y: 0, z: 1 }
];
system15.runInterval(() => {
  const players = world14.getAllPlayers();
  for (const player of players) {
    const setting = player.getDynamicProperty(`shapescape_bewe:settings.states.cracking_ice`) ?? true;
    if (!setting)
      continue;
    crackIce(player, { x: player.location.x, y: player.location.y - 1, z: player.location.z }, true);
  }
}, INTERVAL2);
function crackIce(player, location, initialCrack) {
  const enchantableComponent = player.getComponent(EntityComponentTypes4.Equippable)?.getEquipment(EquipmentSlot4.Feet)?.getComponent(ItemComponentTypes.Enchantable);
  if (enchantableComponent && enchantableComponent.getEnchantment("minecraft:frost_walker"))
    return;
  let blockToCheck = void 0;
  try {
    blockToCheck = player.dimension.getBlock(location);
  } catch {
  }
  const blockBelow = blockToCheck?.below(1);
  if (!blockToCheck || !blockBelow)
    return;
  if (blockBelow.typeId !== "minecraft:water" && blockBelow.typeId !== "minecraft:flowing_water")
    return;
  const dimension = blockToCheck.dimension;
  const particleLocation = { x: blockToCheck.center().x, y: blockToCheck.center().y + 0.5, z: blockToCheck.center().z };
  const pitch = 0.9 + Math.random() * 0.2;
  if (blockToCheck.typeId === "minecraft:ice") {
    if (initialCrack) {
      dimension.spawnParticle("shapescape_bewe:cracking_ice", particleLocation);
      dimension.playSound(`shapescape_bewe.cracking_ice.crack_0`, blockToCheck.location, {
        pitch
      });
    }
    blockToCheck.setType("shapescape_bewe:cracking_ice");
  } else if (blockToCheck.typeId === "shapescape_bewe:cracking_ice") {
    if (initialCrack) {
      dimension.spawnParticle("shapescape_bewe:cracking_ice", particleLocation);
      dimension.playSound(`shapescape_bewe.cracking_ice.crack_1`, blockToCheck.location, {
        pitch
      });
    }
    const permutation = blockToCheck.permutation.getState("shapescape_bewe:cracking_state");
    if (permutation === 0) {
      blockToCheck.setPermutation(blockToCheck.permutation.withState("shapescape_bewe:cracking_state", 1));
    } else if (permutation === 1) {
      blockToCheck.setType("minecraft:air");
      dimension.playSound(`random.glass`, blockToCheck.location);
    }
    if (initialCrack) {
      for (const offset of OFFSETS) {
        if (Math.random() < DATA2.crack_around_chance)
          continue;
        crackIce(
          player,
          {
            x: location.x + offset.x,
            y: location.y + offset.y,
            z: location.z + offset.z
          },
          false
        );
      }
    }
  }
}

// data/system_template_esbuild/subscripts/default_init.ts
import { world as world15 } from "@minecraft/server";
world15.afterEvents.worldLoad.subscribe(() => {
  defaultInit();
});
function defaultInit() {
  let scoreboard = world15.scoreboard.getObjective("shapescape_bewe_tmp");
  if (scoreboard == void 0) {
    world15.getDimension("overworld").runCommand("function shapescape/bewe/init");
  }
}

// data/system_template_esbuild/subscripts/enderstorm.ts
import {
  system as system16,
  world as world16,
  MolangVariableMap as MolangVariableMap5,
  BlockVolume as BlockVolume2,
  EntityComponentTypes as EntityComponentTypes5,
  EntityDamageCause as EntityDamageCause5,
  TicksPerSecond as TicksPerSecond4,
  GameMode as GameMode3
} from "@minecraft/server";
var DEBUG3 = false;
var REFRESH_RATE4 = 2 * TicksPerSecond4;
var THUNDER_CHANCE = 0.35;
var DURATION_LIMIT = 50 * TicksPerSecond4;
var COOLDOWN = (Math.random() + Math.random() + 5) * 60 * TicksPerSecond4;
var SOUND_COOLDOWN2 = 14 * TicksPerSecond4;
var LOUD_SOUND_TAG = `shapescape_bewe_ENDERSTORM_SOUND_LOUD`;
var QUIET_SOUND_TAG = `shapescape_bewe_ENDERSTORM_SOUND_QUIET`;
world16.afterEvents.playerSpawn.subscribe((event) => {
  clearTags(event.player);
});
function clearTags(player) {
  player.removeTag(LOUD_SOUND_TAG);
  player.removeTag(QUIET_SOUND_TAG);
}
system16.runInterval(() => {
  if ((world16.getDynamicProperty("shapescape_bewe:settings.weather.enderstorm") ?? true) === false) {
    world16.setDynamicProperty("enderstorm_duration", DURATION_LIMIT);
    world16.setDynamicProperty("enderstorm_cooldown", 0);
  }
  let duration = world16.getDynamicProperty("enderstorm_duration") ?? 0;
  let cooldown = world16.getDynamicProperty("enderstorm_cooldown") ?? 0;
  duration++;
  cooldown++;
  if (DEBUG3 && system16.currentTick % 20 === 0) {
    world16.sendMessage(JSON.stringify(duration));
    world16.sendMessage(JSON.stringify(cooldown));
  }
  if (duration > DURATION_LIMIT && cooldown > COOLDOWN) {
    world16.setDynamicProperty("enderstorm", true);
    duration = 0;
    cooldown = 0;
  }
  if (duration >= DURATION_LIMIT) {
    world16.getDimension("minecraft:overworld").runCommand("/stopsound @a shapescape_bewe.enderstorm.enderstorm");
    world16.setDynamicProperty("enderstorm", false);
    const tornadoes = world16.getDimension("minecraft:the_end").getEntities({
      type: "shapescape_bewe:ender_tornado"
    });
    for (const tornado of tornadoes) {
      if (tornado.isValid) {
        tornado.triggerEvent("shapescape_bewe:start_despawn");
      }
    }
    const players2 = world16.getAllPlayers();
    for (const player of players2) {
      player.runCommand(`/fog @s remove weather`);
      for (const tag of player.getTags()) {
        if (tag.includes("shapescape_bewe_ender_tornado_")) {
          const ender_tornadoID = tag.replace("shapescape_bewe_ender_tornado_", "");
          const ender_tornado = world16.getEntity(ender_tornadoID);
          player.removeTag(tag);
          ender_tornado?.remove();
        }
      }
    }
  }
  world16.setDynamicProperty("enderstorm_duration", duration);
  world16.setDynamicProperty("enderstorm_cooldown", cooldown);
  if (duration > DURATION_LIMIT && cooldown < COOLDOWN)
    return;
  if (DEBUG3) {
    world16.sendMessage("ENDERSTORM");
  }
  sounds();
  if (system16.currentTick % REFRESH_RATE4 !== 0)
    return;
  let players = world16.getPlayers();
  let alreadyProcessed = /* @__PURE__ */ new Set();
  for (let player of players) {
    const allowedGamemode = player.getGameMode() !== GameMode3.Creative && player.getGameMode() !== GameMode3.Spectator;
    if (!allowedGamemode)
      continue;
    if (player.dimension.id !== "minecraft:the_end")
      continue;
    const dimension = player.dimension;
    const location = player.location;
    let spawnEnderTornado = true;
    for (const tag of player.getTags()) {
      if (!tag.includes(`shapescape_bewe_ender_tornado_`))
        continue;
      spawnEnderTornado = false;
    }
    if (spawnEnderTornado) {
      const ender_tornado = dimension.spawnEntity("shapescape_bewe:ender_tornado", player.location);
      player.setPropertyOverrideForEntity(ender_tornado, "shapescape_bewe:visible", true);
      player.addTag(`shapescape_bewe_ender_tornado_${ender_tornado.id}`);
    }
    player.runCommand(`/fog @s push shapescape_bewe:the_end_stormy weather`);
    try {
      player.spawnParticle(`shapescape_bewe:enderstorm_cloud`, player.location);
      player.spawnParticle(`shapescape_bewe:enderstorm_dots`, player.location);
    } catch {
    }
    if (alreadyProcessed.has(player))
      continue;
    const nearbyPlayers = dimension.getEntities({
      location,
      maxDistance: 32,
      type: "minecraft:player"
    });
    for (let otherPlayer of nearbyPlayers) {
      if (otherPlayer.nameTag !== player.nameTag) {
        alreadyProcessed.add(otherPlayer);
      }
    }
    if (Math.random() > THUNDER_CHANCE) {
      if (Math.random() < 0.4) {
        distantThunder(player);
      } else {
        nearbyThunder(player);
      }
    }
  }
}, 1);
function distantThunder(player, index) {
  if (index && index > 10)
    return;
  index = index === void 0 ? 0 : ++index;
  const dimension = player.dimension;
  const location = player.location;
  let xModified = 1;
  let zModified = 1;
  if (Math.random() < 0.5) {
    xModified = Math.random();
  } else {
    zModified = Math.random();
  }
  const xNegPos = Math.random() > 0.5 ? -1 : 1;
  const zNegPos = Math.random() > 0.5 ? -1 : 1;
  const offset = {
    x: xModified * xNegPos * 50 + xNegPos * Math.random() * 50,
    y: 0,
    z: zModified * zNegPos * 50 + zNegPos * Math.random() * 50
  };
  const particleLocation = {
    x: location.x + offset.x,
    // between 100 and 200 blocks away (negative or positive)
    y: 40,
    // Sea level, lowest it can get, so it makes sure lightning always touches the ground
    z: location.z + offset.z
    // between 100 and 200 blocks away (negative or positive)
  };
  try {
    const block = dimension.getBlock(particleLocation);
    if (block) {
      const nearbyPlayers = dimension.getEntities({
        location,
        maxDistance: 32,
        type: "minecraft:player"
      });
      if (nearbyPlayers.length > 0) {
        distantThunder(player, index);
        return;
      }
    }
  } catch {
  }
  const molangVarMap = new MolangVariableMap5();
  molangVarMap.setVector3("position", offset);
  dimension.spawnParticle("shapescape_bewe:ender_lightning_bolt", { x: location.x, y: 40, z: location.z }, molangVarMap);
  const pitch = Math.random() * 0.2 + 0.9;
  dimension.playSound(`shapescape_bewe.thunderstorm.thunder_distant`, location, {
    volume: 5,
    pitch
  });
}
function nearbyThunder(player, index) {
  if (index && index > 10)
    return;
  index = index === void 0 ? 0 : ++index;
  const dimension = player.dimension;
  const location = player.location;
  const P1 = { x: location.x - 6, y: 200, z: location.z - 6 };
  const P2 = { x: location.x + 6, y: 200, z: location.z + 6 };
  const volume = new BlockVolume2(P1, P2);
  const locations = Array.from(volume.getBlockLocationIterator());
  const randomStrikeIndex = Math.floor(Math.random() * locations.length);
  const randomTeleportIndex = Math.floor(Math.random() * locations.length);
  const randomStrikePosData = locations[randomStrikeIndex];
  const randomTeleportPosData = locations[randomTeleportIndex];
  let strikeHeightMap = getHeightMap(dimension, randomStrikePosData);
  let teleportHeightMap = getHeightMap(dimension, randomTeleportPosData);
  const strikeLocation = {
    x: randomStrikePosData.x,
    y: strikeHeightMap,
    z: randomStrikePosData.z
  };
  const teleportLocation = {
    x: randomTeleportPosData.x,
    y: teleportHeightMap,
    z: randomTeleportPosData.z
  };
  const entities = dimension.getEntities({
    location: strikeLocation,
    maxDistance: 3
  });
  for (const entity of entities) {
    if (entity === player && teleportLocation !== void 0) {
      player.teleport(teleportLocation);
      player.applyDamage(4, { cause: EntityDamageCause5.lightning });
      dimension.playSound(`mob.shulker.teleport`, strikeLocation, {
        volume: 1,
        pitch: 1
      });
    }
    const familyTypes = entity.getComponent(EntityComponentTypes5.TypeFamily)?.getTypeFamilies();
    if (!familyTypes || !entity.typeId.includes("minecraft:"))
      continue;
    else if (familyTypes.includes("pig") && familyTypes.includes("mob")) {
      entity.triggerEvent(`become_zombie`);
    } else if (familyTypes.includes("mushroomcow") && familyTypes.includes("mob")) {
      const variant = entity.getComponent(EntityComponentTypes5.Variant)?.value;
      if (variant === void 0)
        continue;
      if (variant === 0) {
        entity.triggerEvent(`minecraft:become_brown`);
      } else if (variant === 1) {
        entity.triggerEvent(`minecraft:become_red`);
      }
    } else if (familyTypes.includes("creeper") && familyTypes.includes("monster") && familyTypes.includes("mob")) {
      entity.triggerEvent(`minecraft:become_charged`);
    } else if (familyTypes.includes("villager") && familyTypes.includes("mob")) {
      entity.triggerEvent(`become_witch`);
    } else {
      entity.applyDamage(10, {
        cause: EntityDamageCause5.lightning
      });
    }
  }
  const molangVarMap = new MolangVariableMap5();
  molangVarMap.setVector3("position", { x: 0, y: 0, z: 0 });
  dimension.spawnParticle("shapescape_bewe:ender_lightning_bolt", strikeLocation, molangVarMap);
  const pitch = Math.random() * 0.2 + 0.9;
  dimension.playSound(`shapescape_bewe.thunderstorm.thunder_nearby`, strikeLocation, {
    volume: 3,
    pitch
  });
}
function getHeightMap(dimension, position, maxScanDepth = 200) {
  const scanPosition = { x: position.x, y: 200, z: position.z };
  for (let index = 0; index < maxScanDepth; index++) {
    try {
      const blockToCheck = dimension.getBlock(scanPosition)?.below(index);
      if (blockToCheck && !blockToCheck.isAir && !blockToCheck.typeId.includes("minecraft:light_block")) {
        return blockToCheck.location.y + 1;
      }
    } catch {
      continue;
    }
  }
  return 0;
}
function sounds() {
  const players = world16.getPlayers();
  for (const player of players) {
    if (player.dimension.id !== "minecraft:the_end")
      continue;
    let in_shelter = false;
    let ray_location = { x: 0, y: 0, z: 0 };
    let block = void 0;
    try {
      ray_location = {
        x: player.location.x,
        y: player.location.y + 1.5,
        z: player.location.z
      };
      block = player.dimension.getBlockFromRay(
        ray_location,
        { x: 0, y: 1, z: 0 },
        { maxDistance: 16, includePassableBlocks: false }
      );
      if (player.dimension.getBlock(ray_location)?.isLiquid)
        in_shelter = true;
    } catch {
      continue;
    }
    if (block !== void 0)
      in_shelter = true;
    if (player.hasTag(LOUD_SOUND_TAG)) {
      if (in_shelter === true) {
        player.removeTag(LOUD_SOUND_TAG);
        player.runCommand("/stopsound @s shapescape_bewe.enderstorm.enderstorm");
      }
    }
    if (player.hasTag(QUIET_SOUND_TAG)) {
      if (in_shelter === false) {
        player.removeTag(QUIET_SOUND_TAG);
        player.runCommand("/stopsound @s shapescape_bewe.enderstorm.enderstorm");
      }
    }
    if (player.hasTag(LOUD_SOUND_TAG) || player.hasTag(QUIET_SOUND_TAG))
      continue;
    if (!in_shelter) {
      player.addTag(LOUD_SOUND_TAG);
      player.playSound("shapescape_bewe.enderstorm.enderstorm", { volume: 0.6 });
    } else {
      player.addTag(QUIET_SOUND_TAG);
      player.playSound("shapescape_bewe.enderstorm.enderstorm", { volume: 0.2 });
    }
    system16.runTimeout(() => {
      if (!player)
        return;
      player.removeTag(LOUD_SOUND_TAG);
      player.removeTag(QUIET_SOUND_TAG);
    }, SOUND_COOLDOWN2);
  }
}
system16.afterEvents.scriptEventReceive.subscribe((event) => {
  const message = event.message;
  const messageID = event.id;
  const entity = event.sourceEntity;
  if (!entity?.isValid)
    return;
  if (entity && messageID === "shapescape_bewe:ender_tornado" && message === "teleport") {
    const player = entity.dimension.getEntities({
      tags: [`shapescape_bewe_ender_tornado_${entity.id}`]
    })[0];
    if (player && player.isValid) {
      entity.teleport(player.location);
      let duration = world16.getDynamicProperty("enderstorm_duration") ?? 0;
      if (duration > DURATION_LIMIT)
        entity.triggerEvent(`shapescape_bewe:start_despawn`);
    } else {
      const isChested = entity.getComponent(EntityComponentTypes5.IsChested);
      if (!isChested)
        entity.triggerEvent(`shapescape_bewe:start_despawn`);
    }
  }
  if (entity && messageID === "shapescape_bewe:ender_tornado" && message === "despawn") {
    const players = entity.dimension.getEntities({
      tags: [`shapescape_bewe_ender_tornado_${entity.id}`]
    });
    for (const player of players) {
      player.removeTag(`shapescape_bewe_ender_tornado_${entity.id}`);
    }
  }
});
world16.afterEvents.playerSpawn.subscribe((event) => {
  const player = event.player;
  for (const tag of player.getTags()) {
    if (tag.includes("shapescape_bewe_ender_tornado_")) {
      const ender_tornadoID = tag.replace("shapescape_bewe_ender_tornado_", "");
      const ender_tornado = world16.getEntity(ender_tornadoID);
      player.removeTag(tag);
      ender_tornado?.remove();
    }
  }
});
system16.afterEvents.scriptEventReceive.subscribe((event) => {
  const message = event.message;
  const messageID = event.id;
  const entity = event.sourceEntity;
  if (!entity?.isValid)
    return;
  if (entity && messageID === "shapescape_bewe:enderstorm" && message === "dev_start") {
    world16.setDynamicProperty("enderstorm_duration", DURATION_LIMIT);
    world16.setDynamicProperty("enderstorm_cooldown", COOLDOWN);
  }
});

// data/system_template_esbuild/subscripts/environment_detection.ts
import { system as system17, world as world17 } from "@minecraft/server";
var DEBUG4 = false;
var REFRESH_RATE5 = 1 * 20;
system17.afterEvents.scriptEventReceive.subscribe((event) => {
  if (event.sourceEntity?.typeId !== "minecraft:player")
    return;
  let player = event.sourceEntity;
  if (event.id === `shapescape_bewe:environment_detection.weather` && event.message) {
    world17.setDynamicProperty("shapescape_bewe:environment_detection.weather", event.message);
  }
  if (event.id === `shapescape_bewe:environment_detection.light_level` && event.message) {
    player.setDynamicProperty("shapescape_bewe:environment_detection.light_level", parseInt(event.message));
  }
  if (event.id === `shapescape_bewe:environment_detection.biome` && event.message) {
    player.setDynamicProperty("shapescape_bewe:environment_detection.biome", event.message);
  }
  if (event.id === `shapescape_bewe:environment_detection.biome_tags` && event.message) {
    let biomeTags = [];
    let biomeTagsProperty = player.getDynamicProperty("shapescape_bewe:environment_detection.biome_tags");
    if (biomeTagsProperty && typeof biomeTagsProperty === "string") {
      biomeTags = JSON.parse(biomeTagsProperty);
    }
    biomeTags.push(event.message);
    player.setDynamicProperty("shapescape_bewe:environment_detection.biome_tags", JSON.stringify(biomeTags));
  }
  if (event.id === `shapescape_bewe:environment_detection.biome_temperature` && event.message) {
    player.setDynamicProperty("shapescape_bewe:environment_detection.biome_temperature", parseFloat(event.message));
  }
});
function get_environment_info(player) {
  if (DEBUG4) {
    let weather2 = "None";
    let lightLevel = "None";
    let biome = "None";
    let biomeTags = "None";
    let biomeTemperature = "None";
    if (world17.getDynamicProperty("shapescape_bewe:environment_detection.weather") !== void 0) {
      weather2 = world17.getDynamicProperty("shapescape_bewe:environment_detection.weather");
    }
    if (player.getDynamicProperty("shapescape_bewe:environment_detection.light_level") !== void 0) {
      lightLevel = player.getDynamicProperty("shapescape_bewe:environment_detection.light_level");
    }
    if (player.getDynamicProperty("shapescape_bewe:environment_detection.biome") !== void 0) {
      biome = player.getDynamicProperty("shapescape_bewe:environment_detection.biome");
    }
    if (player.getDynamicProperty("shapescape_bewe:environment_detection.biome_tags") !== void 0) {
      biomeTags = player.getDynamicProperty("shapescape_bewe:environment_detection.biome_tags");
    }
    if (player.getDynamicProperty("shapescape_bewe:environment_detection.biome_temperature") !== void 0) {
      biomeTemperature = player.getDynamicProperty("shapescape_bewe:environment_detection.biome_temperature");
    }
    let rawtext = {
      text: `\xA7bBiome: \xA7f${biome} \xA76| \xA7bBiome Temperature: \xA7f${biomeTemperature} \xA76| \xA7bWeather: \xA7f${weather2} \xA76| \xA7bLight Level: \xA7f${lightLevel} \xA76|
\xA7bBiome Tags: \xA7f${biomeTags}`
    };
    player.onScreenDisplay.setActionBar(rawtext);
  }
  player.setDynamicProperty("shapescape_bewe:environment_detection.biome_tags", "[]");
  player.dimension.spawnEntity("shapescape_bewe:environment_detection", player.location);
}
system17.runInterval(() => {
  let players = world17.getPlayers();
  for (let player of players) {
    try {
      get_environment_info(player);
    } catch {
    }
  }
}, REFRESH_RATE5);

// data/system_template_esbuild/subscripts/after_rain_fog.ts
import { system as system18, world as world18, MolangVariableMap as MolangVariableMap6 } from "@minecraft/server";
var DEBUG5 = false;
var REFRESH_RATE6 = 1 * 20;
var AFTER_RAIN_FOG_DURATION = 90;
var LastWeather2 = "clear";
var CurrentWeather2 = "clear";
var after_rain_fog_iteration = 0;
var after_rain_fog_cooldown = 0;
world18.afterEvents.worldLoad.subscribe(() => {
  LastWeather2 = world18.getDynamicProperty("shapescape_bewe:environment_detection.weather") ?? "clear";
  CurrentWeather2 = world18.getDynamicProperty("shapescape_bewe:environment_detection.weather") ?? "clear";
  world18.setDynamicProperty("shapescape_bewe:after_rain_fog_iteration", after_rain_fog_iteration);
});
function getRandomNumber2(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}
system18.runInterval(() => {
  let Weather = world18.getDynamicProperty("shapescape_bewe:environment_detection.weather") ?? "clear";
  if (Weather != CurrentWeather2) {
    LastWeather2 = CurrentWeather2;
    CurrentWeather2 = Weather;
    if (LastWeather2 === "rain" && CurrentWeather2 === "clear") {
      if (DEBUG5)
        world18.sendMessage("After rain fog");
      after_rain_fog();
      after_rain_fog_iteration = AFTER_RAIN_FOG_DURATION / 5;
      world18.setDynamicProperty("shapescape_bewe:after_rain_fog_iteration", after_rain_fog_iteration);
    }
  }
  if (after_rain_fog_iteration > 0) {
    if (after_rain_fog_cooldown === 0) {
      after_rain_fog_cooldown = 1;
      system18.runTimeout(() => {
        if (after_rain_fog_iteration > 2) {
          after_rain_fog();
        }
        after_rain_fog_cooldown = 0;
        after_rain_fog_iteration -= 1;
        world18.setDynamicProperty("shapescape_bewe:after_rain_fog_iteration", after_rain_fog_iteration);
        if (DEBUG5)
          world18.sendMessage(`After rain fog trigger. Left: ${after_rain_fog_iteration}`);
      }, 5 * 20);
    }
  }
}, REFRESH_RATE6);
function after_rain_fog() {
  if ((world18.getDynamicProperty("shapescape_bewe:settings.weather.after_rain_fog") ?? true) === false)
    return;
  let players = world18.getPlayers();
  let alreadyProcessed = /* @__PURE__ */ new Set();
  for (let player of players) {
    try {
      if (player.location.y < 40)
        continue;
      if (player.dimension.id !== "minecraft:overworld")
        continue;
      if (alreadyProcessed.has(player))
        continue;
      const nearbyPlayers = player.dimension.getEntities({
        location: player.location,
        maxDistance: 64,
        type: "minecraft:player"
      });
      for (let otherPlayer of nearbyPlayers) {
        if (otherPlayer.nameTag !== player.nameTag) {
          alreadyProcessed.add(otherPlayer);
        }
      }
      const BIOME_TEMPERATURE = player.getDynamicProperty("shapescape_bewe:environment_detection.biome_temperature") ?? 0.5;
      let fog_type = "normal";
      if (BIOME_TEMPERATURE >= 1)
        continue;
      if (BIOME_TEMPERATURE >= 0.15)
        fog_type = "normal";
      if (BIOME_TEMPERATURE < 0.15)
        fog_type = "cold";
      const fogMolang = new MolangVariableMap6();
      const lifetime = getRandomNumber2(8, 10);
      fogMolang.setFloat("distance_min", 15);
      fogMolang.setFloat("distance_max", 120);
      fogMolang.setFloat("lifetime", lifetime);
      if (fog_type === "normal") {
        fogMolang.setFloat("density", 200);
        fogMolang.setFloat("color_r", 0.7);
        fogMolang.setFloat("color_g", 0.7);
        fogMolang.setFloat("color_b", 0.7);
        fogMolang.setFloat("max_opacity", 0.35);
      }
      if (fog_type === "cold") {
        fogMolang.setFloat("density", 200);
        fogMolang.setFloat("color_r", 1);
        fogMolang.setFloat("color_g", 1);
        fogMolang.setFloat("color_b", 1);
        fogMolang.setFloat("max_opacity", 0.45);
      }
      let location = { x: player.location.x, y: 70, z: player.location.z };
      player.dimension.spawnParticle("shapescape_bewe:3d_fog_emitter", location, fogMolang);
    } catch {
    }
  }
}

// data/system_template_esbuild/subscripts/morning_fog.ts
import { system as system19, world as world19, MolangVariableMap as MolangVariableMap7 } from "@minecraft/server";
var DEBUG6 = false;
function getRandomNumber3(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}
var TRIGGER_COOLDOWN = 8 * 20;
system19.runInterval(() => {
  if ((world19.getDynamicProperty("shapescape_bewe:settings.weather.morning_fog") ?? true) === false)
    return;
  const time = world19.getTimeOfDay();
  if (time > 23e3 || time < 400) {
    if (DEBUG6)
      world19.sendMessage("Morning fog trigger");
    morning_fog();
  }
}, TRIGGER_COOLDOWN);
function morning_fog() {
  let players = world19.getPlayers();
  let alreadyProcessed = /* @__PURE__ */ new Set();
  for (let player of players) {
    try {
      if (player.location.y < 40)
        continue;
      if (player.dimension.id !== "minecraft:overworld")
        continue;
      if (alreadyProcessed.has(player))
        continue;
      const nearbyPlayers = player.dimension.getEntities({
        location: player.location,
        maxDistance: 64,
        type: "minecraft:player"
      });
      for (let otherPlayer of nearbyPlayers) {
        if (otherPlayer.nameTag !== player.nameTag) {
          alreadyProcessed.add(otherPlayer);
        }
      }
      const BIOME_TEMPERATURE = player.getDynamicProperty("shapescape_bewe:environment_detection.biome_temperature") ?? 0.5;
      const biome = player.getDynamicProperty("shapescape_bewe:environment_detection.biome") ?? "";
      const biomeTagsProperty = player.getDynamicProperty("shapescape_bewe:environment_detection.biome_tags") ?? "[]";
      const biomeTags = JSON.parse(biomeTagsProperty);
      let fog_type = "normal";
      if (BIOME_TEMPERATURE >= 1)
        continue;
      if (BIOME_TEMPERATURE >= 0.15)
        fog_type = "normal";
      if (BIOME_TEMPERATURE < 0.15)
        fog_type = "cold";
      if (biomeTags.includes("jungle") || biome === "jungle")
        fog_type = "jungle";
      if (biomeTags.includes("swamp") || biomeTags.includes("mangrove_swamp") || biome === "swamp")
        fog_type = "swamp";
      const fogMolang = new MolangVariableMap7();
      const lifetime = getRandomNumber3(10, 15);
      fogMolang.setFloat("distance_min", 5);
      fogMolang.setFloat("distance_max", 120);
      fogMolang.setFloat("lifetime", lifetime);
      if (fog_type === "normal") {
        fogMolang.setFloat("density", 300);
        fogMolang.setFloat("color_r", 0.85);
        fogMolang.setFloat("color_g", 1);
        fogMolang.setFloat("color_b", 0.85);
        fogMolang.setFloat("max_opacity", 0.2);
      }
      if (fog_type === "jungle") {
        fogMolang.setFloat("density", 300);
        fogMolang.setFloat("color_r", 0.5);
        fogMolang.setFloat("color_g", 1);
        fogMolang.setFloat("color_b", 0.5);
        fogMolang.setFloat("max_opacity", 0.2);
      }
      if (fog_type === "swamp") {
        fogMolang.setFloat("density", 300);
        fogMolang.setFloat("color_r", 0.1);
        fogMolang.setFloat("color_g", 0.3);
        fogMolang.setFloat("color_b", 0);
        fogMolang.setFloat("max_opacity", 0.25);
      }
      if (fog_type === "cold") {
        fogMolang.setFloat("density", 300);
        fogMolang.setFloat("color_r", 1);
        fogMolang.setFloat("color_g", 1);
        fogMolang.setFloat("color_b", 1);
        fogMolang.setFloat("max_opacity", 0.2);
      }
      let location = { x: player.location.x, y: 70, z: player.location.z };
      player.dimension.spawnParticle("shapescape_bewe:3d_fog_emitter", location, fogMolang);
    } catch {
    }
  }
}

// data/system_template_esbuild/subscripts/biome_fog.ts
import { system as system20, world as world20, MolangVariableMap as MolangVariableMap8 } from "@minecraft/server";
var DEBUG7 = false;
function getRandomNumber4(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}
var TRIGGER_COOLDOWN2 = 8.1 * 20;
system20.runInterval(() => {
  if ((world20.getDynamicProperty("shapescape_bewe:settings.weather.biome_fog") ?? true) === false)
    return;
  const WEATHER = world20.getDynamicProperty("shapescape_bewe:environment_detection.weather") ?? "clear";
  if (WEATHER !== "clear")
    return;
  let afterRainFog = world20.getDynamicProperty("shapescape_bewe:after_rain_fog_iteration") ?? 0;
  if (afterRainFog > 0)
    return;
  const time = world20.getTimeOfDay();
  if (time > 22500 || time < 600)
    return;
  if (time > 14e3 && time < 22e3)
    return;
  if (DEBUG7)
    world20.sendMessage("Biome fog trigger");
  biome_fog();
}, TRIGGER_COOLDOWN2);
function biome_fog() {
  let players = world20.getPlayers();
  let alreadyProcessed = /* @__PURE__ */ new Set();
  for (let player of players) {
    try {
      if (player.location.y < 40)
        continue;
      if (player.dimension.id !== "minecraft:overworld")
        continue;
      if (alreadyProcessed.has(player))
        continue;
      const nearbyPlayers = player.dimension.getEntities({
        location: player.location,
        maxDistance: 64,
        type: "minecraft:player"
      });
      for (let otherPlayer of nearbyPlayers) {
        if (otherPlayer.nameTag !== player.nameTag) {
          alreadyProcessed.add(otherPlayer);
        }
      }
      const BIOME_TEMPERATURE = player.getDynamicProperty("shapescape_bewe:environment_detection.biome_temperature") ?? 0.5;
      const biome = player.getDynamicProperty("shapescape_bewe:environment_detection.biome") ?? "";
      const biomeTagsProperty = player.getDynamicProperty("shapescape_bewe:environment_detection.biome_tags") ?? "[]";
      const biomeTags = JSON.parse(biomeTagsProperty);
      let fog_type = "none";
      if (BIOME_TEMPERATURE >= 1)
        continue;
      if (biomeTags.length === 0 || biome === "")
        continue;
      if (BIOME_TEMPERATURE < 0.15)
        fog_type = "cold";
      if (biomeTags.includes("jungle") || biome === "jungle")
        fog_type = "jungle";
      if (biomeTags.includes("swamp") || biomeTags.includes("mangrove_swamp") || biome === "swamp")
        fog_type = "swamp";
      if (fog_type === "none")
        continue;
      const fogMolang = new MolangVariableMap8();
      const lifetime = getRandomNumber4(8, 12);
      fogMolang.setFloat("distance_min", 5);
      fogMolang.setFloat("distance_max", 80);
      fogMolang.setFloat("lifetime", lifetime);
      if (fog_type === "jungle") {
        fogMolang.setFloat("density", 100);
        fogMolang.setFloat("color_r", 0.3);
        fogMolang.setFloat("color_g", 0.8);
        fogMolang.setFloat("color_b", 0.3);
        fogMolang.setFloat("max_opacity", 0.2);
      }
      if (fog_type === "swamp") {
        fogMolang.setFloat("density", 80);
        fogMolang.setFloat("color_r", 0.3);
        fogMolang.setFloat("color_g", 0.4);
        fogMolang.setFloat("color_b", 0.2);
        fogMolang.setFloat("max_opacity", 0.3);
      }
      if (fog_type === "cold") {
        fogMolang.setFloat("density", 150);
        fogMolang.setFloat("color_r", 1);
        fogMolang.setFloat("color_g", 1);
        fogMolang.setFloat("color_b", 1);
        fogMolang.setFloat("max_opacity", 0.25);
      }
      let location = { x: player.location.x, y: 70, z: player.location.z };
      player.dimension.spawnParticle("shapescape_bewe:ground_fog_emitter", location, fogMolang);
    } catch {
    }
  }
}

// data/system_template_esbuild/subscripts/blizzard_fog.ts
import { system as system21, world as world21, MolangVariableMap as MolangVariableMap9 } from "@minecraft/server";
var REFRESH_RATE7 = 8 * 20;
system21.runInterval(() => {
  if ((world21.getDynamicProperty("shapescape_bewe:settings.weather.blizzard") ?? true) === false)
    return;
  let players = world21.getPlayers();
  let alreadyProcessed = /* @__PURE__ */ new Set();
  const WEATHER = world21.getDynamicProperty("shapescape_bewe:environment_detection.weather") ?? "clear";
  if (WEATHER !== "thunderstorm")
    return;
  for (let player of players) {
    try {
      if (alreadyProcessed.has(player))
        continue;
      const nearbyPlayers = player.dimension.getEntities({
        location: player.location,
        maxDistance: 32,
        type: "minecraft:player"
      });
      for (let otherPlayer of nearbyPlayers) {
        if (otherPlayer.nameTag !== player.nameTag) {
          alreadyProcessed.add(otherPlayer);
        }
      }
      const BIOME_TEMPERATURE = player.getDynamicProperty("shapescape_bewe:environment_detection.biome_temperature") ?? 0.5;
      if (BIOME_TEMPERATURE > 0.15)
        continue;
      if (player.location.y < 40 || player.dimension.id !== "minecraft:overworld")
        continue;
      const fogMolang = new MolangVariableMap9();
      fogMolang.setFloat("distance_min", 5);
      fogMolang.setFloat("distance_max", 20);
      fogMolang.setFloat("lifetime", 9);
      fogMolang.setFloat("density", 15);
      fogMolang.setFloat("color_r", 1);
      fogMolang.setFloat("color_g", 1);
      fogMolang.setFloat("color_b", 1);
      fogMolang.setFloat("max_opacity", 0.3);
      let location = { x: player.location.x, y: 70, z: player.location.z };
      player.dimension.spawnParticle("shapescape_bewe:ground_fog_emitter", location, fogMolang);
    } catch {
    }
  }
}, REFRESH_RATE7);

// data/system_template_esbuild/subscripts/night_fog.ts
import { system as system23, world as world23, MolangVariableMap as MolangVariableMap10 } from "@minecraft/server";
var REFRESH_RATE8 = 7 * 20;
function getRandomNumber5(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}
system23.runInterval(() => {
  if ((world23.getDynamicProperty("shapescape_bewe:settings.weather.night_fog") ?? true) === false)
    return;
  const time = world23.getTimeOfDay();
  if (time > 14e3 && time < 22e3) {
    night_fog();
  }
}, REFRESH_RATE8);
function night_fog() {
  let players = world23.getPlayers();
  let alreadyProcessed = /* @__PURE__ */ new Set();
  for (let player of players) {
    try {
      if (player.location.y < 40)
        continue;
      if (player.dimension.id !== "minecraft:overworld")
        continue;
      if (alreadyProcessed.has(player))
        continue;
      const nearbyPlayers = player.dimension.getEntities({
        location: player.location,
        maxDistance: 64,
        type: "minecraft:player"
      });
      for (let otherPlayer of nearbyPlayers) {
        if (otherPlayer.nameTag !== player.nameTag) {
          alreadyProcessed.add(otherPlayer);
        }
      }
      const BIOME_TEMPERATURE = player.getDynamicProperty("shapescape_bewe:environment_detection.biome_temperature") ?? 0.5;
      let fog_type = "normal";
      if (BIOME_TEMPERATURE >= 1)
        continue;
      if (BIOME_TEMPERATURE >= 0.15)
        fog_type = "normal";
      if (BIOME_TEMPERATURE < 0.15)
        fog_type = "cold";
      const fogMolang = new MolangVariableMap10();
      const lifetime = getRandomNumber5(8, 10);
      fogMolang.setFloat("distance_min", 15);
      fogMolang.setFloat("distance_max", 120);
      fogMolang.setFloat("lifetime", lifetime);
      if (fog_type === "normal") {
        fogMolang.setFloat("density", 30);
        fogMolang.setFloat("color_r", 0.3);
        fogMolang.setFloat("color_g", 0.3);
        fogMolang.setFloat("color_b", 0.3);
        fogMolang.setFloat("max_opacity", 0.45);
      }
      if (fog_type === "cold") {
        fogMolang.setFloat("density", 30);
        fogMolang.setFloat("color_r", 0.9);
        fogMolang.setFloat("color_g", 0.9);
        fogMolang.setFloat("color_b", 0.9);
        fogMolang.setFloat("max_opacity", 0.45);
      }
      let location = { x: player.location.x, y: 70, z: player.location.z };
      player.dimension.spawnParticle("shapescape_bewe:3d_fog_emitter", location, fogMolang);
    } catch {
    }
  }
}

// data/system_template_esbuild/subscripts/fog_controll.ts
import { system as system24, world as world24 } from "@minecraft/server";
var DEBUG8 = false;
var biomesWithFog = [
  "basalt_deltas",
  "soulsand_valley",
  "warped_forest",
  "crimson_forest",
  "hell",
  "the_end",
  "desert",
  "savanna",
  "mesa",
  "swamp",
  "ice",
  "taiga",
  "mangrove_swamp",
  "extreme_hills",
  "jungle",
  "mushroom_island"
];
var weather = "clear";
world24.afterEvents.playerSpawn.subscribe(() => {
  onReload();
});
function onReload() {
  let players = world24.getPlayers();
  for (let player of players) {
    player.setDynamicProperty("shapescape_bewe:fog_system.biome_previous", "none");
    world24.setDynamicProperty("shapescape_bewe:fog_system.weather_previous", "clear");
  }
}
system24.afterEvents.scriptEventReceive.subscribe(({ id, sourceEntity }) => {
  if (sourceEntity === void 0 || sourceEntity?.typeId !== "minecraft:player")
    return;
  if (id === "shapescape_bewe:fogs.turn_off") {
    sourceEntity.runCommand("/fog @s remove climatic");
    sourceEntity.runCommand("/fog @s remove weather");
  }
  if (id === "shapescape_bewe:fogs.turn_on") {
    onReload();
  }
});
system24.runInterval(() => {
  let players = world24.getPlayers();
  for (let player of players) {
    if (world24.getDynamicProperty("shapescape_bewe:settings.weather.fogs") ?? true) {
      try {
        let biomeCurrent = getCurrentBiome(player);
        const biomeUnified = unifyingBiomes(biomeCurrent);
        weather = world24.getDynamicProperty("shapescape_bewe:environment_detection.weather") ?? "clear";
        const biomeLast = player.getDynamicProperty("shapescape_bewe:fog_system.biome_previous") ?? "none";
        fogClimaticDependingOnBiome(player, biomeCurrent, biomeLast, biomeUnified);
        fogControllDependingOnWeather(player, biomeCurrent, biomeLast, biomeUnified);
      } catch {
      }
    }
  }
}, 5);
function getCurrentBiome(player) {
  const biomesWanted = ["mangrove_swamp"];
  let biomeTagsString = player.getDynamicProperty("shapescape_bewe:fog_system.biome_tags") ?? '["none"]';
  if (player.getDynamicProperty("shapescape_bewe:environment_detection.biome_tags") !== "[]") {
    biomeTagsString = player.getDynamicProperty("shapescape_bewe:environment_detection.biome_tags");
    player.setDynamicProperty("shapescape_bewe:fog_system.biome_tags", biomeTagsString);
  }
  const biomeTags = JSON.parse(biomeTagsString);
  for (let biomeTag of biomeTags) {
    for (let biomeWanted of biomesWanted) {
      if (biomeTag === biomeWanted)
        return biomeTag;
      else
        return player.getDynamicProperty("shapescape_bewe:environment_detection.biome");
    }
  }
}
function unifyingBiomes(biomeCurrent) {
  if (biomeCurrent == "mangrove_swamp")
    return "swamp";
  if (biomeCurrent == "taiga" || biomeCurrent == "extreme_hills")
    return "ice";
  return biomeCurrent;
}
function fogClimaticDependingOnBiome(player, biomeCurrent, biomeLast, biomeUnified) {
  const intervalStatusClimatic = player.getDynamicProperty("shapescape_bewe:fog_system.interval_status_climatic") ?? "stopInterval";
  const fogStatus = world24.getDynamicProperty("shapescape_bewe:fog_system.weather_previous") ?? "clear";
  if (biomeCurrent !== biomeLast && weather === "clear" || weather === "clear" && fogStatus !== "clear") {
    world24.setDynamicProperty("shapescape_bewe:fog_system.weather_previous", "clear");
    if (biomesWithFog.includes(biomeCurrent)) {
      player.runCommand("/fog @s remove climatic");
      player.runCommand("/fog @s push shapescape_bewe:" + biomeUnified + "_climatic climatic");
      player.setDynamicProperty("shapescape_bewe:fog_system.biome_previous", biomeCurrent);
      player.setDynamicProperty("shapescape_bewe:fog_system.interval_status_climatic", "runInterval");
      if (DEBUG8)
        player.sendMessage("push fog climatic - " + biomeUnified);
    } else {
      player.runCommand("/fog @s remove climatic");
      player.runCommand("/fog @s remove weather");
      player.setDynamicProperty("shapescape_bewe:fog_system.interval_status_climatic", "stopInterval");
      player.setDynamicProperty("shapescape_bewe:fog_system.biome_previous", biomeCurrent);
      if (DEBUG8)
        player.sendMessage("Remove fog climatic - biome without fog");
    }
  } else if (weather !== "clear" && intervalStatusClimatic === "runInterval") {
    player.runCommand("/fog @s remove climatic");
    player.setDynamicProperty("shapescape_bewe:fog_system.interval_status_climatic", "stopInterval");
    player.setDynamicProperty("shapescape_bewe:fog_system.biome_previous", "none");
    if (DEBUG8)
      player.sendMessage("Remove fog climatic - weather is not clear");
  }
}
function fogControllDependingOnWeather(player, biomeCurrent, biomeLast, biomeUnified) {
  const fogStatus = world24.getDynamicProperty("shapescape_bewe:fog_system.weather_previous") ?? "clear";
  if (biomeCurrent !== biomeLast && weather === "rain" || weather === "rain" && fogStatus != "rain") {
    player.setDynamicProperty("shapescape_bewe:fog_system.interval_status_not_clear", "runInterval");
    player.setDynamicProperty("shapescape_bewe:fog_system.biome_previous", biomeCurrent);
    fogRainy(player, biomeCurrent, biomeUnified);
    world24.setDynamicProperty("shapescape_bewe:fog_system.weather_previous", "rain");
    if (DEBUG8)
      player.sendMessage("weather rain");
  } else if (biomeCurrent !== biomeLast && weather === "thunderstorm" || weather === "thunderstorm" && fogStatus != "thunderstorm") {
    player.setDynamicProperty("shapescape_bewe:fog_system.interval_status_not_clear", "runInterval");
    player.setDynamicProperty("shapescape_bewe:fog_system.biome_previous", biomeCurrent);
    fogStormy(player, biomeCurrent, biomeUnified);
    world24.setDynamicProperty("shapescape_bewe:fog_system.weather_previous", "thunderstorm");
    if (DEBUG8)
      player.sendMessage("weather thunderstorm");
  } else if (weather === "clear" && fogStatus != "clear") {
    if (DEBUG8)
      player.sendMessage("weather is clear");
    player.runCommand("/fog @s remove weather");
    player.setDynamicProperty("shapescape_bewe:fog_system.interval_status_not_clear", "stopInterval");
    world24.setDynamicProperty("shapescape_bewe:fog_system.weather_previous", "clear");
  }
}
function fogRainy(player, biomeCurrent, biomeUnified) {
  if (weather === "rain") {
    player.runCommand("/fog @s remove weather");
    if (!biomesWithFog.includes(biomeCurrent))
      biomeUnified = "general";
    player.runCommand("/fog @s push shapescape_bewe:" + biomeUnified + "_rainy weather");
    if (DEBUG8)
      player.sendMessage("Applying fog rainy on biome: " + biomeCurrent);
  } else if (weather !== "rain") {
    player.runCommand("/fog @s remove weather");
    player.setDynamicProperty("shapescape_bewe:fog_system.biome_previous", "none");
    if (DEBUG8)
      player.sendMessage("clear fog after rain");
  }
}
function fogStormy(player, biomeCurrent, biomeUnified) {
  if (weather === "thunderstorm") {
    player.runCommand("/fog @s remove weather");
    if (!biomesWithFog.includes(biomeCurrent))
      biomeUnified = "general";
    player.runCommand("/fog @s push shapescape_bewe:" + biomeUnified + "_stormy weather");
    if (DEBUG8)
      player.sendMessage("Applying fog stormy on biome: " + biomeCurrent);
  } else if (weather !== "thunderstorm") {
    player.runCommand("/fog @s remove weather");
    player.setDynamicProperty("shapescape_bewe:fog_system.biome_previous", "none");
    if (DEBUG8)
      player.sendMessage("clear fog after storm");
  }
}

// data/system_template_esbuild/subscripts/hail.ts
import {
  system as system25,
  world as world25,
  BlockVolume as BlockVolume3,
  GameMode as GameMode4,
  WeatherType as WeatherType2,
  TicksPerSecond as TicksPerSecond5
} from "@minecraft/server";
var DEBUG9 = false;
var REFRESH_RATE9 = 3 * TicksPerSecond5;
var HAIL_DURATION = 90 * TicksPerSecond5;
var lastTimeOfDay = 0;
var DIFFICULTY_TABLE = /* @__PURE__ */ new Map([
  [1, 1],
  // Easy == 1 damage per cycle
  [2, 2],
  // Normal == 2 damage per cycle
  [3, 3]
  // Hard == 2 damage per cycle
]);
system25.runInterval(() => {
  if (system25.currentTick % REFRESH_RATE9 !== 0)
    return;
  let players = world25.getPlayers();
  let alreadyProcessed = /* @__PURE__ */ new Set();
  const hailDuration = world25.getDynamicProperty("hail_duration") ?? 0;
  const WEATHER = world25.getDynamicProperty("shapescape_bewe:environment_detection.weather") ?? "clear";
  if (hailDuration <= 0 || WEATHER === "thunderstorm")
    return;
  world25.getDimension("minecraft:overworld").setWeather(WeatherType2.Clear, REFRESH_RATE9 * 2);
  if (hailDuration > 0) {
    world25.setDynamicProperty("hail_duration", hailDuration - REFRESH_RATE9);
    if (DEBUG9) {
      world25.sendMessage(`${hailDuration - REFRESH_RATE9}`);
    }
  } else {
    world25.setDynamicProperty("hail_duration", 0);
  }
  for (let player of players) {
    const dimension = player.dimension;
    const location = player.location;
    if (location.y < 40 || dimension.id !== "minecraft:overworld")
      continue;
    const biome = player.getDynamicProperty("shapescape_bewe:environment_detection.biome") ?? "";
    const biomeTagsProperty = player.getDynamicProperty("shapescape_bewe:environment_detection.biome_tags") ?? "[]";
    const biomeTags = JSON.parse(biomeTagsProperty);
    if (biome === "")
      continue;
    if (biomeTags.includes("desert") || biome === "desert" || biomeTags.includes("mesa") || biome === "mesa" || biomeTags.includes("ice") || biome === "ice" || biomeTags.includes("cold") || biome === "cold" || biomeTags.includes("frozen") || biome === "frozen")
      continue;
    const BIOME_TEMPERATURE = player.getDynamicProperty("shapescape_bewe:environment_detection.biome_temperature") ?? 0.5;
    if (BIOME_TEMPERATURE < 0.15 || BIOME_TEMPERATURE > 1)
      continue;
    const allowedGamemode = player.getGameMode() !== GameMode4.Creative && player.getGameMode() !== GameMode4.Spectator;
    if (allowedGamemode && !hasRoof(location, dimension)) {
      const difficulty2 = player.getDynamicProperty(`shapescape_bewe:settings.options.difficulty`) ?? 0;
      const damage = DIFFICULTY_TABLE.get(difficulty2) ?? 1;
      player.applyDamage(damage);
    }
    if (alreadyProcessed.has(player))
      continue;
    const nearbyPlayers = dimension.getEntities({
      location,
      maxDistance: 32,
      type: "minecraft:player"
    });
    for (let otherPlayer of nearbyPlayers) {
      if (otherPlayer.nameTag !== player.nameTag) {
        alreadyProcessed.add(otherPlayer);
      }
    }
    try {
      player.dimension.spawnParticle("shapescape_bewe:water_circle_hail", player.location);
    } catch {
    }
  }
}, 1);
function hasRoof(location, dimension) {
  if (location.y < 40)
    return true;
  const P1 = {
    x: location.x,
    y: location.y + 1,
    z: location.z
  };
  const P2 = {
    x: location.x,
    y: location.y + 20,
    z: location.z
  };
  const volume = new BlockVolume3(P1, P2);
  const locations = volume.getBlockLocationIterator();
  for (const location2 of locations) {
    let block = void 0;
    try {
      block = dimension.getBlock(location2);
    } catch {
    }
    if (!block?.isAir && !block?.typeId.includes("light_block"))
      return true;
  }
  return false;
}
world25.afterEvents.worldLoad.subscribe(() => {
  if (world25.getDynamicProperty("hail.daily_hail_today") === void 0) {
    generateDailyHailVariables();
  }
});
system25.runInterval(() => {
  checkDailyHail();
  const currentTime = world25.getTimeOfDay();
  if (lastTimeOfDay > currentTime) {
    generateDailyHailVariables();
  }
  lastTimeOfDay = currentTime;
}, 40 + Math.floor(Math.random() * 10));
function generateDailyHailVariables() {
  const hailFrequency = world25.getDynamicProperty(`shapescape_bewe:settings.options.hail`) ?? 50;
  const dailyHailToday = Math.random() < hailFrequency / 100;
  const dailyHailTimeTick = Math.floor(Math.random() * 12e3 + (Math.random() > 0.5 ? 0 : Math.random() * 12e3));
  world25.setDynamicProperty("hail.daily_hail_today", dailyHailToday);
  world25.setDynamicProperty("hail.daily_hail_time", dailyHailTimeTick);
  if (DEBUG9) {
    world25.sendMessage(`${world25.getDynamicProperty("hail.daily_hail_today")}`);
    world25.sendMessage(`${world25.getDynamicProperty("hail.daily_hail_time")}`);
  }
}
function checkDailyHail() {
  if (!world25.getDynamicProperty("hail.daily_hail_today") || !world25.getDimension("minecraft:overworld"))
    return;
  const currentTime = world25.getTimeOfDay();
  const timeDifference = Math.abs(currentTime - world25.getDynamicProperty("hail.daily_hail_time"));
  if (timeDifference < 100) {
    world25.setDynamicProperty("hail.daily_hail_today", false);
    world25.setDynamicProperty("hail_duration", HAIL_DURATION);
  }
}
system25.afterEvents.scriptEventReceive.subscribe((event) => {
  const message = event.message;
  const messageID = event.id;
  const entity = event.sourceEntity;
  if (!entity?.isValid)
    return;
  if (entity && messageID === "shapescape_bewe:hail" && message === "dev_start") {
    world25.setDynamicProperty("hail_duration", HAIL_DURATION);
    world25.getDimension("minecraft:overworld").setWeather(WeatherType2.Clear, REFRESH_RATE9 * 2);
  }
});

// data/system_template_esbuild/subscripts/loot_block.ts
import { system as system26 } from "@minecraft/server";
system26.beforeEvents.startup.subscribe((event) => {
  event.blockComponentRegistry.registerCustomComponent("shapescape_bewe:loot_block", {
    onTick: (event2) => {
      const dimension = event2.block.dimension;
      const location = event2.block.center();
      try {
        dimension.spawnParticle(`shapescape_bewe:loot_block`, location);
      } catch {
      }
    }
  });
});

// data/system_template_esbuild/subscripts/menu.ts
import { system as system27, world as world27, GameMode as GameMode5 } from "@minecraft/server";
import { ActionFormData, ModalFormData } from "@minecraft/server-ui";
system27.afterEvents.scriptEventReceive.subscribe((event) => {
  if (event.sourceEntity?.typeId !== "minecraft:player")
    return;
  const player = event.sourceEntity;
  if (event.id === `shapescape_bewe:menu` && player.getGameMode() !== GameMode5.Creative) {
    player.sendMessage({
      translate: "shapescape_bewe.menu.settings.not_in_creative"
    });
    return;
  }
  if (event.id === `shapescape_bewe:menu` && player.getGameMode() === GameMode5.Creative) {
    menu(player);
  }
});
world27.afterEvents.itemUse.subscribe((event) => {
  const { itemStack, source } = event;
  const player = source;
  const item = itemStack;
  if (item.typeId === "shapescape_bewe:menu" && player.getGameMode() !== GameMode5.Creative) {
    player.sendMessage({
      translate: "shapescape_bewe.menu.settings.not_in_creative"
    });
    return;
  }
  if (item.typeId === "shapescape_bewe:menu" && player.getGameMode() === GameMode5.Creative) {
    menu(player);
  }
});
function cancel_effect(player) {
}
function confirm_effect(player) {
  player.playSound("note.bass", {
    location: player.location,
    volume: 0.6,
    pitch: 1.5
  });
  player.sendMessage({ translate: "shapescape_bewe.menu.settings.saved_message" });
}
var menu_buttons = [
  {
    name: "shapescape_bewe.menu.settings",
    icon: "textures/shapescape/bewe/ui/settings",
    function: (player) => {
      settingsSettings(player);
    }
  },
  {
    name: "shapescape_bewe.menu.states",
    icon: "textures/shapescape/bewe/ui/states",
    function: (player) => {
      settingsStates(player);
    }
  },
  {
    name: "shapescape_bewe.menu.weather",
    icon: "textures/shapescape/bewe/ui/weather",
    function: (player) => {
      settings_weather(player);
    }
  },
  {
    name: "shapescape_bewe.menu.temperature",
    icon: "textures/shapescape/bewe/ui/temperature",
    function: (player) => {
      settings_temperature(player);
    }
  },
  {
    name: "shapescape_bewe.menu.particles",
    icon: "textures/shapescape/bewe/ui/particles",
    function: (player) => {
      settings_particles(player);
    }
  },
  {
    name: "shapescape_bewe.menu.sounds",
    icon: "textures/shapescape/bewe/ui/sounds",
    function: (player) => {
      settings_sounds(player);
    }
  }
];
function menu(player) {
  const menu_ui = new ActionFormData().title({
    translate: "shapescape_bewe.menu.title"
  });
  for (let button of menu_buttons) {
    menu_ui.button({ translate: button["name"] }, button["icon"]);
  }
  menu_ui.show(player).then((r) => {
    if (r.selection !== void 0) {
      let button = menu_buttons[r.selection];
      button.function(player);
    }
  });
}
var weather_buttons = [
  "rain_ripples",
  "wind_driven_rain",
  "rainbow",
  "blizzard",
  "sandstorm",
  "enderstorm",
  "netherstorm",
  "wind_system",
  "fogs",
  "biome_fog",
  "morning_fog",
  "after_rain_fog",
  "night_fog"
];
function settings_weather(player) {
  let form = new ModalFormData().title({
    translate: "shapescape_bewe.menu.weather"
  });
  for (let setting of weather_buttons) {
    let property = world27.getDynamicProperty(
      `shapescape_bewe:settings.weather.${setting}`
    ) ?? true;
    form.toggle(
      { translate: `shapescape_bewe:settings.weather.${setting}` },
      { defaultValue: property }
    );
  }
  form.submitButton({ translate: "shapescape_bewe.menu.submit_button" });
  form.show(player).then((formData) => {
    if (formData.formValues === void 0) {
      menu(player);
      cancel_effect(player);
      return;
    }
    confirm_effect(player);
    weather_buttons.forEach((setting, index) => {
      if (setting === "fogs") {
        if (formData.formValues[index] === true)
          player.runCommand("/scriptevent shapescape_bewe:fogs.turn_on");
        if (formData.formValues[index] === false)
          player.runCommand("/scriptevent shapescape_bewe:fogs.turn_off");
      }
      world27.setDynamicProperty(
        `shapescape_bewe:settings.weather.${setting}`,
        formData.formValues[index]
      );
    });
  });
}
var temperature_buttons = [
  "heat_effects",
  "heat_damage",
  "freezing_effects",
  "freezing_damage"
];
function settings_temperature(player) {
  let form = new ModalFormData().title({
    rawtext: [
      { translate: "shapescape_bewe.menu.temperature" },
      { text: ` ` },
      { translate: "shapescape_bewe.menu.per_player" }
    ]
  });
  for (let setting of temperature_buttons) {
    let property = player.getDynamicProperty(
      `shapescape_bewe:settings.temperature.${setting}`
    ) ?? true;
    form.toggle(
      { translate: `shapescape_bewe:settings.temperature.${setting}` },
      { defaultValue: property }
    );
  }
  form.submitButton({
    translate: "shapescape_bewe.menu.submit_button_per_player"
  });
  form.show(player).then((formData) => {
    if (formData.formValues === void 0) {
      menu(player);
      cancel_effect(player);
      return;
    }
    confirm_effect(player);
    temperature_buttons.forEach((setting, index) => {
      player.setDynamicProperty(
        `shapescape_bewe:settings.temperature.${setting}`,
        formData.formValues[index]
      );
    });
  });
}
var particles_buttons = ["aurora", "tumbleweed"];
function settings_particles(player) {
  let form = new ModalFormData().title({
    translate: "shapescape_bewe.menu.particles"
  });
  for (let setting of particles_buttons) {
    let property = world27.getDynamicProperty(
      `shapescape_bewe:settings.particles.${setting}`
    ) ?? true;
    form.toggle(
      { translate: `shapescape_bewe:settings.particles.${setting}` },
      { defaultValue: property }
    );
  }
  form.submitButton({ translate: "shapescape_bewe.menu.submit_button" });
  form.show(player).then((formData) => {
    if (formData.formValues === void 0) {
      menu(player);
      cancel_effect(player);
      return;
    }
    confirm_effect(player);
    particles_buttons.forEach((setting, index) => {
      if (setting === "tumbleweed") {
        if (formData.formValues[index] === false)
          player.runCommand(
            "/event entity @e[type=shapescape_bewe:tumbleweed] despawn"
          );
      }
      world27.setDynamicProperty(
        `shapescape_bewe:settings.particles.${setting}`,
        formData.formValues[index]
      );
    });
  });
}
var sounds_buttons = [
  "forest_day",
  "forest_night",
  "plains_night",
  "swamp_day",
  "swamp_night",
  "jungle_day",
  "jungle_night",
  "river",
  "beach",
  "ocean",
  "wind"
];
function settings_sounds(player) {
  let form = new ModalFormData().title({
    rawtext: [
      { translate: "shapescape_bewe.menu.sounds" },
      { text: ` ` },
      { translate: "shapescape_bewe.menu.per_player" }
    ]
  });
  for (let setting of sounds_buttons) {
    let property = player.getDynamicProperty(
      `shapescape_bewe:settings.sounds.${setting}`
    ) ?? true;
    form.toggle(
      { translate: `shapescape_bewe:settings.sounds.${setting}` },
      { defaultValue: property }
    );
  }
  form.submitButton({
    translate: "shapescape_bewe.menu.submit_button_per_player"
  });
  form.show(player).then((formData) => {
    if (formData.formValues === void 0) {
      menu(player);
      cancel_effect(player);
      return;
    }
    confirm_effect(player);
    sounds_buttons.forEach((setting, index) => {
      player.setDynamicProperty(
        `shapescape_bewe:settings.sounds.${setting}`,
        formData.formValues[index]
      );
    });
  });
}
var states = [
  "altitude_sickness",
  "broken_leg",
  "cracking_ice",
  "muddy_state",
  "sea_sick",
  "wet_state"
];
function settingsStates(player) {
  let form = new ModalFormData().title({
    rawtext: [
      { translate: "shapescape_bewe.menu.states" },
      { text: ` ` },
      { translate: "shapescape_bewe.menu.per_player" }
    ]
  });
  for (let setting of states) {
    let property = player.getDynamicProperty(
      `shapescape_bewe:settings.states.${setting}`
    ) ?? true;
    form.toggle(
      { translate: `shapescape_bewe:settings.states.${setting}` },
      { defaultValue: property }
    );
  }
  form.submitButton({
    translate: "shapescape_bewe.menu.submit_button_per_player"
  });
  form.show(player).then((formData) => {
    if (formData.formValues === void 0) {
      menu(player);
      cancel_effect(player);
      return;
    }
    confirm_effect(player);
    states.forEach((setting, index) => {
      player.setDynamicProperty(
        `shapescape_bewe:settings.states.${setting}`,
        formData.formValues[index]
      );
    });
  });
}
var settingsButtonsToggle = [
  { identifier: "thermometer_sneak", tooltip: ``, defaultValue: false },
  { identifier: "actionbar", tooltip: ``, defaultValue: true },
  {
    identifier: "chat_warnings",
    tooltip: `shapescape_bewe:settings.options.chat_warnings.tooltip`,
    defaultValue: true
  }
];
var unitsDropdown = [
  "shapescape_bewe:settings.options.degree_unit_fahrenheit",
  "shapescape_bewe:settings.options.degree_unit_celsius"
];
var difficulty = [
  "shapescape_bewe:settings.options.difficulty.easy",
  "shapescape_bewe:settings.options.difficulty.normal",
  "shapescape_bewe:settings.options.difficulty.hard"
];
function settingsSettings(player) {
  let form = new ModalFormData().title({
    rawtext: [{ translate: "shapescape_bewe.menu.settings" }]
  });
  for (let setting of settingsButtonsToggle) {
    let property = player.getDynamicProperty(
      `shapescape_bewe:settings.options.${setting.identifier}`
    ) ?? setting.defaultValue;
    form.toggle(
      { translate: `shapescape_bewe:settings.options.${setting.identifier}` },
      { defaultValue: property, tooltip: setting.tooltip }
    );
  }
  const stormsFrequency = world27.getDynamicProperty(
    `shapescape_bewe:settings.options.storms`
  ) ?? 50;
  const hailFrequency = world27.getDynamicProperty(`shapescape_bewe:settings.options.hail`) ?? 50;
  form.divider();
  form.dropdown(
    { translate: "shapescape_bewe:settings.options.degree_unit" },
    unitsDropdown,
    {
      defaultValueIndex: player.getDynamicProperty(
        `shapescape_bewe:settings.options.degree_unit`
      ) ?? 0
    }
  );
  form.divider();
  form.dropdown(
    { translate: "shapescape_bewe:settings.options.difficulty" },
    difficulty,
    {
      defaultValueIndex: player.getDynamicProperty(
        `shapescape_bewe:settings.options.difficulty`
      ) ?? 0
    }
  );
  form.divider();
  form.slider({ translate: "shapescape_bewe:settings.options.storms" }, 0, 100, {
    defaultValue: stormsFrequency,
    valueStep: 10
  });
  form.divider();
  form.slider({ translate: "shapescape_bewe:settings.options.hail" }, 0, 100, {
    defaultValue: hailFrequency,
    valueStep: 10
  });
  form.divider();
  form.submitButton({
    translate: "shapescape_bewe.menu.submit_button_per_player"
  });
  form.show(player).then((formData) => {
    if (formData.formValues === void 0) {
      menu(player);
      cancel_effect(player);
      return;
    }
    confirm_effect(player);
    settingsButtonsToggle.forEach((setting, index) => {
      player.setDynamicProperty(
        `shapescape_bewe:settings.options.${setting.identifier}`,
        formData.formValues[index]
      );
    });
    player.setDynamicProperty(
      `shapescape_bewe:settings.options.degree_unit`,
      formData.formValues[settingsButtonsToggle.length + 1]
      // It should be + 0, but apparently dividers are counted in the formValues as well, why....
    );
    player.setDynamicProperty(
      `shapescape_bewe:settings.options.difficulty`,
      formData.formValues[settingsButtonsToggle.length + 3]
      // It should be + 1, but apparently dividers are counted in the formValues as well, why....
    );
    world27.setDynamicProperty(
      `shapescape_bewe:settings.options.storms`,
      formData.formValues[settingsButtonsToggle.length + 5]
      // It should be + 2, but apparently dividers are counted in the formValues as well, why....
    );
    world27.setDynamicProperty(
      `shapescape_bewe:settings.options.hail`,
      formData.formValues[settingsButtonsToggle.length + 7]
      // It should be + 3, but apparently dividers are counted in the formValues as well, why....
    );
    if (stormsFrequency !== formData.formValues[settingsButtonsToggle.length + 5]) {
      world27.sendMessage({
        rawtext: [
          { translate: "shapescape_bewe.menu.settings.storms_message.1" },
          { text: ` ` },
          {
            text: `\xA7a${formData.formValues[settingsButtonsToggle.length + 5]}%%\xA7r`
          },
          { text: ` ` },
          { translate: "shapescape_bewe.menu.settings.storms_message.2" },
          { text: ` ` },
          { text: `\xA7a${player.name}` }
        ]
      });
    }
    if (hailFrequency !== formData.formValues[settingsButtonsToggle.length + 7]) {
      world27.sendMessage({
        rawtext: [
          { translate: "shapescape_bewe.menu.settings.hail_message.1" },
          { text: ` ` },
          {
            text: `\xA7a${formData.formValues[settingsButtonsToggle.length + 7]}%%\xA7r`
          },
          { text: ` ` },
          { translate: "shapescape_bewe.menu.settings.hail_message.2" },
          { text: ` ` },
          { text: `\xA7a${player.name}` }
        ]
      });
    }
  });
}

// data/system_template_esbuild/subscripts/muddy_state.ts
import {
  BlockVolume as BlockVolume4,
  Direction as Direction3,
  MolangVariableMap as MolangVariableMap12,
  Player as Player11,
  system as system28,
  TicksPerSecond as TicksPerSecond6,
  WeatherType as WeatherType3,
  world as world28
} from "@minecraft/server";
var DEBUG10 = false;
var DATA3 = { "getting_muddy": { "on_mud": 5, "in_quicksand": 5 }, "getting_clean": { "in_rain": 5, "in_snowfall": 10, "in_water": 2, "in_lava": 2 }, "effects_threshold": 0.5 };
var THRESHOLD = DATA3.effects_threshold;
var MAX_STATE = 1;
var INTERVAL3 = 0.5 * TicksPerSecond6;
var TAG2 = "shapescape_bewe_MUDDY_STATE";
system28.runInterval(() => {
  const players = world28.getAllPlayers();
  for (const player of players) {
    if (system28.currentTick % INTERVAL3 === 0)
      checkMuddyState(player);
    if (system28.currentTick % 5 === 0) {
      const isMoving = player.getVelocity().x !== 0 || player.getVelocity().y !== 0 || player.getVelocity().z !== 0;
      const currentMuddyState = player.getDynamicProperty("muddy_state") ?? 0;
      if (player.isOnGround && isMoving && currentMuddyState > THRESHOLD * MAX_STATE) {
        if (!player.hasTag(TAG2)) {
          player.sendMessage({ translate: `shapescape_bewe.muddy_state.tip` });
          player.playSound(`note.bass`, { location: player.location });
          player.addTag(TAG2);
        }
        particlesStep(player);
      }
    }
  }
}, 1);
world28.afterEvents.playerSpawn.subscribe((event) => {
  if (event.initialSpawn === false) {
    updateMuddyState(event.player, 0, true);
  }
});
function checkMuddyState(player) {
  const setting = player.getDynamicProperty(`shapescape_bewe:settings.states.muddy_state`) ?? true;
  if (!setting) {
    updateMuddyState(player, 0, true);
    return;
  }
  const biomeTemperature = player.getDynamicProperty("shapescape_bewe:environment_detection.biome_temperature") ?? 0.5 /* TEMPERATE */;
  const currentWeather = world28.getDynamicProperty("shapescape_bewe:environment_detection.weather") ?? "clear";
  let block = void 0;
  let blockBelow = void 0;
  try {
    block = player.dimension.getBlock(player.location);
    blockBelow = player.dimension.getBlock({ x: player.location.x, y: player.location.y - 1, z: player.location.z });
  } catch {
  }
  const isMoving = player.getVelocity().x !== 0 || player.getVelocity().y !== 0 || player.getVelocity().z !== 0;
  if (!block || !blockBelow)
    return;
  const currentMuddyState = player.getDynamicProperty("muddy_state") ?? 0;
  if (currentMuddyState >= THRESHOLD * MAX_STATE) {
    player.addEffect(`minecraft:mining_fatigue`, INTERVAL3 + 10, {
      amplifier: 0,
      showParticles: false
    });
  }
  if ((block.typeId.includes("minecraft:") && block.typeId.includes("mud") || blockBelow.typeId.includes("minecraft:") && blockBelow.typeId.includes("mud")) && isMoving) {
    updateMuddyState(player, DATA3.getting_muddy.on_mud, false);
    return;
  }
  if (block && block.typeId === "shapescape_bewe:quicksand") {
    updateMuddyState(player, DATA3.getting_muddy.in_quicksand, false);
    return;
  }
  if (block && block.typeId.includes("minecraft:") && block.typeId.includes("lava") && isMoving) {
    updateMuddyState(player, DATA3.getting_clean.in_lava, true);
    return;
  }
  if (player.isInWater && isMoving) {
    updateMuddyState(player, DATA3.getting_clean.in_water, true);
    return;
  }
  if (currentWeather.toUpperCase() === WeatherType3.Rain.toUpperCase() && biomeTemperature > 0.15 /* COLD */ && !hasRoof2(player.location, player.dimension)) {
    updateMuddyState(player, DATA3.getting_clean.in_rain, true);
  }
  if (currentWeather.toUpperCase() === WeatherType3.Rain.toUpperCase() && biomeTemperature <= 0.15 /* COLD */ && !hasRoof2(player.location, player.dimension)) {
    updateMuddyState(player, DATA3.getting_clean.in_snowfall, true);
  }
}
function updateMuddyState(player, time, cleaning = false) {
  const currentMuddyState = player.getDynamicProperty("muddy_state") ?? 0;
  const step = MAX_STATE / (time === 0 ? 1 * (INTERVAL3 / TicksPerSecond6) : time) * (INTERVAL3 / TicksPerSecond6) * (cleaning ? -1 : 1);
  let newMuddyState = Number((currentMuddyState + step).toPrecision(5));
  if (newMuddyState >= MAX_STATE) {
    newMuddyState = MAX_STATE;
  } else if (newMuddyState <= 0) {
    newMuddyState = 0;
  }
  if (DEBUG10) {
    world28.sendMessage(`muddy state: ` + JSON.stringify(newMuddyState));
  }
  player.setDynamicProperty("muddy_state", newMuddyState);
}
function particlesStep(player) {
  const locator = player.location;
  const velocity = player.getVelocity();
  const particleLocation = {
    x: locator.x + velocity.x * 5,
    y: locator.y,
    z: locator.z + velocity.z * 5
  };
  let speed = Math.sqrt(velocity.x ** 2 + velocity.y ** 2 + velocity.z ** 2);
  const molang = new MolangVariableMap12();
  molang.setFloat("variable.size_from_velocity", 1 + speed * 4);
  try {
    player.dimension.spawnParticle("shapescape_bewe:muddy_footstep", particleLocation, molang);
    if (Math.random() < 0.75) {
      player.playSound(`block.mud.step`, {
        location: particleLocation,
        volume: 0.25,
        pitch: 0.9 + Math.random() * 0.2
      });
    }
  } catch {
  }
}
function particlesHit(player, block, blockFace, entity) {
  const currentMuddyState = player.getDynamicProperty("muddy_state") ?? 0;
  if (currentMuddyState < THRESHOLD * MAX_STATE)
    return;
  if (block && blockFace) {
    const OFFSETS2 = /* @__PURE__ */ new Map([
      [Direction3.Up, { x: 0, y: 0.5, z: 0 }],
      [Direction3.Down, { x: 0, y: -0.5, z: 0 }],
      [Direction3.North, { x: 0, y: 0, z: -0.5 }],
      [Direction3.South, { x: 0, y: 0, z: 0.5 }],
      [Direction3.West, { x: -0.5, y: 0, z: 0 }],
      [Direction3.East, { x: 0.5, y: 0, z: 0 }]
    ]);
    const location = {
      x: block.center().x + OFFSETS2.get(blockFace).x,
      y: block.center().y + OFFSETS2.get(blockFace).y,
      z: block.center().z + OFFSETS2.get(blockFace).z
    };
    player.playSound(`block.mud.place`, {
      location
    });
    player.dimension.spawnParticle("shapescape_bewe:muddy_hit", location);
  }
  try {
    if (entity) {
      const location = {
        x: entity.location.x,
        y: entity.location.y + (entity.getHeadLocation().y - entity.location.y) / 2,
        z: entity.location.z
      };
      player.playSound(`block.mud.place`, {
        location
      });
      player.dimension.spawnParticle("shapescape_bewe:muddy_hit", location);
    }
  } catch {
  }
}
function hasRoof2(location, dimension) {
  if (location.y < 40)
    return true;
  const P1 = {
    x: location.x,
    y: location.y + 1,
    z: location.z
  };
  const P2 = {
    x: location.x,
    y: location.y + 20,
    z: location.z
  };
  const volume = new BlockVolume4(P1, P2);
  const locations = volume.getBlockLocationIterator();
  for (const location2 of locations) {
    let block = void 0;
    try {
      block = dimension.getBlock(location2);
    } catch {
    }
    if (!block?.isAir && !block?.typeId.includes("light_block"))
      return true;
  }
  return false;
}
world28.afterEvents.entityHitBlock.subscribe((event) => {
  const { hitBlock, damagingEntity, blockFace } = event;
  if (!(damagingEntity instanceof Player11))
    return;
  const player = damagingEntity;
  particlesHit(player, hitBlock, blockFace);
});
world28.afterEvents.playerInteractWithBlock.subscribe((event) => {
  const { block, player, blockFace } = event;
  particlesHit(player, block, blockFace);
});
world28.afterEvents.entityHitEntity.subscribe((event) => {
  const { damagingEntity, hitEntity } = event;
  if (!(damagingEntity instanceof Player11))
    return;
  const player = damagingEntity;
  particlesHit(player, void 0, void 0, hitEntity);
});
world28.afterEvents.playerInteractWithEntity.subscribe((event) => {
  const { player, target } = event;
  if (!(player instanceof Player11))
    return;
  particlesHit(player, void 0, void 0, target);
});

// data/system_template_esbuild/subscripts/netherstorm.ts
import {
  system as system29,
  world as world29,
  MolangVariableMap as MolangVariableMap13,
  BlockVolume as BlockVolume5,
  EntityComponentTypes as EntityComponentTypes8,
  EntityDamageCause as EntityDamageCause8,
  TicksPerSecond as TicksPerSecond7,
  GameMode as GameMode6
} from "@minecraft/server";
var DEBUG11 = false;
var REFRESH_RATE10 = 2 * TicksPerSecond7;
var THUNDER_CHANCE2 = 0.35;
var DURATION_LIMIT2 = 50 * TicksPerSecond7;
var COOLDOWN2 = (Math.random() + Math.random() + 5) * 60 * TicksPerSecond7;
var SOUND_COOLDOWN3 = 14 * TicksPerSecond7;
var LOUD_SOUND_TAG2 = `shapescape_bewe_netherSTORM_SOUND_LOUD`;
var QUIET_SOUND_TAG2 = `shapescape_bewe_netherSTORM_SOUND_QUIET`;
world29.afterEvents.playerSpawn.subscribe((event) => {
  clearTags2(event.player);
});
function clearTags2(player) {
  player.removeTag(LOUD_SOUND_TAG2);
  player.removeTag(QUIET_SOUND_TAG2);
}
system29.runInterval(() => {
  if ((world29.getDynamicProperty("shapescape_bewe:settings.weather.netherstorm") ?? true) === false) {
    world29.setDynamicProperty("netherstorm_duration", DURATION_LIMIT2);
    world29.setDynamicProperty("netherstorm_cooldown", 0);
  }
  let duration = world29.getDynamicProperty("netherstorm_duration") ?? 0;
  let cooldown = world29.getDynamicProperty("netherstorm_cooldown") ?? 0;
  duration++;
  cooldown++;
  if (DEBUG11 && system29.currentTick % 20 === 0) {
    world29.sendMessage(JSON.stringify(duration));
    world29.sendMessage(JSON.stringify(cooldown));
  }
  if (duration > DURATION_LIMIT2 && cooldown > COOLDOWN2) {
    world29.setDynamicProperty("netherstorm", true);
    duration = 0;
    cooldown = 0;
    const players2 = world29.getAllPlayers();
    for (const player of players2) {
      const allowedGamemode = player.getGameMode() !== GameMode6.Creative && player.getGameMode() !== GameMode6.Spectator;
      if (!allowedGamemode)
        continue;
      if (player.dimension.id !== "minecraft:nether")
        continue;
      const dimension = player.dimension;
      const location = player.location;
      const skeletonsInTotal = 5;
      const nearbyWitherSkeletons = dimension.getEntities({
        location,
        maxDistance: 20,
        type: "minecraft:wither_skeleton"
      });
      const skeletonP1 = {
        x: location.x - 10,
        y: location.y,
        z: location.z - 10
      };
      const skeletonP2 = {
        x: location.x + 10,
        y: location.y + 3,
        z: location.z + 10
      };
      const skeletonVolume = new BlockVolume5(skeletonP1, skeletonP2).getBlockLocationIterator();
      const skeletonVolumeAir = [];
      for (const location2 of skeletonVolume) {
        try {
          const block = dimension.getBlock(location2);
          if (block?.isAir || block?.typeId.includes("minecraft:light_block")) {
            skeletonVolumeAir.push(location2);
          }
        } catch {
        }
      }
      for (let index = 0; index < skeletonsInTotal - nearbyWitherSkeletons.length; index++) {
        const randomLocation = skeletonVolumeAir[Math.floor(Math.random() * skeletonVolumeAir.length)];
        dimension.spawnEntity("minecraft:wither_skeleton", randomLocation);
      }
    }
  }
  if (duration >= DURATION_LIMIT2) {
    world29.getDimension("minecraft:overworld").runCommand("/stopsound @a shapescape_bewe.netherstorm.netherstorm");
    world29.setDynamicProperty("netherstorm", false);
    const tornadoes = world29.getDimension("minecraft:nether").getEntities({
      type: "shapescape_bewe:nether_tornado"
    });
    for (const tornado of tornadoes) {
      if (tornado.isValid) {
        tornado.triggerEvent("shapescape_bewe:start_despawn");
      }
    }
    const players2 = world29.getAllPlayers();
    for (const player of players2) {
      player.runCommand(`/fog @s remove weather`);
      for (const tag of player.getTags()) {
        if (tag.includes("shapescape_bewe_nether_tornado_")) {
          const nether_tornadoID = tag.replace("shapescape_bewe_nether_tornado_", "");
          const nether_tornado = world29.getEntity(nether_tornadoID);
          player.removeTag(tag);
          nether_tornado?.remove();
        }
      }
    }
  }
  world29.setDynamicProperty("netherstorm_duration", duration);
  world29.setDynamicProperty("netherstorm_cooldown", cooldown);
  if (duration > DURATION_LIMIT2 && cooldown < COOLDOWN2)
    return;
  if (DEBUG11) {
    world29.sendMessage("netherSTORM");
  }
  sounds2();
  if (system29.currentTick % REFRESH_RATE10 !== 0)
    return;
  let players = world29.getPlayers();
  let alreadyProcessed = /* @__PURE__ */ new Set();
  for (let player of players) {
    if (player.dimension.id !== "minecraft:nether")
      continue;
    const dimension = player.dimension;
    const location = player.location;
    let spawnNetherTornado = true;
    for (const tag of player.getTags()) {
      if (!tag.includes(`shapescape_bewe_nether_tornado_`))
        continue;
      spawnNetherTornado = false;
    }
    if (spawnNetherTornado) {
      const nether_tornado = dimension.spawnEntity("shapescape_bewe:nether_tornado", player.location);
      player.setPropertyOverrideForEntity(nether_tornado, "shapescape_bewe:visible", true);
      player.addTag(`shapescape_bewe_nether_tornado_${nether_tornado.id}`);
    }
    player.runCommand(`/fog @s push shapescape_bewe:nether_stormy weather`);
    try {
      player.spawnParticle(`shapescape_bewe:netherstorm_cloud`, player.location);
      player.spawnParticle(`shapescape_bewe:netherstorm_dots`, player.location);
    } catch {
    }
    if (alreadyProcessed.has(player))
      continue;
    const nearbyPlayers = dimension.getEntities({
      location,
      maxDistance: 32,
      type: "minecraft:player"
    });
    for (let otherPlayer of nearbyPlayers) {
      if (otherPlayer.nameTag !== player.nameTag) {
        alreadyProcessed.add(otherPlayer);
      }
    }
    const nearbyWitherSkeletons = dimension.getEntities({
      location,
      maxDistance: 32,
      type: "minecraft:wither_skeleton"
    });
    for (const skeleton of nearbyWitherSkeletons) {
      if (skeleton.isValid) {
        skeleton.addEffect("minecraft:speed", REFRESH_RATE10, {
          amplifier: 0,
          showParticles: false
        });
      }
    }
    if (Math.random() > THUNDER_CHANCE2) {
      if (Math.random() < 0.5) {
        const pitch = Math.random() * 0.2 + 0.9;
        dimension.playSound(`shapescape_bewe.thunderstorm.thunder_distant`, location, {
          volume: 5,
          pitch
        });
      } else {
        const pitch = Math.random() * 0.2 + 0.9;
        dimension.playSound(`shapescape_bewe.thunderstorm.thunder_nearby`, player.location, {
          volume: 3,
          pitch
        });
      }
    }
  }
}, 1);
function sounds2() {
  const players = world29.getPlayers();
  for (const player of players) {
    if (player.dimension.id !== "minecraft:nether")
      continue;
    let in_shelter = false;
    let ray_location = { x: 0, y: 0, z: 0 };
    let block = void 0;
    try {
      ray_location = {
        x: player.location.x,
        y: player.location.y + 1.5,
        z: player.location.z
      };
      block = player.dimension.getBlockFromRay(
        ray_location,
        { x: 0, y: 1, z: 0 },
        { maxDistance: 16, includePassableBlocks: false }
      );
      if (player.dimension.getBlock(ray_location)?.isLiquid)
        in_shelter = true;
    } catch {
      continue;
    }
    if (block !== void 0)
      in_shelter = true;
    if (player.hasTag(LOUD_SOUND_TAG2)) {
      if (in_shelter === true) {
        player.removeTag(LOUD_SOUND_TAG2);
        player.runCommand("/stopsound @s shapescape_bewe.netherstorm.netherstorm");
      }
    }
    if (player.hasTag(QUIET_SOUND_TAG2)) {
      if (in_shelter === false) {
        player.removeTag(QUIET_SOUND_TAG2);
        player.runCommand("/stopsound @s shapescape_bewe.netherstorm.netherstorm");
      }
    }
    if (player.hasTag(LOUD_SOUND_TAG2) || player.hasTag(QUIET_SOUND_TAG2))
      continue;
    if (!in_shelter) {
      player.addTag(LOUD_SOUND_TAG2);
      player.playSound("shapescape_bewe.netherstorm.netherstorm", { volume: 0.6 });
    } else {
      player.addTag(QUIET_SOUND_TAG2);
      player.playSound("shapescape_bewe.netherstorm.netherstorm", { volume: 0.2 });
    }
    system29.runTimeout(() => {
      if (!player)
        return;
      player.removeTag(LOUD_SOUND_TAG2);
      player.removeTag(QUIET_SOUND_TAG2);
    }, SOUND_COOLDOWN3);
  }
}
system29.afterEvents.scriptEventReceive.subscribe((event) => {
  const message = event.message;
  const messageID = event.id;
  const entity = event.sourceEntity;
  if (!entity?.isValid)
    return;
  if (entity && messageID === "shapescape_bewe:nether_tornado" && message === "teleport") {
    const player = entity.dimension.getEntities({
      tags: [`shapescape_bewe_nether_tornado_${entity.id}`]
    })[0];
    if (player && player.isValid) {
      entity.teleport(player.location);
      let duration = world29.getDynamicProperty("netherstorm_duration") ?? 0;
      if (duration > DURATION_LIMIT2)
        entity.triggerEvent(`shapescape_bewe:start_despawn`);
    } else {
      const isChested = entity.getComponent(EntityComponentTypes8.IsChested);
      if (!isChested)
        entity.triggerEvent(`shapescape_bewe:start_despawn`);
    }
  }
  if (entity && messageID === "shapescape_bewe:nether_tornado" && message === "despawn") {
    const players = entity.dimension.getEntities({
      tags: [`shapescape_bewe_nether_tornado_${entity.id}`]
    });
    for (const player of players) {
      player.removeTag(`shapescape_bewe_nether_tornado_${entity.id}`);
    }
  }
});
world29.afterEvents.playerSpawn.subscribe((event) => {
  const player = event.player;
  for (const tag of player.getTags()) {
    if (tag.includes("shapescape_bewe_nether_tornado_")) {
      const nether_tornadoID = tag.replace("shapescape_bewe_nether_tornado_", "");
      const nether_tornado = world29.getEntity(nether_tornadoID);
      player.removeTag(tag);
      nether_tornado?.remove();
    }
  }
});
system29.afterEvents.scriptEventReceive.subscribe((event) => {
  const message = event.message;
  const messageID = event.id;
  const entity = event.sourceEntity;
  if (!entity?.isValid)
    return;
  if (entity && messageID === "shapescape_bewe:netherstorm" && message === "dev_start") {
    world29.setDynamicProperty("netherstorm_duration", DURATION_LIMIT2);
    world29.setDynamicProperty("netherstorm_cooldown", COOLDOWN2);
  }
});

// data/system_template_esbuild/subscripts/freezing_protection_potion.ts
import {
  system as system30,
  world as world30,
  Player as Player13,
  ItemStack as ItemStack2
} from "@minecraft/server";
var activeTimers = /* @__PURE__ */ new Map();
world30.afterEvents.itemCompleteUse.subscribe((event) => {
  const player = event.source;
  const itemStack = event.itemStack;
  if (!(player instanceof Player13) || !itemStack)
    return;
  if (itemStack.typeId !== "shapescape_bewe:freezing_protection_potion")
    return;
  applyPotionEffect(player, "f_i");
  system30.run(() => {
    player.runCommand(`clear @s shapescape_bewe:freezing_protection_potion 0 1`);
    player.dimension.spawnItem(new ItemStack2("minecraft:glass_bottle", 1), player.location);
  });
});
world30.beforeEvents.itemUse.subscribe((event) => {
  const player = event.source;
  const itemStack = event.itemStack;
  if (!(player instanceof Player13) || !itemStack)
    return;
  if (itemStack.typeId !== "shapescape_bewe:freezing_protection_splash_potion")
    return;
  system30.run(() => {
    player.runCommand(`clear @s shapescape_bewe:freezing_protection_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_bewe:freezing_protection_splash_potion", location);
  projectile.applyImpulse(viewDirection.add({ x: 0, y: 0.4, z: 0 }).multiply({ x: 0.6, y: 0.6, z: 0.6 }));
  player.dimension.playSound(`mob.witch.throw`, player.location);
}
world30.afterEvents.projectileHitEntity.subscribe((event) => {
  const projectile = event.projectile;
  if (projectile.typeId !== "shapescape_bewe:freezing_protection_splash_potion")
    return;
  projectileHit(projectile);
});
world30.afterEvents.projectileHitBlock.subscribe((event) => {
  const projectile = event.projectile;
  if (projectile.typeId !== "shapescape_bewe:freezing_protection_splash_potion")
    return;
  projectileHit(projectile);
});
function projectileHit(projectile) {
  projectile.dimension.playSound(`random.glass`, projectile.location);
  const location = projectile.location;
  const dimension = projectile.dimension;
  projectile.remove();
  const affectedEntities = dimension.getEntities({
    location,
    maxDistance: 4
  });
  try {
    dimension.spawnParticle("shapescape_bewe:freezing_protection_splash_potion", location);
  } catch {
  }
  for (const entity of affectedEntities) {
    if (entity instanceof Player13) {
      applyPotionEffect(entity, "f_i");
    }
  }
}
world30.afterEvents.playerJoin.subscribe((event) => {
  const timerKey = `${event.playerId}_f_i`;
  if (!activeTimers.has(timerKey)) {
    const player = world30.getAllPlayers().find((p) => p.id === event.playerId);
    if (player) {
      player.setDynamicProperty("f_i", false);
    }
  }
});
function applyPotionEffect(player, propertyName) {
  const timerKey = `${player.id}_${propertyName}`;
  const particleKey = `${timerKey}_particles`;
  const existingTimer = activeTimers.get(timerKey);
  const existingParticleTimer = activeTimers.get(particleKey);
  if (existingTimer !== void 0) {
    player.setDynamicProperty(propertyName, false);
    system30.clearRun(existingTimer);
  }
  if (existingParticleTimer !== void 0) {
    system30.clearRun(existingParticleTimer);
  }
  player.setDynamicProperty(propertyName, true);
  const particleTimer = system30.runInterval(() => {
    if (player.getDynamicProperty(propertyName)) {
      playParticle(player, "shapescape_bewe:freezing_protection_effect");
    }
  }, 3);
  const newTimer = system30.runTimeout(() => {
    player.setDynamicProperty(propertyName, false);
    system30.clearRun(particleTimer);
    activeTimers.delete(timerKey);
    activeTimers.delete(particleKey);
  }, 3600);
  activeTimers.set(timerKey, newTimer);
  activeTimers.set(particleKey, particleTimer);
}
function playParticle(player, particleEffect) {
  const locator = player.location;
  const direction = player.getViewDirection();
  const velocity = player.getVelocity();
  const particleLocation = {
    x: locator.x + direction.x * 0.1 + velocity.x * 8,
    y: locator.y + 0.1 + direction.y * 0.1 + velocity.y * 2,
    z: locator.z + direction.z * 0.1 + velocity.z * 8
  };
  try {
    player.dimension.spawnParticle(particleEffect, particleLocation);
  } catch {
  }
}

// data/system_template_esbuild/subscripts/overheating_protection_potion.ts
import {
  system as system31,
  world as world31,
  Player as Player14,
  ItemStack as ItemStack3
} from "@minecraft/server";
var activeTimers2 = /* @__PURE__ */ new Map();
world31.afterEvents.itemCompleteUse.subscribe((event) => {
  const player = event.source;
  const itemStack = event.itemStack;
  if (!(player instanceof Player14) || !itemStack)
    return;
  if (itemStack.typeId !== "shapescape_bewe:overheating_protection_potion")
    return;
  applyPotionEffect2(player, "o_i");
  system31.run(() => {
    player.runCommand(`clear @s shapescape_bewe:overheating_protection_potion 0 1`);
    player.dimension.spawnItem(new ItemStack3("minecraft:glass_bottle", 1), player.location);
  });
});
world31.beforeEvents.itemUse.subscribe((event) => {
  const player = event.source;
  const itemStack = event.itemStack;
  if (!(player instanceof Player14) || !itemStack)
    return;
  if (itemStack.typeId !== "shapescape_bewe:overheating_protection_splash_potion")
    return;
  system31.run(() => {
    player.runCommand(`clear @s shapescape_bewe:overheating_protection_splash_potion 0 1`);
    shoot2(player);
  });
});
function shoot2(player) {
  const viewDirection = Vec3.from(player.getViewDirection());
  const location = viewDirection.multiply(1.25).add(player.getHeadLocation());
  const projectile = player.dimension.spawnEntity("shapescape_bewe:overheating_protection_splash_potion", location);
  projectile.applyImpulse(viewDirection.add({ x: 0, y: 0.4, z: 0 }).multiply({ x: 0.6, y: 0.6, z: 0.6 }));
  player.dimension.playSound(`mob.witch.throw`, player.location);
}
world31.afterEvents.projectileHitEntity.subscribe((event) => {
  const projectile = event.projectile;
  if (projectile.typeId !== "shapescape_bewe:overheating_protection_splash_potion")
    return;
  projectileHit2(projectile);
});
world31.afterEvents.projectileHitBlock.subscribe((event) => {
  const projectile = event.projectile;
  if (projectile.typeId !== "shapescape_bewe:overheating_protection_splash_potion")
    return;
  projectileHit2(projectile);
});
function projectileHit2(projectile) {
  projectile.dimension.playSound(`random.glass`, projectile.location);
  const location = projectile.location;
  const dimension = projectile.dimension;
  projectile.remove();
  const affectedEntities = dimension.getEntities({
    location,
    maxDistance: 4
  });
  try {
    dimension.spawnParticle("shapescape_bewe:overheating_protection_splash_potion", location);
  } catch {
  }
  for (const entity of affectedEntities) {
    if (entity instanceof Player14) {
      applyPotionEffect2(entity, "o_i");
    }
  }
}
world31.afterEvents.playerJoin.subscribe((event) => {
  const timerKey = `${event.playerId}_o_i`;
  if (!activeTimers2.has(timerKey)) {
    const player = world31.getAllPlayers().find((p) => p.id === event.playerId);
    if (player) {
      player.setDynamicProperty("shapescape_bewe:overheating_immune", false);
    }
  }
});
function applyPotionEffect2(player, propertyName) {
  const timerKey = `${player.id}_${propertyName}`;
  const particleKey = `${timerKey}_particles`;
  const existingTimer = activeTimers2.get(timerKey);
  const existingParticleTimer = activeTimers2.get(particleKey);
  if (existingTimer !== void 0) {
    player.setDynamicProperty(propertyName, false);
    system31.clearRun(existingTimer);
  }
  if (existingParticleTimer !== void 0) {
    system31.clearRun(existingParticleTimer);
  }
  player.setDynamicProperty(propertyName, true);
  const particleTimer = system31.runInterval(() => {
    if (player.getDynamicProperty(propertyName)) {
      playParticle2(player, "shapescape_bewe:overheating_protection_effect");
    }
  }, 3);
  const newTimer = system31.runTimeout(() => {
    player.setDynamicProperty(propertyName, false);
    system31.clearRun(particleTimer);
    activeTimers2.delete(timerKey);
    activeTimers2.delete(particleKey);
  }, 3600);
  activeTimers2.set(timerKey, newTimer);
  activeTimers2.set(particleKey, particleTimer);
}
function playParticle2(player, particleEffect) {
  const locator = player.location;
  const direction = player.getViewDirection();
  const velocity = player.getVelocity();
  const particleLocation = {
    x: locator.x + direction.x * 0.1 + velocity.x * 8,
    y: locator.y + 0.1 + direction.y * 0.1 + velocity.y * 2,
    z: locator.z + direction.z * 0.1 + velocity.z * 8
  };
  try {
    player.dimension.spawnParticle(particleEffect, particleLocation);
  } catch {
  }
}

// data/system_template_esbuild/subscripts/quicksand.ts
import {
  system as system32,
  world as world32,
  EntityDamageCause as EntityDamageCause9
} from "@minecraft/server";
system32.runInterval(() => {
  const players = world32.getPlayers();
  for (const player of players) {
    let block;
    let blockAbove;
    try {
      block = player.dimension.getBlock(player.location);
      blockAbove = player.dimension.getBlock(player.location);
    } catch {
    }
    if (blockAbove && block && block.typeId.includes("shapescape_bewe:") && block.typeId.includes("quicksand")) {
      player.addEffect(`minecraft:slow_falling`, 10, {
        amplifier: 0,
        showParticles: false
      });
      const velocityThreshold = 0.05;
      const velocity = player.getVelocity();
      if (Math.abs(velocity.x) > velocityThreshold || Math.abs(velocity.y) > velocityThreshold || Math.abs(velocity.z) > velocityThreshold) {
        const yVelocity = velocity.y > 0 ? Math.min(Math.max(velocity.y, 0), 1) : Math.min(Math.max(velocity.y, -1), 0);
        player.applyKnockback(
          { x: -velocity.x * 1, z: -velocity.z * 1 },
          -yVelocity * 1
        );
      }
      const fullInQuicksand = (blockAbove.typeId === "shapescape_bewe:quicksand" || blockAbove.typeId === "shapescape_bewe:red_quicksand") && (block.typeId === "shapescape_bewe:quicksand" || block.typeId === "shapescape_bewe:red_quicksand");
      if (fullInQuicksand && system32.currentTick % 40 === 0) {
        player.applyDamage(1, {
          cause: EntityDamageCause9.drowning
        });
      }
    }
  }
}, 1);
var modifiedQuicksandBlocks = /* @__PURE__ */ new Map();
var playerCameraBlocks = /* @__PURE__ */ new Map();
function getBlockKey(location) {
  return `${Math.floor(location.x)},${Math.floor(location.y)},${Math.floor(
    location.z
  )}`;
}
function getCameraLocation(player) {
  const headLocation = player.getHeadLocation();
  return {
    x: Math.floor(headLocation.x),
    y: Math.floor(headLocation.y),
    z: Math.floor(headLocation.z)
  };
}
function isQuicksandBlock(block) {
  return block?.typeId === "shapescape_bewe:quicksand" || block?.typeId === "shapescape_bewe:red_quicksand";
}
function setQuicksandInvisible(block, player) {
  try {
    const currentState = block.permutation.getState(
      "shapescape_bewe:player_inside"
    );
    if (!currentState) {
      const newPermutation = block.permutation.withState(
        "shapescape_bewe:player_inside",
        true
      );
      player.dimension.setBlockPermutation(block.location, newPermutation);
      const blockKey = getBlockKey(block.location);
      modifiedQuicksandBlocks.set(blockKey, {
        location: block.location,
        dimension: player.dimension.id
      });
    }
  } catch (error) {
    console.warn("Failed to set quicksand invisible:", error);
  }
}
function setQuicksandVisible(blockLocation, dimension) {
  try {
    const block = dimension.getBlock(blockLocation);
    if (block && isQuicksandBlock(block)) {
      const newPermutation = block.permutation.withState(
        "shapescape_bewe:player_inside",
        false
      );
      dimension.setBlockPermutation(blockLocation, newPermutation);
    }
  } catch (error) {
    console.warn("Failed to restore quicksand visibility:", error);
  }
}
system32.runInterval(() => {
  for (const player of world32.getAllPlayers()) {
    const cameraLocation = getCameraLocation(player);
    const currentBlock = player.dimension.getBlock(cameraLocation);
    const currentBlockKey = getBlockKey(cameraLocation);
    const lastCameraBlockKey = playerCameraBlocks.get(player.id);
    if (lastCameraBlockKey !== currentBlockKey) {
      if (lastCameraBlockKey && modifiedQuicksandBlocks.has(lastCameraBlockKey)) {
        const lastBlockData = modifiedQuicksandBlocks.get(lastCameraBlockKey);
        setQuicksandVisible(lastBlockData.location, player.dimension);
        modifiedQuicksandBlocks.delete(lastCameraBlockKey);
      }
      playerCameraBlocks.set(player.id, currentBlockKey);
    }
    if (currentBlock && isQuicksandBlock(currentBlock)) {
      setQuicksandInvisible(currentBlock, player);
    }
  }
}, 1);
system32.runInterval(() => {
  const activePlayers = new Set(world32.getAllPlayers().map((p) => p.id));
  const activePlayerCameraBlocks = new Set(
    Array.from(playerCameraBlocks.entries()).filter(([playerId]) => activePlayers.has(playerId)).map(([, blockKey]) => blockKey)
  );
  for (const [blockKey, blockData] of modifiedQuicksandBlocks.entries()) {
    if (!activePlayerCameraBlocks.has(blockKey)) {
      try {
        const dimension = world32.getDimension(blockData.dimension);
        setQuicksandVisible(blockData.location, dimension);
        modifiedQuicksandBlocks.delete(blockKey);
      } catch (error) {
        modifiedQuicksandBlocks.delete(blockKey);
      }
    }
  }
  for (const playerId of playerCameraBlocks.keys()) {
    if (!activePlayers.has(playerId)) {
      playerCameraBlocks.delete(playerId);
    }
  }
}, 60);
world32.afterEvents.worldLoad.subscribe(() => {
  for (const [blockKey, blockData] of modifiedQuicksandBlocks.entries()) {
    try {
      const dimension = world32.getDimension(blockData.dimension);
      setQuicksandVisible(blockData.location, dimension);
    } catch (error) {
      console.warn("Failed to restore block during initialization:", error);
    }
  }
  modifiedQuicksandBlocks.clear();
  playerCameraBlocks.clear();
});

// data/system_template_esbuild/subscripts/sandstorm.ts
import {
  system as system33,
  world as world33,
  MolangVariableMap as MolangVariableMap16,
  BlockVolume as BlockVolume8,
  EntityDamageCause as EntityDamageCause10,
  GameMode as GameMode9
} from "@minecraft/server";
var REFRESH_RATE11 = 1 * 20;
system33.runInterval(() => {
  if (system33.currentTick % REFRESH_RATE11 !== 0)
    return;
  if ((world33.getDynamicProperty(
    "shapescape_bewe:settings.weather.sandstorm"
  ) ?? true) === false)
    return;
  let players = world33.getPlayers();
  let alreadyProcessed = /* @__PURE__ */ new Set();
  const WEATHER = world33.getDynamicProperty(
    "shapescape_bewe:environment_detection.weather"
  ) ?? "clear";
  const WIND_DIRECTION = world33.getDynamicProperty(
    "shapescape_bewe:wind_direction"
  ) ?? { x: 1, y: 0, z: 0 };
  if (WEATHER !== "thunderstorm")
    return;
  for (let player of players) {
    const dimension = player.dimension;
    const location = player.location;
    const biome = player.getDynamicProperty(
      "shapescape_bewe:environment_detection.biome"
    ) ?? "";
    const biomeTagsProperty = player.getDynamicProperty(
      "shapescape_bewe:environment_detection.biome_tags"
    ) ?? "[]";
    const biomeTags = JSON.parse(biomeTagsProperty);
    if (biome === "")
      continue;
    if (!biomeTags.includes("desert") && biome !== "desert" && !biomeTags.includes("mesa") && biome !== "mesa")
      continue;
    if (location.y < 40 || dimension.id !== "minecraft:overworld")
      continue;
    const allowedGamemode = player.getGameMode() !== GameMode9.Creative && player.getGameMode() !== GameMode9.Spectator;
    if (!allowedGamemode)
      continue;
    applyAgainstWindEffects(player, false, true);
    if (alreadyProcessed.has(player))
      continue;
    const nearbyPlayers = dimension.getEntities({
      location,
      maxDistance: 32,
      type: "minecraft:player"
    });
    for (let otherPlayer of nearbyPlayers) {
      if (otherPlayer.nameTag !== player.nameTag) {
        alreadyProcessed.add(otherPlayer);
      }
    }
    const windDrivenRain_molang = new MolangVariableMap16();
    windDrivenRain_molang.setVector3("wind_direction", WIND_DIRECTION);
    try {
      dimension.spawnParticle("shapescape_bewe:sandstorm_clouds", location);
      dimension.spawnParticle(
        "shapescape_bewe:sandstorm",
        location,
        windDrivenRain_molang
      );
    } catch {
    }
    if (system33.currentTick % 40 === 0) {
      const entitiesToLevitateMob = dimension.getEntities({
        location,
        maxDistance: 32,
        families: ["mob"]
      });
      const entitiesToLevitateMonster = dimension.getEntities({
        location,
        maxDistance: 32,
        families: ["monster"]
      });
      const entitesToLevitate = [
        ...entitiesToLevitateMob,
        ...entitiesToLevitateMonster
      ];
      for (const entity of entitesToLevitate) {
        if (Math.random() < 0.3)
          continue;
        entity.addEffect("minecraft:levitation", 25 + Math.random() * 10, {
          amplifier: 2,
          // Random level between 1 and 2
          showParticles: false
        });
        entity.removeEffect("minecraft:slow_falling");
        entity.addEffect("minecraft:slow_falling", 80, {
          amplifier: 0,
          // Random level between 0 and 2
          showParticles: false
        });
      }
    }
    if (system33.currentTick % 60 === 0) {
      const normRevertWindDir = Vec3.from(WIND_DIRECTION).multiply(-1).normalize();
      const P1 = {
        x: location.x + (Math.round(normRevertWindDir.x) === 0 ? 20 : Math.round(normRevertWindDir.x) * 30),
        y: location.y + 1,
        z: location.z + (Math.round(normRevertWindDir.z) === 0 ? 20 : Math.round(normRevertWindDir.z) * 30)
      };
      const P2 = {
        x: location.x - (Math.round(normRevertWindDir.x) === 0 ? 20 : -Math.round(normRevertWindDir.x) * 30),
        y: location.y,
        z: location.z - (Math.round(normRevertWindDir.z) === 0 ? 20 : -Math.round(normRevertWindDir.z) * 30)
      };
      const volume = new BlockVolume8(P1, P2);
      let index = 0;
      for (const location2 of volume.getBlockLocationIterator()) {
        if (Math.random() < 0.975)
          continue;
        let block;
        try {
          block = dimension.getBlock(location2);
        } catch {
        }
        if (block && block.isAir) {
          index++;
          system33.runTimeout(() => {
            try {
              dimension.spawnEntity("shapescape_bewe:tumbleweed", block.center());
            } catch {
            }
          }, index * 10);
        }
      }
    }
  }
}, 1);
var SOUND_COOLDOWN4 = 8 * 20;
var COOLDOWN_NORMAL2 = "shapescape_bewe_sandstorm_normal";
var COOLDOWN_SHELTER2 = "shapescape_bewe_sandstorm_shelter";
world33.afterEvents.playerSpawn.subscribe((event) => {
  clear_cooldowns3(event.player);
});
function clear_cooldowns3(player) {
  player.removeTag(COOLDOWN_NORMAL2);
  player.removeTag(COOLDOWN_SHELTER2);
}
system33.runInterval(() => {
  sandstorm_sound();
}, 1);
function sandstorm_sound() {
  if ((world33.getDynamicProperty(
    "shapescape_bewe:settings.weather.sandstorm"
  ) ?? true) === false)
    return;
  let players = world33.getPlayers();
  const WEATHER = world33.getDynamicProperty(
    "shapescape_bewe:environment_detection.weather"
  ) ?? "clear";
  if (WEATHER !== "thunderstorm")
    return;
  for (let player of players) {
    try {
      let in_shelter = false;
      let ray_location = {
        x: player.location.x,
        y: player.location.y + 1.5,
        z: player.location.z
      };
      let block = player.dimension.getBlockFromRay(
        ray_location,
        { x: 0, y: 1, z: 0 },
        { maxDistance: 16, includePassableBlocks: false }
      );
      if (player.dimension.getBlock(ray_location)?.isLiquid)
        in_shelter = true;
      if (block !== void 0)
        in_shelter = true;
      if (player.location.y < 55)
        in_shelter = true;
      if (player.hasTag(COOLDOWN_NORMAL2)) {
        if (in_shelter === true) {
          player.removeTag(COOLDOWN_NORMAL2);
          player.runCommand("/stopsound @s shapescape_bewe.sandstorm");
        }
      }
      if (player.hasTag(COOLDOWN_SHELTER2)) {
        if (in_shelter === false) {
          player.removeTag(COOLDOWN_SHELTER2);
          player.runCommand("/stopsound @s shapescape_bewe.sandstorm");
        }
      }
      const biome = player.getDynamicProperty(
        "shapescape_bewe:environment_detection.biome"
      ) ?? "";
      const biomeTagsProperty = player.getDynamicProperty(
        "shapescape_bewe:environment_detection.biome_tags"
      ) ?? "[]";
      const biomeTags = JSON.parse(biomeTagsProperty);
      if (biome === "")
        continue;
      if (!biomeTags.includes("desert") && biome !== "desert" && !biomeTags.includes("mesa") && biome !== "mesa")
        continue;
      if (player.location.y < 50 || player.dimension.id !== "minecraft:overworld")
        continue;
      if (player.hasTag(COOLDOWN_NORMAL2) || player.hasTag(COOLDOWN_SHELTER2))
        continue;
      if (!in_shelter) {
        player.addTag(COOLDOWN_NORMAL2);
        player.playSound("shapescape_bewe.sandstorm", { volume: 0.7 });
      } else {
        player.addTag(COOLDOWN_SHELTER2);
        player.playSound("shapescape_bewe.sandstorm", { volume: 0.3 });
      }
      system33.runTimeout(() => {
        player.removeTag(COOLDOWN_NORMAL2);
        player.removeTag(COOLDOWN_SHELTER2);
      }, SOUND_COOLDOWN4);
    } catch {
    }
  }
}
function applyAgainstWindEffects(player, shouldPlayAnimation = true, shouldApplyWindDamage = true) {
  const playerFlatLocation = Vec3.from(player.location).setY(0);
  const previousPlayerLocation = Vec3.from(
    player.getDynamicProperty(
      "shapescape_bewe:player_previous_location"
    ) ?? { x: 0.5, y: 0, z: 0.5 }
  ).setY(0);
  const threshold = playerFlatLocation.subtract(previousPlayerLocation);
  if (playerFlatLocation === void 0 || previousPlayerLocation === void 0 || threshold.length() < 0.01) {
    return;
  }
  const playerGeneralDirection = playerFlatLocation.subtract(
    previousPlayerLocation
  );
  const playerNormalizedDirection = playerGeneralDirection.normalize();
  const windDirection = Vec3.from(
    world33.getDynamicProperty("shapescape_bewe:wind_direction") ?? {
      x: 1,
      y: 0,
      z: 0
    }
  ).normalize();
  if (playerNormalizedDirection.dot(windDirection) < 0.5) {
    if (shouldPlayAnimation) {
      player.playAnimation("animation.shapescape_bewe.player.sandstorm_pose");
    }
    if (system33.currentTick % 60 === 0 && shouldApplyWindDamage) {
      player.applyDamage(1.1, { cause: EntityDamageCause10.none });
      randomTip(player, "sandstorm_against_wind");
    }
  }
  player.setDynamicProperty(
    "shapescape_bewe:player_previous_location",
    playerFlatLocation
  );
}
world33.afterEvents.playerSpawn.subscribe((event) => {
  if (event.initialSpawn === false) {
    event.player.removeTag(`shapescape_bewe_sandstorm_wind`);
  }
});
function randomTip(player, temperature) {
  const tipSetting = player.getDynamicProperty(
    `shapescape_bewe:settings.options.chat_warnings`
  ) ?? true;
  if (!tipSetting)
    return;
  if (player.hasTag(`shapescape_bewe_sandstorm_wind`))
    return;
  player.addTag(`shapescape_bewe_sandstorm_wind`);
  const message = {
    rawtext: [
      {
        translate: `shapescape_bewe.sandstorm_against_wind.tip`
      }
    ]
  };
  player.sendMessage(message);
  player.playSound(`note.bass`, {
    location: player.location
  });
}

// data/system_template_esbuild/subscripts/sea_sick.ts
import {
  EntityComponentTypes as EntityComponentTypes9,
  system as system34,
  TicksPerSecond as TicksPerSecond8,
  WeatherType as WeatherType4,
  world as world34
} from "@minecraft/server";
var DEBUG12 = false;
var DELAY = 20;
var REVERSE_MULTIPLIER = 2;
var MAX_STATE2 = 1;
var THRESHOLD2 = 0.5;
var INTERVAL4 = 1 * TicksPerSecond8;
var TAG3 = "shapescape_bewe_SEA_SICK";
system34.runInterval(() => {
  const players = world34.getAllPlayers();
  for (const player of players) {
    checkSeaSick(player);
  }
}, 1);
world34.afterEvents.playerSpawn.subscribe((event) => {
  if (event.initialSpawn === false) {
    updateSeaSick(event.player, 0, true);
    event.player.removeEffect("minecraft:nausea");
  }
});
function checkSeaSick(player) {
  const setting = player.getDynamicProperty(`shapescape_bewe:settings.states.sea_sick`) ?? true;
  if (!setting) {
    updateSeaSick(player, 0, true);
  }
  if (system34.currentTick % (9 * TicksPerSecond8) === 0) {
    const currentSeaSick = player.getDynamicProperty("sea_sick") ?? 0;
    if (currentSeaSick > THRESHOLD2 * MAX_STATE2) {
      player.addEffect("minecraft:nausea", 7 * TicksPerSecond8, {
        amplifier: 0,
        showParticles: false
      });
    }
  }
  if (system34.currentTick % INTERVAL4 === 0) {
    const currentSeaSick = player.getDynamicProperty("sea_sick") ?? 0;
    if (currentSeaSick > THRESHOLD2 * MAX_STATE2) {
      if (!player.hasTag(TAG3)) {
        player.sendMessage({ translate: `shapescape_bewe.sea_sick.tip` });
        player.playSound(`note.bass`, { location: player.location });
        player.addTag(TAG3);
      }
    }
    const currentWeather = world34.getDynamicProperty("shapescape_bewe:environment_detection.weather") ?? "clear";
    if (currentWeather.toUpperCase() === WeatherType4.Clear.toUpperCase())
      return;
    const ridingComp = player.getComponent(EntityComponentTypes9.Riding);
    const onBoat = ridingComp?.entityRidingOn.typeId.includes("minecraft:") && ridingComp?.entityRidingOn.typeId.includes("boat");
    let blockIn = void 0;
    let blockBelow1 = void 0;
    let blockBelow2 = void 0;
    try {
      blockIn = player.dimension.getBlock(player.location);
      blockBelow1 = blockIn?.below(1);
      blockBelow2 = blockIn?.below(2);
    } catch {
    }
    const waterBelow = blockIn?.typeId.includes("minecraft:") && blockIn?.typeId.includes("water") || blockBelow1?.typeId.includes("minecraft:") && blockBelow1?.typeId.includes("water") || blockBelow2?.typeId.includes("minecraft:") && blockBelow2?.typeId.includes("water");
    if (onBoat && waterBelow) {
      updateSeaSick(player, DELAY);
    } else {
      updateSeaSick(player, DELAY / REVERSE_MULTIPLIER, true);
    }
  }
}
function updateSeaSick(player, time, offBoat = false) {
  const currentSeaSick = player.getDynamicProperty("sea_sick") ?? 0;
  const step = MAX_STATE2 / (time === 0 ? 1 * (INTERVAL4 / TicksPerSecond8) : time) * (INTERVAL4 / TicksPerSecond8) * (offBoat ? -1 : 1);
  let newSeaSick = Number((currentSeaSick + step).toPrecision(5));
  if (newSeaSick >= MAX_STATE2) {
    newSeaSick = MAX_STATE2;
  } else if (newSeaSick <= 0) {
    newSeaSick = 0;
  }
  if (DEBUG12) {
    world34.sendMessage(`sea sick: ` + JSON.stringify(newSeaSick));
  }
  player.setDynamicProperty("sea_sick", newSeaSick);
}

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

// data/system_template_esbuild/subscripts/guide_book_page_access.ts
import { world as world35 } 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]];
var groupIdxGroupName = ["first_page", "contents", "vitality_compass_start", "world_mechanic_start", "10", "12", "14", "16", "storms_start", "20", "22", "24", "items_start", "28", "30", "32", "34", "36", "38", "40", "42", "structures_start", "46", "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" }], "vitality_compass_start": [{ "page_index": 2, "group_index": 2, "group_name": "vitality_compass_start" }], "world_mechanic_start": [{ "page_index": 3, "group_index": 3, "group_name": "world_mechanic_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" }], "storms_start": [{ "page_index": 8, "group_index": 8, "group_name": "storms_start" }], "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" }], "items_start": [{ "page_index": 12, "group_index": 12, "group_name": "items_start" }], "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" }], "34": [{ "page_index": 16, "group_index": 16, "group_name": "34" }], "36": [{ "page_index": 17, "group_index": 17, "group_name": "36" }], "38": [{ "page_index": 18, "group_index": 18, "group_name": "38" }], "40": [{ "page_index": 19, "group_index": 19, "group_name": "40" }], "42": [{ "page_index": 20, "group_index": 20, "group_name": "42" }], "structures_start": [{ "page_index": 21, "group_index": 21, "group_name": "structures_start" }], "46": [{ "page_index": 22, "group_index": 22, "group_name": "46" }], "last_page": [{ "page_index": 23, "group_index": 23, "group_name": "last_page" }] };
var pageInteractions = [{ "min": [-0.85, 0.185], "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", "vitality_compass_start", "world_mechanic_start", "10", "12", "14", "16", "storms_start", "20", "22", "24", "items_start", "28", "30", "32", "34", "36", "38", "40", "42", "structures_start", "46", "last_page"] }, { "min": [-0.85, 0.07], "max": [-0.66, 0.185], "responses": [{ "type": "set_page_group", "group_name": "contents" }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }], "group_name": ["vitality_compass_start", "world_mechanic_start", "10", "12", "14", "16", "storms_start", "20", "22", "24", "items_start", "28", "30", "32", "34", "36", "38", "40", "42", "structures_start", "46", "last_page"] }, { "min": [0.66, 0.09], "max": [0.85, 0.21], "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": "vitality_compass_start" }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }], "group_name": ["world_mechanic_start", "10", "12", "14", "16", "storms_start", "20", "22", "24", "items_start", "28", "30", "32", "34", "36", "38", "40", "42", "structures_start", "46", "last_page"] }, { "min": [0.66, -0.02], "max": [0.85, 0.09], "responses": [{ "type": "set_page_group", "group_name": "vitality_compass_start" }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }], "group_name": ["first_page", "contents"] }, { "min": [-0.85, -0.15], "max": [-0.66, -0.04], "responses": [{ "type": "set_page_group", "group_name": "world_mechanic_start" }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }], "group_name": ["10", "12", "14", "16", "storms_start", "20", "22", "24", "items_start", "28", "30", "32", "34", "36", "38", "40", "42", "structures_start", "46", "last_page"] }, { "min": [0.66, -0.13], "max": [0.85, -0.02], "responses": [{ "type": "set_page_group", "group_name": "world_mechanic_start" }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }], "group_name": ["first_page", "contents", "vitality_compass_start"] }, { "min": [-0.85, -0.26], "max": [-0.66, -0.15], "responses": [{ "type": "set_page_group", "group_name": "storms_start" }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }], "group_name": ["20", "22", "24", "items_start", "28", "30", "32", "34", "36", "38", "40", "42", "structures_start", "46", "last_page"] }, { "min": [0.66, -0.23], "max": [0.85, -0.13], "responses": [{ "type": "set_page_group", "group_name": "storms_start" }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }], "group_name": ["first_page", "contents", "vitality_compass_start", "world_mechanic_start", "10", "12", "14", "16"] }, { "min": [-0.85, -0.37], "max": [-0.66, -0.26], "responses": [{ "type": "set_page_group", "group_name": "items_start" }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }], "group_name": ["28", "30", "32", "34", "36", "38", "40", "42", "structures_start", "46", "last_page"] }, { "min": [0.66, -0.33], "max": [0.85, -0.23], "responses": [{ "type": "set_page_group", "group_name": "items_start" }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }], "group_name": ["first_page", "contents", "vitality_compass_start", "world_mechanic_start", "10", "12", "14", "16", "storms_start", "20", "22", "24"] }, { "min": [-0.85, -0.48], "max": [-0.66, -0.37], "responses": [{ "type": "set_page_group", "group_name": "structures_start" }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }], "group_name": ["46", "last_page"] }, { "min": [0.66, -0.48], "max": [0.85, -0.33], "responses": [{ "type": "set_page_group", "group_name": "structures_start" }, { "type": "run_command", "as": "book", "command": "/playsound item.book.page_turn @a[r=10]" }], "group_name": ["first_page", "contents", "vitality_compass_start", "world_mechanic_start", "10", "12", "14", "16", "storms_start", "20", "22", "24", "items_start", "28", "30", "32", "34", "36", "38", "40", "42"] }, { "min": [-0.85, -0.6], "max": [0.85, 0.45], "responses": [{ "type": "run_command", "as": "book", "command": "/particle shapescape_bewe: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_bewe.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_bewe.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_bewe.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_bewe.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_bewe: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_bewe:active_texture", group[0].page_index);
    return;
  }
  entity.runCommand(`function ${bookName}/get_${groupName}_state_value`);
  const stateIdx = world35.scoreboard.getObjective("shapescape_bewe_tmp_var")?.getScore("STATE")?.valueOf();
  if (typeof stateIdx != "number") {
    return;
  }
  entity.setProperty("shapescape_bewe: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 };
}
system35.afterEvents.scriptEventReceive.subscribe((event) => {
  if (event.id != `shapescape_bewe:${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 world37 } from "@minecraft/server";
var DEBUG13 = false;
var NAMESPACE = "shapescape_bewe:";
var PATH_NAMESPACE = "shapescape/bewe/";
world37.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 (DEBUG13) {
    world37.sendMessage(`Given Player Book`);
  }
}

// data/system_template_esbuild/subscripts/starting_eq.ts
import { world as world38 } from "@minecraft/server";
var DEBUG14 = false;
var NAMESPACE2 = "shapescape_bewe:";
var TAG4 = "eq";
var PATH_NAMESPACE2 = "shapescape/bewe/";
world38.afterEvents.playerSpawn.subscribe((event) => {
  givePlayerEq(event.player);
});
function givePlayerEq(player) {
  player.runCommand(
    `execute as @s[tag=!${NAMESPACE2.substring(
      0,
      NAMESPACE2.length - 1
    )}_${TAG4}] at @s run loot spawn ~ ~ ~ loot "${PATH_NAMESPACE2}starting_eq"`
  );
  player.runCommand(
    `tag @s[tag=!${NAMESPACE2.substring(0, NAMESPACE2.length - 1)}_${TAG4}] add ${NAMESPACE2.substring(
      0,
      NAMESPACE2.length - 1
    )}_${TAG4}`
  );
  if (DEBUG14) {
    world38.sendMessage(`Given Player Eq`);
  }
}

// data/system_template_esbuild/subscripts/temperature_system.ts
import {
  system as system36,
  world as world39,
  EntityDamageCause as EntityDamageCause12,
  MolangVariableMap as MolangVariableMap18,
  EntityComponentTypes as EntityComponentTypes10,
  GameMode as GameMode10,
  TicksPerSecond as TicksPerSecond9
} from "@minecraft/server";
var BASE_STEP = 1.5;
var DIFFICULTY_TABLE2 = /* @__PURE__ */ new Map([
  [0, 1],
  // Easy
  [1, 1.5],
  // Normal
  [2, 2]
  // Hard
]);
var DEBUG15 = false;
var TEMPERATURE_LIMIT_NEGATIVE = -0.65;
var TEMPERATURE_LIMIT_POSITIVE = 0.65;
var REFRESH_RATE_UPDATE = 1 * 20;
var REFRESH_RATE_CALCULATION = 1 * 20;
var EFFECTS_INTERVAL = 1 * 20;
var MAX_PROGRESS = 300;
function calculateTemperature(player) {
  let biomeTemperature = player.getDynamicProperty(
    "shapescape_bewe:environment_detection.biome_temperature"
  ) ?? 0;
  biomeTemperature = biomeTemperature * 2 - 1;
  biomeTemperature = biomeTemperature * 0.85 /* biomeTemperature */;
  if (biomeTemperature > 0.8) {
    biomeTemperature = 0.7;
  }
  let blocksTemperatureHeat = player.getDynamicProperty(
    "shapescape_bewe:temperature.blocks.heat"
  ) ?? 0;
  let blocksTemperatureCold = player.getDynamicProperty(
    "shapescape_bewe:temperature.blocks.cold"
  ) ?? 0;
  blocksTemperatureHeat = blocksTemperatureHeat * 0.01;
  blocksTemperatureCold = blocksTemperatureCold * 0.01;
  let blocksTemperature = 0;
  if (biomeTemperature > 0) {
    blocksTemperature = blocksTemperatureCold + blocksTemperatureHeat * 0.02;
  } else {
    blocksTemperature = blocksTemperatureHeat + blocksTemperatureCold * 0.02;
  }
  blocksTemperature = blocksTemperature * 1 /* blocksTemperature */;
  blocksTemperature = clamp(blocksTemperature, -0.3, 0.3);
  const heaterBlock = player.getDynamicProperty(
    "shapescape_bewe:temperature.heaterBlock"
  ) ?? 0;
  if (heaterBlock > 1) {
    blocksTemperature += 0.5;
  }
  const coolerBlock = player.getDynamicProperty(
    "shapescape_bewe:temperature.coolerBlock"
  ) ?? 0;
  if (coolerBlock > 1) {
    blocksTemperature -= 0.5;
  }
  let shelterTemperature = player.getDynamicProperty("shapescape_bewe:temperature.shelter") ?? 0;
  if (shelterTemperature >= 3) {
    shelterTemperature = shelterTemperature * 0.03;
    shelterTemperature = shelterTemperature * 1 /* shelter */;
    if (biomeTemperature > 0.3) {
      shelterTemperature = -shelterTemperature;
    }
  } else
    shelterTemperature = 0;
  let timeOfDayTemperature = world39.getDynamicProperty(
    "shapescape_bewe:temperature.time_of_day"
  ) ?? 0;
  if (player.dimension.id === "minecraft:overworld") {
    timeOfDayTemperature = timeOfDayTemperature * 0.01;
    timeOfDayTemperature = timeOfDayTemperature * 0.5 /* timeOfDay */;
    if (shelterTemperature > 0) {
      timeOfDayTemperature = timeOfDayTemperature * 0.3;
    }
  } else
    timeOfDayTemperature = 0;
  let armorTemperature = player.getDynamicProperty("shapescape_bewe:temperature.armor") ?? 0;
  armorTemperature = armorTemperature * 0.01;
  if (biomeTemperature > 0 && armorTemperature > 0.3) {
    armorTemperature = 0.3;
  }
  if (biomeTemperature < 0 && armorTemperature < 0) {
    armorTemperature = 0;
  }
  armorTemperature = armorTemperature * 1 /* armorTemperature */;
  let isInWaterTemperature = 0;
  if (player.isInWater) {
    if (biomeTemperature > 0) {
      isInWaterTemperature = -0.1 * 1 /* isInWaterTemperature */;
    } else {
      isInWaterTemperature = -0.2 * 1 /* isInWaterTemperature */;
    }
  }
  let altitudeTemperature = 0;
  let altitude = player.location.y;
  if (altitude < 50)
    altitudeTemperature = 0.03;
  if (altitude < 40)
    altitudeTemperature = 0.06;
  if (altitude < 30)
    altitudeTemperature = 0.08;
  if (altitude < 15)
    altitudeTemperature = 0.1;
  if (altitude < -10)
    altitudeTemperature = 0.12;
  if (altitude < -20)
    altitudeTemperature = 0.14;
  if (altitude < -30)
    altitudeTemperature = 0.16;
  if (altitude < -40)
    altitudeTemperature = 0.19;
  if (altitude < -50)
    altitudeTemperature = 0.23;
  if (altitude > 60)
    altitudeTemperature = -0.01;
  if (altitude > 70)
    altitudeTemperature = -0.05;
  if (altitude > 80)
    altitudeTemperature = -0.08;
  if (altitude > 90)
    altitudeTemperature = -0.13;
  if (altitude > 100)
    altitudeTemperature = -0.17;
  if (altitude > 120)
    altitudeTemperature = -0.2;
  if (altitude > 135)
    altitudeTemperature = -0.22;
  if (altitude > 160)
    altitudeTemperature = -0.24;
  if (altitude > 185)
    altitudeTemperature = -0.26;
  if (altitude > 210)
    altitudeTemperature = -0.31;
  let movementTemperature = 0;
  if (player.isSprinting && !player.isGliding) {
    if (biomeTemperature > 0) {
      movementTemperature += 0.05;
    } else {
      movementTemperature += 0.1;
    }
  }
  if (player.isGliding) {
    movementTemperature -= 0.05;
  }
  const WEATHER = world39.getDynamicProperty(
    "shapescape_bewe:environment_detection.weather"
  ) ?? "clear";
  let weatherTemperature = 0;
  if (player.dimension.id === "minecraft:overworld") {
    if (biomeTemperature < 0) {
      if (WEATHER === "rain")
        weatherTemperature = -0.18;
      if (WEATHER === "thunderstorm")
        weatherTemperature = -0.3;
    }
    if (biomeTemperature >= 0) {
      if (WEATHER === "rain")
        weatherTemperature = -0.14;
      if (WEATHER === "thunderstorm")
        weatherTemperature = -0.24;
    }
    if (shelterTemperature > 0) {
      weatherTemperature = weatherTemperature * 0.3;
    }
  }
  weatherTemperature = weatherTemperature * 1 /* weatherTemperature */;
  let onFireTemperature = 0;
  const onfire = player.getComponent(EntityComponentTypes10.OnFire);
  if (onfire) {
    if (biomeTemperature < 0) {
      onFireTemperature = 1.5;
    } else {
      onFireTemperature = 1;
    }
  }
  const wetStateThreshold = 0.2;
  const currentWetState = player.getDynamicProperty("wet_state") ?? 0;
  let wetStateTemperature = 0;
  if (currentWetState > wetStateThreshold) {
    wetStateTemperature = -currentWetState;
  }
  const muddyStateThreshold = 0.5;
  const currentMuddyState = player.getDynamicProperty("muddy_state") ?? 0;
  let muddyStateTemperature = 0;
  if (currentMuddyState > muddyStateThreshold) {
    muddyStateTemperature = -currentMuddyState * 0.15;
  }
  let itemTemperature = player.getDynamicProperty("shapescape_bewe:temperature.item") ?? 0;
  itemTemperature = itemTemperature * 0.01;
  itemTemperature = itemTemperature * 1.3 /* itemTemperature */;
  let foodTemperature = player.getDynamicProperty("shapescape_bewe:temperature.food") ?? 0;
  foodTemperature = foodTemperature * 0.01;
  if (biomeTemperature > 0 && foodTemperature > 0) {
    foodTemperature = foodTemperature * 0.4;
  }
  if (biomeTemperature < 0 && foodTemperature < 0) {
    foodTemperature = foodTemperature * 0.4;
  }
  foodTemperature = clamp(
    foodTemperature * 1.3 /* foodTemperature */,
    -0.3,
    0.3
  );
  let dimensionTemperature = 0;
  if (player.dimension.id === "minecraft:nether") {
    dimensionTemperature = 0.4;
  } else if (player.dimension.id === "minecraft:the_end") {
    dimensionTemperature = -1.1;
  }
  let temperature = biomeTemperature + timeOfDayTemperature + blocksTemperature + shelterTemperature + armorTemperature + isInWaterTemperature + weatherTemperature + itemTemperature + foodTemperature + movementTemperature + altitudeTemperature + onFireTemperature + wetStateTemperature + muddyStateTemperature + dimensionTemperature;
  let world_temperature = biomeTemperature + timeOfDayTemperature + blocksTemperature + shelterTemperature + isInWaterTemperature + weatherTemperature + altitudeTemperature + dimensionTemperature;
  if (DEBUG15) {
    player.sendMessage(`------------`);
    player.sendMessage(`biome: ${biomeTemperature}`);
    player.sendMessage(`time: ${timeOfDayTemperature}`);
    player.sendMessage(`blocks: ${blocksTemperature}`);
    player.sendMessage(`shelter: ${shelterTemperature}`);
    player.sendMessage(`armor: ${armorTemperature}`);
    player.sendMessage(`water: ${isInWaterTemperature}`);
    player.sendMessage(`weather: ${weatherTemperature}`);
    player.sendMessage(`item: ${itemTemperature}`);
    player.sendMessage(`food: ${foodTemperature}`);
    player.sendMessage(`movement: ${movementTemperature}`);
    player.sendMessage(`altitude: ${altitudeTemperature}`);
    player.sendMessage(`onFire: ${onFireTemperature}`);
    player.sendMessage(`wetState: ${wetStateTemperature}`);
    player.sendMessage(`muddyState: ${muddyStateTemperature}`);
    player.sendMessage(`dimension: ${dimensionTemperature}`);
  }
  player.setDynamicProperty(
    "shapescape_bewe:surrounding_temperature",
    world_temperature
  );
  player.setDynamicProperty("shapescape_bewe:temperature_target", temperature);
}
function updateTemperature(player) {
  const currentTemperature = player.getDynamicProperty("shapescape_bewe:temperature") ?? 0.5;
  const targetTemperature = player.getDynamicProperty("shapescape_bewe:temperature_target") ?? 0.5;
  const difference = Math.abs(targetTemperature - currentTemperature);
  const interpolationFactor = Math.min(1e-4 + difference * 0.01, 0.05) * REFRESH_RATE_UPDATE;
  const easedTemperature = easeOutCirc(interpolationFactor);
  const newTemperature = currentTemperature + (targetTemperature - currentTemperature) * easedTemperature;
  player.setDynamicProperty("shapescape_bewe:temperature", newTemperature);
  if (DEBUG15) {
    const displayCurrentTemperature = Math.round(newTemperature * 100) / 100;
    const displayTargetTemperature = Math.round(targetTemperature * 100) / 100;
    const message = `\xA7bTemperature: \xA7f${displayCurrentTemperature} \xA76| \xA7bTarget Temperature: \xA7f${displayTargetTemperature}`;
    player.onScreenDisplay.setActionBar({ text: message });
  }
}
function effects(player) {
  const temperature = player.getDynamicProperty("shapescape_bewe:temperature") ?? 0;
  const targetTemperature = player.getDynamicProperty("shapescape_bewe:temperature_target") ?? 0;
  let freezingProgress = player.getDynamicProperty("shapescape_bewe:temperature.freezing") ?? 0;
  let overheatingProgress = player.getDynamicProperty("shapescape_bewe:temperature.overheating") ?? 0;
  let freezingImmune = player.getDynamicProperty("f_i") ?? false;
  let overheatingImmune = player.getDynamicProperty("o_i") ?? false;
  const allowedGamemode = player.getGameMode() !== GameMode10.Creative && player.getGameMode() !== GameMode10.Spectator;
  if (!allowedGamemode)
    return;
  const isFreezing = temperature <= TEMPERATURE_LIMIT_NEGATIVE;
  const isOverheating = temperature >= TEMPERATURE_LIMIT_POSITIVE;
  const difficulty2 = player.getDynamicProperty(`shapescape_bewe:settings.options.difficulty`) ?? 0;
  const step = BASE_STEP * Math.abs(temperature * 2.5) * (DIFFICULTY_TABLE2.get(difficulty2) ?? 1);
  if (isFreezing) {
    freezingProgress = freezingProgress + step;
  } else if (freezingProgress > 0) {
    freezingProgress = Math.max(freezingProgress - 10, 0);
  }
  if (isOverheating) {
    overheatingProgress = overheatingProgress + step;
  } else if (overheatingProgress > 0) {
    overheatingProgress = Math.max(overheatingProgress - 10, 0);
  }
  player.setDynamicProperty(
    "shapescape_bewe:temperature.freezing",
    freezingProgress
  );
  player.setDynamicProperty(
    "shapescape_bewe:temperature.overheating",
    overheatingProgress
  );
  if (freezingProgress > 0 && isFreezing && freezingImmune === false) {
    freezing(player, freezingProgress, targetTemperature);
  }
  if (overheatingProgress > 0 && isOverheating && overheatingImmune === false) {
    overheating(player, overheatingProgress, targetTemperature);
  }
}
function freezing(player, progress, targetTemperature) {
  const cameraShake = false;
  const currentSeconds = system36.currentTick / TicksPerSecond9;
  let settingFreezingEffects = player.getDynamicProperty(
    "shapescape_bewe:settings.temperature.freezing_effects"
  ) ?? true;
  let settingFreezingDamage = player.getDynamicProperty(
    "shapescape_bewe:settings.temperature.freezing_damage"
  ) ?? true;
  if (settingFreezingEffects || settingFreezingDamage)
    randomTip2(player, "freezing", progress);
  if (!settingFreezingEffects && !settingFreezingDamage)
    return;
  if (progress > 10 && currentSeconds % 1 === 0 && targetTemperature < TEMPERATURE_LIMIT_NEGATIVE) {
    player.runCommand(
      "/playanimation @s animation.shapescape_bewe.player.freezing null 0.1"
    );
  }
  if (progress > 10 && progress < 60) {
    if (settingFreezingEffects && cameraShake)
      player.runCommand(`/camerashake add @s 0.02 1.05 positional`);
  }
  if (progress > 15 && currentSeconds % 4 === 0 && targetTemperature < TEMPERATURE_LIMIT_NEGATIVE) {
    if (settingFreezingEffects)
      particleColdBreath(player);
  }
  if (progress >= 60 && progress < 90) {
    if (settingFreezingEffects && cameraShake)
      player.runCommand(`/camerashake add @s 0.05 1.05 positional`);
  }
  if (progress > 60 && currentSeconds % 10 === 0) {
    if (settingFreezingEffects)
      player.playSound("fall.powder_snow", {
        location: player.location,
        volume: 0.9,
        pitch: 0.9
      });
  }
  if (progress >= 90 && progress < 120) {
    if (settingFreezingEffects)
      player.addEffect("slowness", 25, { showParticles: false, amplifier: 0 });
    if (settingFreezingEffects && cameraShake)
      player.runCommand(`/camerashake add @s 0.1 1.05 positional`);
  }
  if (progress >= 120 && progress < 180) {
    if (settingFreezingEffects)
      player.addEffect("slowness", 25, { showParticles: false, amplifier: 1 });
    if (settingFreezingEffects && cameraShake)
      player.runCommand(`/camerashake add @s 0.12 1.05`);
    if (currentSeconds % 5 === 0 && targetTemperature < TEMPERATURE_LIMIT_NEGATIVE) {
      if (settingFreezingDamage)
        player.applyDamage(1, { cause: EntityDamageCause12.freezing });
    }
  }
  if (progress >= 180 && progress < 220) {
    if (settingFreezingEffects)
      player.addEffect("slowness", 25, { showParticles: false, amplifier: 1 });
    if (settingFreezingEffects && cameraShake)
      player.runCommand(`/camerashake add @s 0.15 1.05`);
    if (currentSeconds % 3 === 0 && targetTemperature < TEMPERATURE_LIMIT_NEGATIVE) {
      if (settingFreezingDamage)
        player.applyDamage(1, { cause: EntityDamageCause12.freezing });
    }
  }
  if (progress >= 220) {
    if (currentSeconds % 2 === 0 && targetTemperature < TEMPERATURE_LIMIT_NEGATIVE) {
      if (settingFreezingDamage)
        player.applyDamage(2, { cause: EntityDamageCause12.freezing });
    }
    if (settingFreezingEffects)
      player.addEffect("slowness", 25, { showParticles: false, amplifier: 1 });
    if (settingFreezingEffects && cameraShake)
      player.runCommand(`/camerashake add @s 0.18 1.05`);
  }
  if (progress > MAX_PROGRESS) {
    player.setDynamicProperty("shapescape_bewe:temperature.freezing", 300);
  }
}
function overheating(player, progress, targetTemperature) {
  const currentSeconds = system36.currentTick / TicksPerSecond9;
  let setting_heat_effects = player.getDynamicProperty(
    "shapescape_bewe:settings.temperature.heat_effects"
  ) ?? true;
  let setting_heat_damage = player.getDynamicProperty(
    "shapescape_bewe:settings.temperature.heat_damage"
  ) ?? true;
  if (!setting_heat_effects && !setting_heat_damage)
    return;
  randomTip2(player, "overheating", progress);
  if (currentSeconds % 4 === 0 && targetTemperature > TEMPERATURE_LIMIT_POSITIVE) {
    player.runCommand(
      "/playanimation @s animation.shapescape_bewe.player.overheat null 1"
    );
  }
  if (currentSeconds % 8 === 0 && targetTemperature > TEMPERATURE_LIMIT_POSITIVE) {
    particleSweat(player);
  }
  if (progress > 5 && progress < 60) {
    if (currentSeconds % 10 === 0) {
      if (setting_heat_effects)
        player.addEffect("nausea", 100, { showParticles: false, amplifier: 0 });
    }
  }
  if (progress >= 60 && progress < 90) {
    if (setting_heat_effects)
      player.addEffect("weakness", 40, { showParticles: false, amplifier: 0 });
    if (currentSeconds % 7 === 0) {
      if (setting_heat_effects)
        player.addEffect("nausea", 120, { showParticles: false, amplifier: 0 });
    }
  }
  if (progress >= 90 && progress < 120) {
    if (currentSeconds % 7 === 0) {
      if (setting_heat_effects)
        player.addEffect("nausea", 120, { showParticles: false, amplifier: 0 });
    }
    if (setting_heat_effects)
      player.addEffect("mining_fatigue", 40, {
        showParticles: false,
        amplifier: 0
      });
    if (setting_heat_effects)
      player.addEffect("weakness", 40, { showParticles: false, amplifier: 0 });
    if (setting_heat_effects)
      player.addEffect("slowness", 40, { showParticles: false, amplifier: 0 });
  }
  if (progress >= 120 && progress < 180) {
    if (currentSeconds % 7 === 0) {
      if (setting_heat_effects)
        player.addEffect("nausea", 120, { showParticles: false, amplifier: 0 });
    }
    if (setting_heat_effects)
      player.addEffect("mining_fatigue", 40, {
        showParticles: false,
        amplifier: 0
      });
    if (setting_heat_effects)
      player.addEffect("weakness", 40, { showParticles: false, amplifier: 1 });
    if (currentSeconds % 5 === 0 && targetTemperature > TEMPERATURE_LIMIT_POSITIVE) {
      if (setting_heat_damage)
        player.applyDamage(1, { cause: EntityDamageCause12.fireTick });
    }
  }
  if (progress >= 180 && progress < 220) {
    if (currentSeconds % 7 === 0) {
      if (setting_heat_effects)
        player.addEffect("nausea", 120, { showParticles: false, amplifier: 0 });
    }
    if (setting_heat_effects)
      player.addEffect("mining_fatigue", 40, {
        showParticles: false,
        amplifier: 0
      });
    if (setting_heat_effects)
      player.addEffect("weakness", 40, { showParticles: false, amplifier: 1 });
    if (setting_heat_effects)
      player.addEffect("blindness", 60, { showParticles: false, amplifier: 1 });
    if (currentSeconds % 3 === 0 && targetTemperature > TEMPERATURE_LIMIT_POSITIVE) {
      if (setting_heat_damage)
        player.applyDamage(1, { cause: EntityDamageCause12.fireTick });
    }
  }
  if (progress >= 220) {
    if (currentSeconds % 7 === 0) {
      if (setting_heat_effects)
        player.addEffect("nausea", 120, { showParticles: false, amplifier: 0 });
    }
    if (setting_heat_effects)
      player.addEffect("mining_fatigue", 40, {
        showParticles: false,
        amplifier: 0
      });
    if (setting_heat_effects)
      player.addEffect("weakness", 40, { showParticles: false, amplifier: 1 });
    if (setting_heat_effects)
      player.addEffect("blindness", 60, { showParticles: false, amplifier: 1 });
    if (currentSeconds % 2 === 0 && targetTemperature > TEMPERATURE_LIMIT_POSITIVE) {
      if (setting_heat_damage)
        player.applyDamage(2, { cause: EntityDamageCause12.fireTick });
    }
  }
  if (progress > MAX_PROGRESS) {
    player.setDynamicProperty("shapescape_bewe:temperature.overheating", 300);
  }
}
function particleSweat(player) {
  const headLocation = player.getHeadLocation();
  const direction = player.getViewDirection();
  const velocity = player.getVelocity();
  const particleLocation = {
    x: headLocation.x + direction.x * 0.1 + velocity.x * 5,
    y: headLocation.y + 0.1 + direction.y * 0.1 + velocity.y * 5,
    z: headLocation.z + direction.z * 0.1 + velocity.z * 5
  };
  let speed = Math.sqrt(velocity.x ** 2 + velocity.y ** 2 + velocity.z ** 2);
  const molang = new MolangVariableMap18();
  molang.setFloat("variable.size_from_velocity", 1 + speed * 4);
  try {
    player.dimension.spawnParticle(
      "shapescape_bewe:sweat",
      particleLocation,
      molang
    );
  } catch {
  }
}
function particleColdBreath(player) {
  const headLocation = player.getHeadLocation();
  const direction = player.getViewDirection();
  const particleLocation = {
    x: headLocation.x + direction.x * 0.2,
    y: headLocation.y - 0.1 + direction.y * 0.2,
    z: headLocation.z + direction.z * 0.2
  };
  const molang = new MolangVariableMap18();
  molang.setSpeedAndDirection("variable.particle", 0.6, direction);
  try {
    player.dimension.spawnParticle(
      "shapescape_bewe:cold_breath",
      particleLocation,
      molang
    );
  } catch {
  }
  player.playSound("mob.horse.breathe", {
    location: player.location,
    volume: 0.8,
    pitch: 1.3
  });
}
function easeOutCirc(x) {
  return Math.sqrt(1 - Math.pow(x - 1, 2));
}
function clamp(value, min, max) {
  return Math.min(Math.max(value, min), max);
}
function randomTip2(player, temperature, progres) {
  const tipSetting = player.getDynamicProperty(
    `shapescape_bewe:settings.options.chat_warnings`
  ) ?? true;
  if (!tipSetting)
    return;
  let messageNumber = 0;
  if (progres >= 15 && progres < 60) {
    messageNumber = 1;
  } else if (progres >= 60 && progres < 120) {
    messageNumber = 2;
  } else if (progres >= 120 && progres < 300) {
    messageNumber = 3;
  }
  player.removeTag(
    `shapescape_bewe_TEMPERATURE_TIP.${temperature}_${messageNumber + 1}`
  );
  if (messageNumber === 0) {
    return;
  }
  if (player.hasTag(`shapescape_bewe_TEMPERATURE_TIP.${temperature}_${messageNumber}`))
    return;
  player.addTag(`shapescape_bewe_TEMPERATURE_TIP.${temperature}_${messageNumber}`);
  const message = {
    rawtext: [
      {
        translate: `shapescape_bewe.temperature.tip.${temperature}.${messageNumber}`
      }
    ]
  };
  player.sendMessage(message);
  player.playSound(`note.bass`, {
    location: player.location
  });
}
world39.afterEvents.entityDie.subscribe((event) => {
  const player = event.deadEntity;
  if (player.typeId !== "minecraft:player")
    return;
  player.setDynamicProperty("shapescape_bewe:temperature", 0);
  player.setDynamicProperty("shapescape_bewe:temperature_target", 0);
  player.setDynamicProperty("shapescape_bewe:temperature.freezing", 0);
  player.setDynamicProperty("shapescape_bewe:temperature.overheating", 0);
});
system36.runInterval(() => {
  let players = world39.getPlayers();
  for (let player of players) {
    if (system36.currentTick % REFRESH_RATE_UPDATE === 0) {
      updateTemperature(player);
    }
    if (system36.currentTick % REFRESH_RATE_CALCULATION === 0) {
      calculateTemperature(player);
    }
    if (system36.currentTick % EFFECTS_INTERVAL === 0) {
      effects(player);
    }
  }
}, 1);

// data/system_template_esbuild/subscripts/temperature_blocks.ts
import {
  system as system37,
  world as world40
} from "@minecraft/server";
var REFRESH_RATE12 = 2 * 20;
var PROCESSING_TAG = "shapescape_bewe_temperature_block_process";
world40.afterEvents.playerSpawn.subscribe((event) => {
  event.player.removeTag(PROCESSING_TAG);
});
var heat_blocks = {
  "minecraft:fire": 4,
  "minecraft:soul_fire": 4,
  // campfire extinguished detection in calculation
  "minecraft:campfire": 12,
  "minecraft:soul_campfire": 12,
  "minecraft:lava": 8,
  "minecraft:magma": 2,
  // cauldron lava detection in calculation
  "minecraft:cauldron": 5,
  "minecraft:lit_furnace": 5,
  "minecraft:lit_blast_furnace": 5,
  "minecraft:lit_smoker": 5,
  "minecraft:torch": 1,
  "minecraft:soul_torch": 1,
  "minecraft:lit_pumpkin": 2,
  "minecraft:lantern": 1,
  "minecraft:soul_lantern": 1,
  // COLD
  "minecraft:ice": -5,
  "minecraft:blue_ice": -6,
  "minecraft:forested_ice": -8,
  "minecraft:packed_ice": -8,
  "minecraft:snow": -3,
  "minecraft:snow_layer": -2,
  "minecraft:powder_snow": -2,
  "minecraft:water": -0.5
};
function getHeatBlocksInRadius(dimension, origin, radius) {
  return new Promise((resolve) => {
    const generator = function* () {
      const heatBlocks = [];
      for (let x = -radius; x <= radius; x++) {
        for (let y = -radius; y <= radius; y++) {
          for (let z = -radius; z <= radius; z++) {
            try {
              let block = void 0;
              try {
                block = dimension.getBlock({
                  x: origin.x + x,
                  y: origin.y + y,
                  z: origin.z + z
                });
              } catch {
              }
              if (block && !block.isAir && heat_blocks.hasOwnProperty(block.typeId)) {
                heatBlocks.push(block);
              }
              yield;
            } catch {
              yield;
            }
          }
        }
      }
      resolve(heatBlocks);
    };
    system37.runJob(generator());
  });
}
async function temperature_update(player) {
  player.addTag(PROCESSING_TAG);
  const radius = 5;
  const nearbyHeatBlocks = await getHeatBlocksInRadius(player.dimension, player.location, radius);
  if (!player)
    return;
  let totalHeat = 0;
  let totalCold = 0;
  for (let block of nearbyHeatBlocks) {
    if (block.typeId === "minecraft:campfire" || block.typeId === "minecraft:soul_campfire") {
      let is_extinguished = block.permutation.getState("extinguished");
      if (is_extinguished)
        continue;
    }
    if (block.typeId === "minecraft:cauldron") {
      let liquid = block.permutation.getState("cauldron_liquid");
      let fill_level = block.permutation.getState("fill_level");
      if (liquid !== "lava" || fill_level === 0)
        continue;
    }
    const heatValue = heat_blocks[block.typeId];
    if (heatValue === void 0)
      continue;
    if (heatValue > 0) {
      totalHeat += heatValue;
    } else {
      totalCold += heatValue;
    }
  }
  player.setDynamicProperty("shapescape_bewe:temperature.blocks.heat", totalHeat);
  player.setDynamicProperty("shapescape_bewe:temperature.blocks.cold", totalCold);
  player.removeTag(PROCESSING_TAG);
}
system37.runInterval(() => {
  let players = world40.getPlayers();
  for (let player of players) {
    if (!player.hasTag(PROCESSING_TAG)) {
      try {
        temperature_update(player);
      } catch {
      }
    }
  }
}, REFRESH_RATE12);
system37.runInterval(() => {
  const entities = world40.getDimension("Overworld").getEntities({ families: ["shapescape_bewe_thermometer_block"] });
  for (let entity of entities) {
    if (!entity.hasTag(PROCESSING_TAG)) {
      try {
        temperature_update_thermometer_block(entity);
      } catch {
        continue;
      }
    }
  }
}, REFRESH_RATE12 * 4);
async function temperature_update_thermometer_block(thermometer_block) {
  thermometer_block.addTag(PROCESSING_TAG);
  const radius = 5;
  const nearbyHeatBlocks = await getHeatBlocksInRadius(thermometer_block.dimension, thermometer_block.location, radius);
  if (!thermometer_block)
    return;
  let totalHeat = 0;
  let totalCold = 0;
  for (let block of nearbyHeatBlocks) {
    if (block.typeId === "minecraft:campfire" || block.typeId === "minecraft:soul_campfire") {
      let is_extinguished = block.permutation.getState("extinguished");
      if (is_extinguished)
        continue;
    }
    if (block.typeId === "minecraft:cauldron") {
      let liquid = block.permutation.getState("cauldron_liquid");
      let fill_level = block.permutation.getState("fill_level");
      if (liquid !== "lava" || fill_level === 0)
        continue;
    }
    const heatValue = heat_blocks[block.typeId];
    if (heatValue > 0) {
      totalHeat += heatValue;
    } else {
      totalCold += heatValue;
    }
  }
  if (thermometer_block.isValid) {
    thermometer_block.setDynamicProperty("shapescape_bewe:temperature.blocks.heat", totalHeat);
    thermometer_block.setDynamicProperty("shapescape_bewe:temperature.blocks.cold", totalCold);
    thermometer_block.removeTag(PROCESSING_TAG);
  }
}

// data/system_template_esbuild/subscripts/temperature_time_of_day.ts
import { system as system38, world as world41 } from "@minecraft/server";
var REFRESH_RATE13 = 5 * 20;
system38.runInterval(() => {
  const timeOfDay = world41.getTimeOfDay();
  let temperature = 0;
  if (timeOfDay >= 23e3 /* SUNRISE */ || timeOfDay < 1e3 /* DAY */) {
    temperature += 5;
  } else if (timeOfDay >= 1e3 /* DAY */ && timeOfDay < 6e3 /* NOON */) {
    temperature += 10;
  } else if (timeOfDay >= 6e3 /* NOON */ && timeOfDay < 12e3 /* SUNSET */) {
    temperature += 15;
  } else if (timeOfDay >= 12e3 /* SUNSET */ && timeOfDay < 12610 /* DUSK */) {
    temperature -= 5;
  } else if (timeOfDay >= 12610 /* DUSK */ && timeOfDay < 13e3 /* NIGHT */) {
    temperature -= 10;
  } else if (timeOfDay >= 13e3 /* NIGHT */ && timeOfDay < 18e3 /* MIDNIGHT */) {
    temperature -= 15;
  } else if (timeOfDay >= 18e3 /* MIDNIGHT */ && timeOfDay < 23e3 /* SUNRISE */) {
    temperature -= 20;
  }
  world41.setDynamicProperty("shapescape_bewe:temperature.time_of_day", temperature);
}, REFRESH_RATE13);

// data/system_template_esbuild/subscripts/temperature_shelter.ts
import { system as system39, world as world42 } from "@minecraft/server";
var DEBUG16 = false;
var REFRESH_RATE14 = 5 * 20;
var RADIUS = 10;
var PROCESSING_TAG2 = "shapescape_bewe_temperature_shelter_process";
world42.afterEvents.playerSpawn.subscribe((event) => {
  event.player.removeTag(PROCESSING_TAG2);
});
function getWallsInRadius(player, radius) {
  if (!player.isValid)
    return;
  const location = {
    x: player.location.x,
    y: player.location.y + 1,
    z: player.location.z
  };
  const directions = [
    { x: 0, y: 1, z: 0 },
    { x: 1, y: 0, z: 0 },
    { x: -1, y: 0, z: 0 },
    { x: 0, y: 0, z: 1 },
    { x: 0, y: 0, z: -1 }
  ];
  let walls = 0;
  for (const direction of directions) {
    const block = player.dimension.getBlockFromRay(location, direction, {
      includeLiquidBlocks: false,
      includePassableBlocks: false,
      maxDistance: radius
    })?.block;
    if (block)
      walls += 1;
  }
  return walls;
}
async function shelter_check(player) {
  player.addTag(PROCESSING_TAG2);
  const cover = await getWallsInRadius(player, RADIUS);
  if (DEBUG16)
    console.warn("Cover:", cover);
  player.setDynamicProperty("shapescape_bewe:temperature.shelter", cover);
  player.removeTag(PROCESSING_TAG2);
}
system39.runInterval(() => {
  let players = world42.getPlayers();
  for (let player of players) {
    if (!player.hasTag(PROCESSING_TAG2)) {
      try {
        shelter_check(player);
      } catch {
        continue;
      }
    }
  }
}, REFRESH_RATE14);
system39.runInterval(() => {
  const entities = world42.getDimension("Overworld").getEntities({ families: ["shapescape_bewe_thermometer_block"] });
  for (let entity of entities) {
    if (!entity.hasTag(PROCESSING_TAG2)) {
      try {
        shelter_check_thermometer_block(entity);
      } catch {
        continue;
      }
    }
  }
}, REFRESH_RATE14 * 2);
async function shelter_check_thermometer_block(thermometer_block) {
  thermometer_block.addTag(PROCESSING_TAG2);
  const cover = await getWallsInRadius(thermometer_block, RADIUS);
  if (thermometer_block.isValid) {
    thermometer_block.setDynamicProperty("shapescape_bewe:temperature.shelter", cover);
    thermometer_block.removeTag(PROCESSING_TAG2);
  }
}

// data/system_template_esbuild/subscripts/temperature_armor.ts
import { EquipmentSlot as EquipmentSlot5, system as system40, world as world43 } from "@minecraft/server";
var DEBUG17 = false;
var REFRESH_RATE15 = 1 * 20;
var STATS = {
  // COLD
  "shapescape_bewe:cold_helmet": 15,
  "shapescape_bewe:cold_chestplate": 20,
  "shapescape_bewe:cold_leggings": 20,
  "shapescape_bewe:cold_boots": 15,
  // HEAT
  "shapescape_bewe:sun_helmet": -8,
  "shapescape_bewe:sun_chestplate": -12,
  "shapescape_bewe:sun_leggings": -12,
  "shapescape_bewe:sun_boots": -8,
  // LEATHER WARM
  "shapescape_bewe:leather_warm_helmet": 15,
  "shapescape_bewe:leather_warm_chestplate": 20,
  "shapescape_bewe:leather_warm_leggings": 20,
  "shapescape_bewe:leather_warm_boots": 15,
  // IRON WARM
  "shapescape_bewe:iron_warm_helmet": 15,
  "shapescape_bewe:iron_warm_chestplate": 20,
  "shapescape_bewe:iron_warm_leggings": 20,
  "shapescape_bewe:iron_warm_boots": 15,
  // GOLD WARM
  "shapescape_bewe:gold_warm_helmet": 15,
  "shapescape_bewe:gold_warm_chestplate": 20,
  "shapescape_bewe:gold_warm_leggings": 20,
  "shapescape_bewe:gold_warm_boots": 15,
  // DIAMOND WARM
  "shapescape_bewe:diamond_warm_helmet": 15,
  "shapescape_bewe:diamond_warm_chestplate": 20,
  "shapescape_bewe:diamond_warm_leggings": 20,
  "shapescape_bewe:diamond_warm_boots": 15,
  // NETHERITE WARM
  "shapescape_bewe:netherite_warm_helmet": 15,
  "shapescape_bewe:netherite_warm_chestplate": 20,
  "shapescape_bewe:netherite_warm_leggings": 20,
  "shapescape_bewe:netherite_warm_boots": 15,
  // LEATHER COOLING
  "shapescape_bewe:leather_cooling_helmet": -8,
  "shapescape_bewe:leather_cooling_chestplate": -12,
  "shapescape_bewe:leather_cooling_leggings": -12,
  "shapescape_bewe:leather_cooling_boots": -8,
  // IRON COOLING
  "shapescape_bewe:iron_cooling_helmet": -8,
  "shapescape_bewe:iron_cooling_chestplate": -12,
  "shapescape_bewe:iron_cooling_leggings": -12,
  "shapescape_bewe:iron_cooling_boots": -8,
  // GOLD COOLING
  "shapescape_bewe:gold_cooling_helmet": -8,
  "shapescape_bewe:gold_cooling_chestplate": -12,
  "shapescape_bewe:gold_cooling_leggings": -12,
  "shapescape_bewe:gold_cooling_boots": -8,
  // DIAMOND COOLING
  "shapescape_bewe:diamond_cooling_helmet": -8,
  "shapescape_bewe:diamond_cooling_chestplate": -12,
  "shapescape_bewe:diamond_cooling_leggings": -12,
  "shapescape_bewe:diamond_cooling_boots": -8,
  // NETHERITE COOLING
  "shapescape_bewe:netherite_cooling_helmet": -8,
  "shapescape_bewe:netherite_cooling_chestplate": -12,
  "shapescape_bewe:netherite_cooling_leggings": -12,
  "shapescape_bewe:netherite_cooling_boots": -8,
  // LEATHER
  "minecraft:leather_helmet": 3,
  "minecraft:leather_chestplate": 5,
  "minecraft:leather_leggings": 5,
  "minecraft:leather_boots": 3,
  // IRON
  "minecraft:iron_helmet": 2,
  "minecraft:iron_chestplate": 2,
  "minecraft:iron_leggings": 2,
  "minecraft:iron_boots": 2,
  // CHAINMAIL
  "minecraft:chainmail_helmet": 1,
  "minecraft:chainmail_chestplate": 1,
  "minecraft:chainmail_leggings": 1,
  "minecraft:chainmail_boots": 1,
  // GOLD
  "minecraft:gold_helmet": 2,
  "minecraft:gold_chestplate": 2,
  "minecraft:gold_leggings": 2,
  "minecraft:gold_boots": 2,
  // DIAMOND
  "minecraft:diamond_helmet": 2,
  "minecraft:diamond_chestplate": 2,
  "minecraft:diamond_leggings": 2,
  "minecraft:diamond_boots": 2,
  // NETHERITE
  "minecraft:netherite_helmet": 2,
  "minecraft:netherite_chestplate": 2,
  "minecraft:netherite_leggings": 2,
  "minecraft:netherite_boots": 2,
  // OTHER
  "minecraft:turtle_helmet": 2,
  "minecraft:carved_pumpkin": 2,
  // CUSTOM ARMOR / UNASSIGNED
  custom_helmet: 2,
  custom_chestplate: 2,
  custom_leggings: 2,
  custom_boots: 2
};
function get_armor_temperature(player) {
  const equippable = player.getComponent("equippable");
  const helmet = equippable.getEquipment(EquipmentSlot5.Head);
  const chestplate = equippable.getEquipment(EquipmentSlot5.Chest);
  const leggings = equippable.getEquipment(EquipmentSlot5.Legs);
  const boots = equippable.getEquipment(EquipmentSlot5.Feet);
  let armor_temperature = 0;
  const armor = [helmet, chestplate, leggings, boots];
  for (const part of armor) {
    if (!part)
      continue;
    if (part.typeId in STATS) {
      armor_temperature += STATS[part.typeId];
    } else {
      switch (part) {
        case helmet:
          armor_temperature += STATS.custom_helmet;
          break;
        case chestplate:
          armor_temperature += STATS.custom_chestplate;
          break;
        case leggings:
          armor_temperature += STATS.custom_leggings;
          break;
        case boots:
          armor_temperature += STATS.custom_boots;
          break;
        default:
          break;
      }
    }
  }
  if (DEBUG17) {
    console.warn("Armor Temperature:", armor_temperature);
  }
  player.setDynamicProperty("shapescape_bewe:temperature.armor", armor_temperature);
}
system40.runInterval(() => {
  let players = world43.getPlayers();
  for (let player of players) {
    get_armor_temperature(player);
  }
}, REFRESH_RATE15);

// data/system_template_esbuild/subscripts/temperature_item.ts
import { system as system41, world as world44 } from "@minecraft/server";
var DEBUG18 = false;
var REFRESH_RATE16 = 1 * 20;
var STATS2 = {
  "minecraft:torch": 4,
  "minecraft:soul_torch": 4,
  "minecraft:redstone_torch": 2,
  "minecraft:lantern": 2,
  "minecraft:soul_lantern": 2,
  "minecraft:lava_bucket": 8,
  "minecraft:lit_pumpkin": 4,
  // COLD
  powder_snow_bucket: -8,
  "minecraft:ice": -5,
  "minecraft:blue_ice": -6,
  "minecraft:forested_ice": -7,
  "minecraft:packed_ice": -6,
  "minecraft:snow": -3,
  "minecraft:snow_layer": -2,
  "minecraft:powder_snow": -2,
  "minecraft:snowball": -3,
  "minecraft:water_bucket": -4
};
function get_item_temperature(player) {
  const equippable = player.getComponent("equippable");
  const mainhand_item = equippable.getEquipment("Mainhand");
  const offhand_item = equippable.getEquipment("Offhand");
  let item_temperature = 0;
  if (mainhand_item) {
    if (mainhand_item.typeId in STATS2) {
      item_temperature += STATS2[mainhand_item.typeId];
    }
  }
  if (offhand_item) {
    if (offhand_item.typeId in STATS2) {
      item_temperature += STATS2[offhand_item.typeId];
    }
  }
  if (DEBUG18) {
    console.warn("Item Temperature:", item_temperature);
  }
  player.setDynamicProperty("shapescape_bewe:temperature.item", item_temperature);
}
system41.runInterval(() => {
  let players = world44.getPlayers();
  for (let player of players) {
    get_item_temperature(player);
  }
}, REFRESH_RATE16);

// data/system_template_esbuild/subscripts/temperature_food.ts
import { system as system42, world as world45 } from "@minecraft/server";
var DEBUG19 = false;
var REFRESH_RATE17 = 2 * 20;
var DURATION = 120 * 20;
var STATS3 = {
  // hot
  "minecraft:cooked_beef": 5,
  "minecraft:cooked_chicken": 5,
  "minecraft:cooked_cod": 3,
  "minecraft:cooked_mutton": 5,
  "minecraft:cooked_porkchop": 5,
  "minecraft:cooked_rabbit": 5,
  "minecraft:cooked_salmon": 3,
  "shapescape_bewe:self_heating_cup_6": 6,
  "shapescape_bewe:self_heating_cup_5": 6,
  "shapescape_bewe:self_heating_cup_4": 6,
  "shapescape_bewe:self_heating_cup_3": 6,
  "shapescape_bewe:self_heating_cup_2": 6,
  "shapescape_bewe:self_heating_cup_1": 6,
  // cold
  "minecraft:potion": -6,
  "minecraft:milk_bucket": -5,
  "minecraft:melon_slice": -3,
  "minecraft:glistering_melon_slice": -5,
  "minecraft:glow_berries": -4,
  "minecraft:sweet_berries": -3,
  "minecraft:apple": -3,
  "minecraft:enchanted_golden_apple": -3,
  "minecraft:golden_apple": -3,
  "shapescape_bewe:insulated_flask_6": -6,
  "shapescape_bewe:insulated_flask_5": -6,
  "shapescape_bewe:insulated_flask_4": -6,
  "shapescape_bewe:insulated_flask_3": -6,
  "shapescape_bewe:insulated_flask_2": -6,
  "shapescape_bewe:insulated_flask_1": -6
};
world45.afterEvents.playerSpawn.subscribe((event) => {
  list_clear(event.player);
});
world45.afterEvents.itemCompleteUse.subscribe((event) => {
  const item = event.itemStack;
  const player = event.source;
  if (!item)
    return;
  if (item.typeId in STATS3) {
    list_add(player, item);
    system42.runTimeout(() => {
      list_remove(player, item);
    }, DURATION);
  }
});
function update_food_temperature(player) {
  const list = list_get(player);
  let temperature = 0;
  for (const item of list) {
    temperature += STATS3[item];
  }
  if (DEBUG19)
    console.warn("Food Temperature", temperature, JSON.stringify(list));
  player.setDynamicProperty("shapescape_bewe:temperature.food", temperature);
}
system42.runInterval(() => {
  let players = world45.getPlayers();
  for (let player of players) {
    update_food_temperature(player);
  }
}, REFRESH_RATE17);
function list_get(player) {
  let list = [];
  let property_list = player.getDynamicProperty("shapescape_bewe:temperature.food.list") ?? "[]";
  if (property_list)
    list = JSON.parse(property_list);
  return list;
}
function list_add(player, item) {
  let list = [];
  let property_list = player.getDynamicProperty("shapescape_bewe:temperature.food.list") ?? "[]";
  if (property_list)
    list = JSON.parse(property_list);
  list.push(item.typeId);
  player.setDynamicProperty("shapescape_bewe:temperature.food.list", JSON.stringify(list));
}
function list_remove(player, item) {
  let list = [];
  let property_list = player.getDynamicProperty("shapescape_bewe:temperature.food.list") ?? "[]";
  if (property_list)
    list = JSON.parse(property_list);
  list = list.filter((string) => string !== item.typeId);
  player.setDynamicProperty("shapescape_bewe:temperature.food.list", JSON.stringify(list));
}
function list_clear(player) {
  let list = [];
  player.setDynamicProperty("shapescape_bewe:temperature.food.list", JSON.stringify(list));
}

// data/system_template_esbuild/subscripts/item/self_heating_cup.ts
import {
  world as world46,
  Player as Player26,
  EntityComponentTypes as EntityComponentTypes11,
  EquipmentSlot as EquipmentSlot6,
  ItemStack as ItemStack5
} from "@minecraft/server";
var ID_FULL = "shapescape_bewe:self_heating_cup_6";
world46.afterEvents.itemUse.subscribe(({ source: player, itemStack }) => {
  if (player instanceof Player26) {
    const ITEM_TAGS = itemStack.getTags();
    if (!ITEM_TAGS.includes("shapescape_bewe:self_heating_cup"))
      return;
    if (itemStack.typeId === ID_FULL)
      return;
    let raycastHit = player.getBlockFromViewDirection({
      includeLiquidBlocks: true,
      maxDistance: 32
    });
    if (raycastHit) {
      let block = raycastHit.block;
      if (block.typeId !== "minecraft:water")
        return;
      let distance = getDistance(player.location, raycastHit.block.location);
      if (distance > 5)
        return;
      const inventory = player.getComponent(EntityComponentTypes11.Equippable);
      if (!inventory)
        return;
      let item = new ItemStack5(ID_FULL, 1);
      inventory.setEquipment(EquipmentSlot6.Mainhand, item);
      player.playSound("bucket.fill_water", { pitch: 1.6 });
    }
  }
});
world46.afterEvents.itemStartUseOn.subscribe(({ source: player, itemStack, block }) => {
  if (player instanceof Player26 && itemStack) {
    const ITEM_TAGS = itemStack.getTags();
    if (!ITEM_TAGS.includes("shapescape_bewe:self_heating_cup"))
      return;
    if (itemStack.typeId === ID_FULL)
      return;
    if (block.typeId === "minecraft:cauldron") {
      let liquid = block.permutation.getState("cauldron_liquid");
      let fill_level = block.permutation.getState("fill_level");
      if (liquid !== "water" || fill_level === 0)
        return;
    }
    const inventory = player.getComponent(EntityComponentTypes11.Equippable);
    if (!inventory)
      return;
    let item = new ItemStack5(ID_FULL, 1);
    inventory.setEquipment(EquipmentSlot6.Mainhand, item);
    player.playSound("bucket.fill_water", { pitch: 1.6 });
  }
});
function getDistance(vector1, vector2) {
  const dx = vector2.x - vector1.x;
  const dy = vector2.y - vector1.y;
  const dz = vector2.z - vector1.z;
  return Math.sqrt(dx * dx + dy * dy + dz * dz);
}

// data/system_template_esbuild/subscripts/item/insulated_flask.ts
import {
  world as world47,
  Player as Player27,
  EntityComponentTypes as EntityComponentTypes12,
  EquipmentSlot as EquipmentSlot7,
  ItemStack as ItemStack6
} from "@minecraft/server";
var ID_FULL2 = "shapescape_bewe:insulated_flask_6";
world47.afterEvents.itemUse.subscribe(({ source: player, itemStack }) => {
  if (player instanceof Player27) {
    const ITEM_TAGS = itemStack.getTags();
    if (!ITEM_TAGS.includes("shapescape_bewe:insulated_flask"))
      return;
    if (itemStack.typeId === ID_FULL2)
      return;
    let raycastHit = player.getBlockFromViewDirection({
      includeLiquidBlocks: true,
      maxDistance: 32
    });
    if (raycastHit) {
      let block = raycastHit.block;
      if (block.typeId !== "minecraft:water")
        return;
      let distance = getDistance2(player.location, raycastHit.block.location);
      if (distance > 5)
        return;
      const inventory = player.getComponent(EntityComponentTypes12.Equippable);
      if (!inventory)
        return;
      let item = new ItemStack6(ID_FULL2, 1);
      inventory.setEquipment(EquipmentSlot7.Mainhand, item);
      player.playSound("bucket.fill_water", { pitch: 1.6 });
    }
  }
});
world47.afterEvents.itemStartUseOn.subscribe((event) => {
  const { source: player, itemStack, block } = event;
  if (player instanceof Player27 && itemStack) {
    const ITEM_TAGS = itemStack.getTags();
    if (!ITEM_TAGS.includes("shapescape_bewe:insulated_flask"))
      return;
    if (itemStack.typeId === ID_FULL2)
      return;
    if (block.typeId === "minecraft:cauldron") {
      let liquid = block.permutation.getState("cauldron_liquid");
      let fill_level = block.permutation.getState("fill_level");
      if (liquid !== "water" || fill_level === 0)
        return;
    }
    const inventory = player.getComponent(EntityComponentTypes12.Equippable);
    if (!inventory)
      return;
    let item = new ItemStack6(ID_FULL2, 1);
    inventory.setEquipment(EquipmentSlot7.Mainhand, item);
    player.playSound("bucket.fill_water", { pitch: 1.6 });
  }
});
function getDistance2(vector1, vector2) {
  const dx = vector2.x - vector1.x;
  const dy = vector2.y - vector1.y;
  const dz = vector2.z - vector1.z;
  return Math.sqrt(dx * dx + dy * dy + dz * dz);
}

// data/system_template_esbuild/subscripts/block/heater.ts
import { system as system45, world as world48 } from "@minecraft/server";
system45.beforeEvents.startup.subscribe((event) => {
  event.blockComponentRegistry.registerCustomComponent("shapescape_bewe:heater", {
    onTick: (event2) => {
      const block = event2.block;
      const powered = is_powered(block);
      if (block.permutation.getState("shapescape_bewe:powered") === false) {
        if (powered) {
          event2.block.setPermutation(block.permutation.withState("shapescape_bewe:powered", true));
        }
      } else {
        if (!powered) {
          event2.block.setPermutation(block.permutation.withState("shapescape_bewe:powered", false));
        }
        const nearbyPlayers = block.dimension.getEntities({
          location: block.location,
          maxDistance: 16,
          type: "minecraft:player"
        });
        for (let player of nearbyPlayers) {
          if (player) {
            player.setDynamicProperty("shapescape_bewe:temperature.heaterBlock", 20);
          }
        }
        const nearbyThermometerBlocks = block.dimension.getEntities({
          location: block.location,
          maxDistance: 16,
          type: "shapescape_bewe:thermometer_block"
        });
        for (let thermometerBlock of nearbyThermometerBlocks) {
          if (thermometerBlock) {
            thermometerBlock.setDynamicProperty("shapescape_bewe:temperature.heaterBlock", 20);
          }
        }
      }
    }
  });
});
system45.runInterval(() => {
  let players = world48.getPlayers();
  for (let player of players) {
    const heaterBlock = player.getDynamicProperty("shapescape_bewe:temperature.heaterBlock") ?? 0;
    if (heaterBlock > 1) {
      let new_value = heaterBlock - 1;
      player.setDynamicProperty("shapescape_bewe:temperature.heaterBlock", new_value);
    }
  }
}, 1);
function is_powered(block) {
  let powered = false;
  let above = void 0;
  try {
    above = block.above(1);
  } catch {
  }
  let below = void 0;
  try {
    below = block.below(1);
  } catch {
  }
  let north = void 0;
  try {
    north = block.north(1);
  } catch {
  }
  let south = void 0;
  try {
    south = block.south(1);
  } catch {
  }
  let east = void 0;
  try {
    east = block.east(1);
  } catch {
  }
  let west = void 0;
  try {
    west = block.west(1);
  } catch {
  }
  const sides = [above, below, north, south, east, west];
  for (const side of sides) {
    const redstonePower = side?.getRedstonePower();
    if (side === void 0 || !redstonePower)
      continue;
    if (redstonePower > 0)
      powered = true;
  }
  return powered;
}

// data/system_template_esbuild/subscripts/block/cooler.ts
import { system as system46, world as world49 } from "@minecraft/server";
system46.beforeEvents.startup.subscribe((event) => {
  event.blockComponentRegistry.registerCustomComponent("shapescape_bewe:cooler", {
    onTick: (event2) => {
      const block = event2.block;
      const powered = is_powered2(block);
      if (block.permutation.getState("shapescape_bewe:powered") === false) {
        if (powered) {
          event2.block.setPermutation(block.permutation.withState("shapescape_bewe:powered", true));
        }
      } else {
        if (!powered) {
          event2.block.setPermutation(block.permutation.withState("shapescape_bewe:powered", false));
        }
        const nearbyPlayers = block.dimension.getEntities({
          location: block.location,
          maxDistance: 16,
          type: "minecraft:player"
        });
        for (let player of nearbyPlayers) {
          if (player) {
            player.setDynamicProperty("shapescape_bewe:temperature.coolerBlock", 20);
          }
        }
        const nearbyThermometerBlocks = block.dimension.getEntities({
          location: block.location,
          maxDistance: 16,
          type: "shapescape_bewe:thermometer_block"
        });
        for (let thermometerBlock of nearbyThermometerBlocks) {
          if (thermometerBlock) {
            thermometerBlock.setDynamicProperty("shapescape_bewe:temperature.coolerBlock", 20);
          }
        }
      }
    }
  });
});
system46.runInterval(() => {
  let players = world49.getPlayers();
  for (let player of players) {
    const coolerBlock = player.getDynamicProperty("shapescape_bewe:temperature.coolerBlock") ?? 0;
    if (coolerBlock > 1) {
      let new_value = coolerBlock - 1;
      player.setDynamicProperty("shapescape_bewe:temperature.coolerBlock", new_value);
    }
  }
}, 1);
function is_powered2(block) {
  let powered = false;
  let above = void 0;
  try {
    above = block.above(1);
  } catch {
  }
  let below = void 0;
  try {
    below = block.below(1);
  } catch {
  }
  let north = void 0;
  try {
    north = block.north(1);
  } catch {
  }
  let south = void 0;
  try {
    south = block.south(1);
  } catch {
  }
  let east = void 0;
  try {
    east = block.east(1);
  } catch {
  }
  let west = void 0;
  try {
    west = block.west(1);
  } catch {
  }
  const sides = [above, below, north, south, east, west];
  for (const side of sides) {
    const redstonePower = side?.getRedstonePower();
    if (side === void 0 || !redstonePower)
      continue;
    if (redstonePower > 0)
      powered = true;
  }
  return powered;
}

// data/system_template_esbuild/subscripts/block/thermometer_block.ts
import { system as system47, world as world50 } from "@minecraft/server";
var DEBUG20 = false;
world50.afterEvents.entitySpawn.subscribe((event) => {
  const entity = event.entity;
  if (entity.typeId === "shapescape_bewe:thermometer_block") {
    if (!entity.isValid)
      return;
    entity.runCommand("setblock ~ ~ ~ trapped_chest");
  }
});
system47.runInterval(() => {
  const entities = world50.getDimension("Overworld").getEntities({ families: ["shapescape_bewe_thermometer_block"] });
  for (let entity of entities) {
    let block = entity.dimension.getBlock(entity.location);
    const nearbyPlayers = entity.dimension.getPlayers({
      location: entity.location,
      maxDistance: 32
    });
    if (nearbyPlayers.length === 0)
      continue;
    if (!block || block.typeId !== "minecraft:trapped_chest") {
      if (!entity.isValid)
        continue;
      entity.runCommand(
        '/loot spawn ~~~ loot "shapescape/bewe/thermometer_block.loot"'
      );
      entity.remove();
      continue;
    }
    let block_below = block?.below(1);
    if (!block_below || block_below.typeId !== "minecraft:iron_block") {
      iron_block_warn(entity);
      continue;
    }
  }
}, 10);
function iron_block_warn(thermometer_block) {
  const nearest_players = thermometer_block.dimension.getPlayers({
    location: thermometer_block.location,
    closest: 1
  });
  if (!nearest_players)
    return;
  const nearest_player = nearest_players[0];
  if (!nearest_player)
    return;
  nearest_player.sendMessage({
    rawtext: [{ translate: `shapescape_bewe.temperature_block.missing_iron_block` }]
  });
  thermometer_block.runCommand(
    '/loot spawn ~~~ loot "shapescape/bewe/thermometer_block.loot"'
  );
  thermometer_block.runCommand(
    "/fill ~~~ ~~~ air [] replace minecraft:trapped_chest"
  );
  thermometer_block.remove();
}
system47.runInterval(() => {
  const entities = world50.getDimension("Overworld").getEntities({ families: ["shapescape_bewe_thermometer_block"] });
  for (let entity of entities) {
    let temperature = calculate_temperature(entity);
    let temperature_int = temperature_to_int(temperature);
    if (!entity)
      continue;
    entity.runCommand(`event entity @s temperature_${temperature_int}`);
    let old_temperature_int = entity.getDynamicProperty("shapescape_bewe:thermometer_block.temperature") ?? 0;
    if (temperature_int != old_temperature_int) {
      entity.setDynamicProperty(
        "shapescape_bewe:thermometer_block.temperature",
        temperature_int
      );
      update_redstone(entity, temperature_int);
    }
    if (DEBUG20)
      console.warn(entity.id, temperature, temperature_int);
  }
}, 100);
function temperature_to_int(temperature) {
  let celsius = calculateCelsius(temperature);
  if (celsius > 60)
    return 6;
  if (celsius > 40)
    return 5;
  if (celsius > 27)
    return 4;
  if (celsius >= 15)
    return 3;
  if (celsius < -18)
    return 0;
  if (celsius < -5)
    return 1;
  if (celsius < 15)
    return 2;
}
function calculate_temperature(thermometer_block) {
  const nearest_players = thermometer_block.dimension.getPlayers({
    location: thermometer_block.location,
    closest: 1
  });
  if (!nearest_players)
    return;
  const nearest_player = nearest_players[0];
  if (!nearest_player)
    return;
  let dimensionTemperature = 0;
  if (nearest_player.dimension.id === "minecraft:nether") {
    dimensionTemperature = 0.4;
  } else if (nearest_player.dimension.id === "minecraft:the_end") {
    dimensionTemperature = -1.1;
  }
  let biomeTemperature = nearest_player.getDynamicProperty(
    "shapescape_bewe:environment_detection.biome_temperature"
  ) ?? 0;
  biomeTemperature = biomeTemperature * 2 - 1;
  biomeTemperature = biomeTemperature * 0.85;
  if (biomeTemperature > 0.8) {
    biomeTemperature = 0.7;
  }
  let blocksTemperatureHeat = thermometer_block.getDynamicProperty(
    "shapescape_bewe:temperature.blocks.heat"
  ) ?? 0;
  let blocksTemperatureCold = thermometer_block.getDynamicProperty(
    "shapescape_bewe:temperature.blocks.cold"
  ) ?? 0;
  blocksTemperatureHeat = blocksTemperatureHeat * 0.01;
  blocksTemperatureCold = blocksTemperatureCold * 0.01;
  let blocksTemperature = 0;
  if (biomeTemperature > 0) {
    blocksTemperature = blocksTemperatureCold + blocksTemperatureHeat * 0.02;
  } else {
    blocksTemperature = blocksTemperatureHeat + blocksTemperatureCold * 0.02;
  }
  blocksTemperature = clamp2(blocksTemperature, -0.3, 0.3);
  const heaterBlock = thermometer_block.getDynamicProperty(
    "shapescape_bewe:temperature.heaterBlock"
  ) ?? 0;
  if (heaterBlock > 1) {
    blocksTemperature += 0.5;
  }
  const coolerBlock = thermometer_block.getDynamicProperty(
    "shapescape_bewe:temperature.coolerBlock"
  ) ?? 0;
  if (coolerBlock > 1) {
    blocksTemperature -= 0.5;
  }
  let shelterTemperature = thermometer_block.getDynamicProperty(
    "shapescape_bewe:temperature.shelter"
  ) ?? 0;
  if (shelterTemperature >= 3) {
    shelterTemperature = shelterTemperature * 0.03;
    if (biomeTemperature > 0.3) {
      shelterTemperature = -shelterTemperature;
    }
  } else
    shelterTemperature = 0;
  let timeOfDayTemperature = world50.getDynamicProperty(
    "shapescape_bewe:temperature.time_of_day"
  ) ?? 0;
  if (thermometer_block.dimension.id === "minecraft:overworld") {
    timeOfDayTemperature = timeOfDayTemperature * 0.01;
    timeOfDayTemperature = timeOfDayTemperature * 0.5;
    if (shelterTemperature > 0) {
      timeOfDayTemperature = timeOfDayTemperature * 0.3;
    }
  } else
    timeOfDayTemperature = 0;
  let isInWaterTemperature = 0;
  if (thermometer_block.isInWater) {
    if (biomeTemperature > 0) {
      isInWaterTemperature = -0.1;
    } else {
      isInWaterTemperature = -0.2;
    }
  }
  let altitudeTemperature = 0;
  let altitude = thermometer_block.location.y;
  if (altitude < 50)
    altitudeTemperature = 0.03;
  if (altitude < 40)
    altitudeTemperature = 0.06;
  if (altitude < 30)
    altitudeTemperature = 0.08;
  if (altitude < 15)
    altitudeTemperature = 0.1;
  if (altitude < -10)
    altitudeTemperature = 0.12;
  if (altitude < -20)
    altitudeTemperature = 0.14;
  if (altitude < -30)
    altitudeTemperature = 0.16;
  if (altitude < -40)
    altitudeTemperature = 0.19;
  if (altitude < -50)
    altitudeTemperature = 0.23;
  if (altitude > 60)
    altitudeTemperature = -0.01;
  if (altitude > 70)
    altitudeTemperature = -0.05;
  if (altitude > 80)
    altitudeTemperature = -0.08;
  if (altitude > 90)
    altitudeTemperature = -0.13;
  if (altitude > 100)
    altitudeTemperature = -0.17;
  if (altitude > 120)
    altitudeTemperature = -0.2;
  if (altitude > 135)
    altitudeTemperature = -0.22;
  if (altitude > 160)
    altitudeTemperature = -0.24;
  if (altitude > 185)
    altitudeTemperature = -0.26;
  if (altitude > 210)
    altitudeTemperature = -0.31;
  const WEATHER = world50.getDynamicProperty(
    "shapescape_bewe:environment_detection.weather"
  ) ?? "clear";
  let weatherTemperature = 0;
  if (thermometer_block.dimension.id === "minecraft:overworld") {
    if (biomeTemperature < 0) {
      if (WEATHER === "rain")
        weatherTemperature = -0.18;
      if (WEATHER === "thunderstorm")
        weatherTemperature = -0.3;
    }
    if (biomeTemperature >= 0) {
      if (WEATHER === "rain")
        weatherTemperature = -0.14;
      if (WEATHER === "thunderstorm")
        weatherTemperature = -0.24;
    }
    if (shelterTemperature > 0) {
      weatherTemperature = weatherTemperature * 0.3;
    }
  }
  let temperature = biomeTemperature + blocksTemperature + shelterTemperature + timeOfDayTemperature + weatherTemperature + altitudeTemperature + isInWaterTemperature + dimensionTemperature;
  return temperature;
}
function clamp2(value, min, max) {
  return Math.min(Math.max(value, min), max);
}
function update_redstone(entity, temperature) {
  if (!entity.isValid)
    return;
  const filled_slots = temperature * 2;
  for (let i = 0; i <= filled_slots; i++) {
    entity.runCommand(
      `replaceitem block ~ ~ ~ slot.container ${i} shapescape_bewe:wood_scrap`
    );
  }
  for (let i = filled_slots; i <= 29; i++) {
    entity.runCommand(`replaceitem block ~ ~ ~ slot.container ${i} air`);
  }
}
function calculateCelsius(tempPoints) {
  const keyPoints = [
    { tempPoint: -2, temperature: -100 },
    { tempPoint: -1.1, temperature: -20 },
    { tempPoint: -1, temperature: -14 },
    { tempPoint: -0.95, temperature: -12 },
    { tempPoint: -0.9, temperature: -8 },
    { tempPoint: -0.85, temperature: -4 },
    { tempPoint: -0.8, temperature: 4 },
    { tempPoint: -0.75, temperature: 10 },
    { tempPoint: -0.74, temperature: 10.2 },
    { tempPoint: -0.6, temperature: 12 },
    { tempPoint: -0.15, temperature: 14 },
    { tempPoint: 0.15, temperature: 16 },
    { tempPoint: 0.4, temperature: 20 },
    { tempPoint: 0.5, temperature: 23 },
    { tempPoint: 0.6, temperature: 25 },
    { tempPoint: 0.7, temperature: 30 },
    { tempPoint: 0.74, temperature: 39 },
    { tempPoint: 0.75, temperature: 40 },
    { tempPoint: 0.8, temperature: 43 },
    { tempPoint: 0.85, temperature: 46 },
    { tempPoint: 0.9, temperature: 50 },
    { tempPoint: 2, temperature: 100 }
  ];
  if (tempPoints <= keyPoints[0].tempPoint)
    return keyPoints[0].temperature;
  if (tempPoints >= keyPoints[keyPoints.length - 1].tempPoint)
    return keyPoints[keyPoints.length - 1].temperature;
  for (let i = 0; i < keyPoints.length - 1; i++) {
    const { tempPoint: t1, temperature: temp1 } = keyPoints[i];
    const { tempPoint: t2, temperature: temp2 } = keyPoints[i + 1];
    if (tempPoints >= t1 && tempPoints <= t2) {
      const ratio = (tempPoints - t1) / (t2 - t1);
      return temp1 + ratio * (temp2 - temp1);
    }
  }
  return keyPoints[0].temperature;
}

// data/system_template_esbuild/subscripts/thermometer.ts
import {
  system as system48,
  world as world51,
  ItemStack as ItemStack7,
  EquipmentSlot as EquipmentSlot8,
  EntityComponentTypes as EntityComponentTypes13
} from "@minecraft/server";
var ITEM_TAG = "shapescape_bewe:thermometer";
var TEMPERATURE_RANGES = [{ "identifier": "-3", "min": -1e3, "max": -18 }, { "identifier": "-2", "min": -18, "max": -5 }, { "identifier": "-1", "min": -5, "max": 15 }, { "identifier": "0", "min": 15, "max": 27 }, { "identifier": "1", "min": 27, "max": 40 }, { "identifier": "2", "min": 40, "max": 60 }, { "identifier": "3", "min": 60, "max": 1e3 }];
system48.runInterval(() => {
  let players = world51.getPlayers();
  for (let player of players) {
    const equippable = player.getComponent(EntityComponentTypes13.Equippable);
    const mainhand_item = equippable?.getEquipment(EquipmentSlot8.Mainhand);
    const offhand_item = equippable?.getEquipment(EquipmentSlot8.Offhand);
    if (!mainhand_item && !offhand_item)
      continue;
    if (!mainhand_item?.hasTag(ITEM_TAG) && !offhand_item?.hasTag(ITEM_TAG))
      continue;
    thermometer(player);
  }
}, 2);
function thermometer(player) {
  let surrounding_temperature = player.getDynamicProperty("shapescape_bewe:surrounding_temperature") ?? 0;
  let displayed_surrounding_temperature = toCelsius(
    player,
    surrounding_temperature,
    "displayed_surrounding_temperature"
  );
  let felt_temperature = player.getDynamicProperty("shapescape_bewe:temperature") ?? 0;
  let displayed_felt_temperature = toCelsius(player, felt_temperature, "displayed_felt_temperature");
  item_texture(player, displayed_felt_temperature);
  let unit = player.getDynamicProperty("shapescape_bewe:settings.options.degree_unit") ?? 0;
  if (!(player.getDynamicProperty(`shapescape_bewe:settings.options.actionbar`) ?? true))
    return;
  if ((player.getDynamicProperty(`shapescape_bewe:settings.options.thermometer_sneak`) ?? false) && !player.isSneaking)
    return;
  let message = "";
  if (unit === 0) {
    message = `\xA7r\xA7pWorld Temperature: \xA7${getTempColor(
      displayed_surrounding_temperature
    )}${celsiusToFahrenheit(displayed_surrounding_temperature).toFixed(1)}\xB0F`;
  } else {
    message = `\xA7r\xA7pWorld Temperature: \xA7${getTempColor(
      displayed_surrounding_temperature
    )}${displayed_surrounding_temperature.toFixed(1)}\xB0C`;
  }
  player.onScreenDisplay.setActionBar(message);
}
function item_texture(player, temp) {
  const equippable = player.getComponent("equippable");
  const mainhand_item = equippable?.getEquipment("Mainhand");
  const offhand_item = equippable?.getEquipment("Offhand");
  const newItem = new ItemStack7(`shapescape_bewe:thermometer_${getItem(player, temp)}`, 1);
  if (mainhand_item && mainhand_item?.hasTag(ITEM_TAG)) {
    const selectedSlot = equippable.getEquipmentSlot(EquipmentSlot8.Mainhand);
    if (selectedSlot === void 0)
      return;
    selectedSlot.setItem(newItem);
  }
  if (offhand_item && offhand_item?.hasTag(ITEM_TAG)) {
    const selectedSlot = equippable.getEquipmentSlot(EquipmentSlot8.Offhand);
    if (selectedSlot === void 0)
      return;
    selectedSlot.setItem(newItem);
  }
}
function getItem(player, temp) {
  let itemName = "";
  let temperatureRange = "";
  for (const temperature_range of TEMPERATURE_RANGES) {
    if (temp >= temperature_range.min && temp < temperature_range.max) {
      temperatureRange = temperature_range.identifier + "_";
    }
  }
  itemName = itemName + temperatureRange;
  const sneaking = player.getDynamicProperty("shapescape_bewe:settings.options.thermometer_sneak") ?? false;
  itemName = itemName + (sneaking ? "sneak_" : "");
  const muddyState = player.getDynamicProperty("muddy_state") ?? 0;
  const wetState = player.getDynamicProperty("wet_state") ?? 0;
  const brokenLegState = player.getDynamicProperty("break_leg") ?? false;
  const seaSick = player.getDynamicProperty("sea_sick") ?? 0;
  const altitudeSickness = player.getDynamicProperty("altitude_sickness") ?? false;
  if (muddyState && muddyState > 0.5) {
    itemName = itemName + "_muddy";
  }
  if (wetState && wetState > 0.5) {
    itemName = itemName + "_wet";
  }
  if (brokenLegState) {
    itemName = itemName + "_b_l";
  }
  if (seaSick >= 0.5) {
    itemName = itemName + "_sea_sick";
  }
  if (altitudeSickness) {
    itemName = itemName + "_a_s";
  }
  return itemName.replace("__", "_");
}
function getTempColor(temp) {
  if (temp > 45)
    return "m";
  if (temp > 40)
    return "4";
  if (temp > 32)
    return "c";
  if (temp > 27)
    return "n";
  if (temp > 23)
    return "2";
  if (temp < -10)
    return "1";
  if (temp < 0)
    return "t";
  if (temp < 10)
    return "3";
  if (temp < 15)
    return "b";
  return "q";
}
function toCelsius(player, value, property) {
  let displayed_temperature = player.getDynamicProperty(`shapescape_bewe:${property}`) ?? 0;
  const easeFactor = 0.1;
  const maxChange = 0.5;
  let celsius = calculateCelsius2(value);
  let difference = (celsius ?? 0) - displayed_temperature;
  let step = Math.min(Math.abs(difference) * easeFactor, maxChange);
  if (difference > 0) {
    displayed_temperature += step;
  } else {
    displayed_temperature -= step;
  }
  player.setDynamicProperty(`shapescape_bewe:${property}`, displayed_temperature);
  return displayed_temperature;
}
function celsiusToFahrenheit(celsius) {
  return celsius * 9 / 5 + 32;
}
function calculateCelsius2(tempPoints) {
  const keyPoints = [
    { tempPoint: -2, temperature: -100 },
    { tempPoint: -1.1, temperature: -20 },
    { tempPoint: -1, temperature: -14 },
    { tempPoint: -0.95, temperature: -12 },
    { tempPoint: -0.9, temperature: -8 },
    { tempPoint: -0.85, temperature: -4 },
    { tempPoint: -0.8, temperature: 4 },
    { tempPoint: -0.75, temperature: 10 },
    { tempPoint: -0.74, temperature: 10.2 },
    { tempPoint: -0.6, temperature: 12 },
    { tempPoint: -0.15, temperature: 14 },
    { tempPoint: 0.15, temperature: 16 },
    { tempPoint: 0.4, temperature: 20 },
    { tempPoint: 0.5, temperature: 23 },
    { tempPoint: 0.6, temperature: 25 },
    { tempPoint: 0.7, temperature: 30 },
    { tempPoint: 0.74, temperature: 39 },
    { tempPoint: 0.75, temperature: 40 },
    { tempPoint: 0.8, temperature: 43 },
    { tempPoint: 0.85, temperature: 46 },
    { tempPoint: 0.9, temperature: 50 },
    { tempPoint: 2, temperature: 100 }
  ];
  if (tempPoints <= keyPoints[0].tempPoint)
    return keyPoints[0].temperature;
  if (tempPoints >= keyPoints[keyPoints.length - 1].tempPoint)
    return keyPoints[keyPoints.length - 1].temperature;
  for (let i = 0; i < keyPoints.length - 1; i++) {
    const { tempPoint: t1, temperature: temp1 } = keyPoints[i];
    const { tempPoint: t2, temperature: temp2 } = keyPoints[i + 1];
    if (tempPoints >= t1 && tempPoints <= t2) {
      const ratio = (tempPoints - t1) / (t2 - t1);
      return temp1 + ratio * (temp2 - temp1);
    }
  }
}

// data/system_template_esbuild/subscripts/thunderstorm.ts
import {
  system as system49,
  world as world52,
  MolangVariableMap as MolangVariableMap19,
  BlockVolume as BlockVolume10,
  EntityComponentTypes as EntityComponentTypes14,
  EntityDamageCause as EntityDamageCause13,
  GameMode as GameMode11,
  WeatherType as WeatherType5,
  TicksPerSecond as TicksPerSecond10
} from "@minecraft/server";
var REFRESH_RATE18 = 1 * 73;
var CHANCE_PER_REFRESH_RATE = 0.5;
var STORM_DURATION = 90 * TicksPerSecond10;
var globalTornadoSpawn = false;
var lastTimeOfDay2 = 0;
system49.runInterval(() => {
  if (system49.currentTick % REFRESH_RATE18 !== 0 || Math.random() > CHANCE_PER_REFRESH_RATE)
    return;
  let players = world52.getPlayers();
  let alreadyProcessed = /* @__PURE__ */ new Set();
  const WEATHER = world52.getDynamicProperty("shapescape_bewe:environment_detection.weather") ?? "clear";
  const previousWeather = world52.getDynamicProperty("thunderstorm.previous_weather") ?? "clear";
  if (WEATHER !== "thunderstorm") {
    world52.setDynamicProperty("thunderstorm.previous_weather", WEATHER);
    return;
  }
  if (previousWeather !== WEATHER) {
    globalTornadoSpawn = Math.random() < 0.5 ? true : false;
    world52.setDynamicProperty("thunderstorm.previous_weather", WEATHER);
  }
  for (let player of players) {
    const allowedGamemode = player.getGameMode() !== GameMode11.Creative && player.getGameMode() !== GameMode11.Spectator;
    if (!allowedGamemode)
      continue;
    const dimension = player.dimension;
    const location = player.location;
    if (location.y < 40 || dimension.id !== "minecraft:overworld")
      continue;
    const biome = player.getDynamicProperty("shapescape_bewe:environment_detection.biome") ?? "";
    const biomeTagsProperty = player.getDynamicProperty("shapescape_bewe:environment_detection.biome_tags") ?? "[]";
    const biomeTags = JSON.parse(biomeTagsProperty);
    if (biome === "")
      continue;
    if (biomeTags.includes("desert") || biome === "desert" || biomeTags.includes("mesa") || biome === "mesa")
      continue;
    const BIOME_TEMPERATURE = player.getDynamicProperty("shapescape_bewe:environment_detection.biome_temperature") ?? 0.5;
    if (BIOME_TEMPERATURE < 0.15)
      continue;
    if (globalTornadoSpawn) {
      let spawnTornado = true;
      for (const tag of player.getTags()) {
        if (!tag.includes(`shapescape_bewe_TORNADO_`))
          continue;
        spawnTornado = false;
      }
      if (spawnTornado) {
        const tornado = dimension.spawnEntity("shapescape_bewe:tornado", player.location);
        player.setPropertyOverrideForEntity(tornado, "shapescape_bewe:visible", true);
        player.addTag(`shapescape_bewe_TORNADO_${tornado.id}`);
      }
    }
    if (alreadyProcessed.has(player))
      continue;
    const nearbyPlayers = dimension.getEntities({
      location,
      maxDistance: 32,
      type: "minecraft:player"
    });
    for (let otherPlayer of nearbyPlayers) {
      if (otherPlayer.nameTag !== player.nameTag) {
        alreadyProcessed.add(otherPlayer);
      }
    }
    if (Math.random() < 0.3) {
      distantEffect(player);
    } else {
      nearbyEffect(player);
    }
  }
}, 1);
function distantEffect(player, index) {
  if (index && index > 10)
    return;
  index = index === void 0 ? 0 : ++index;
  const dimension = player.dimension;
  const location = player.location;
  let xModified = 1;
  let zModified = 1;
  if (Math.random() < 0.5) {
    xModified = Math.random();
  } else {
    zModified = Math.random();
  }
  const xNegPos = Math.random() > 0.5 ? -1 : 1;
  const zNegPos = Math.random() > 0.5 ? -1 : 1;
  const offset = {
    x: xModified * xNegPos * 50 + xNegPos * Math.random() * 50,
    y: 0,
    z: zModified * zNegPos * 50 + zNegPos * Math.random() * 50
  };
  const particleLocation = {
    x: location.x + offset.x,
    // between 100 and 200 blocks away (negative or positive)
    y: 40,
    // Sea level, lowest it can get, so it makes sure lightning always touches the ground
    z: location.z + offset.z
    // between 100 and 200 blocks away (negative or positive)
  };
  try {
    const block = dimension.getBlock(particleLocation);
    if (block) {
      const nearbyPlayers = dimension.getEntities({
        location,
        maxDistance: 32,
        type: "minecraft:player"
      });
      if (nearbyPlayers.length > 0) {
        distantEffect(player, index);
        return;
      }
    }
  } catch {
  }
  const molangVarMap = new MolangVariableMap19();
  molangVarMap.setVector3("position", offset);
  dimension.spawnParticle("shapescape_bewe:lightning_bolt", { x: location.x, y: 40, z: location.z }, molangVarMap);
  const pitch = Math.random() * 0.2 + 0.9;
  dimension.playSound(`shapescape_bewe.thunderstorm.thunder_distant`, location, {
    volume: 5,
    pitch
  });
}
function nearbyEffect(player, index) {
  if (index && index > 10)
    return;
  index = index === void 0 ? 0 : ++index;
  const dimension = player.dimension;
  const location = player.location;
  const P1 = { x: location.x - 6, y: 200, z: location.z - 6 };
  const P2 = { x: location.x + 6, y: 200, z: location.z + 6 };
  const volume = new BlockVolume10(P1, P2);
  const locations = Array.from(volume.getBlockLocationIterator());
  const randomIndex = Math.floor(Math.random() * locations.length);
  const randomLocation = locations[randomIndex];
  let heightMap = 0;
  for (let index2 = 0; index2 < 200; index2++) {
    try {
      const blockToCheck = dimension.getBlock(randomLocation)?.below(index2);
      if (blockToCheck && !blockToCheck.isAir && !blockToCheck.typeId.includes("minecraft:light_block")) {
        if (!checkClearSpaceAbove(dimension, blockToCheck.location))
          break;
        heightMap = blockToCheck.location.y + 1;
        break;
      }
    } catch {
      continue;
    }
  }
  const strikeLocation = {
    x: randomLocation.x,
    y: heightMap,
    z: randomLocation.z
  };
  const entities = dimension.getEntities({
    location: strikeLocation,
    maxDistance: 3
  });
  for (const entity of entities) {
    const familyTypes = entity.getComponent(EntityComponentTypes14.TypeFamily)?.getTypeFamilies();
    if (!familyTypes || !entity.typeId.includes("minecraft:"))
      continue;
    else if (familyTypes.includes("pig") && familyTypes.includes("mob")) {
      entity.triggerEvent(`become_zombie`);
    } else if (familyTypes.includes("mushroomcow") && familyTypes.includes("mob")) {
      const variant = entity.getComponent(EntityComponentTypes14.Variant)?.value;
      if (variant === void 0)
        continue;
      if (variant === 0) {
        entity.triggerEvent(`minecraft:become_brown`);
      } else if (variant === 1) {
        entity.triggerEvent(`minecraft:become_red`);
      }
    } else if (familyTypes.includes("creeper") && familyTypes.includes("monster") && familyTypes.includes("mob")) {
      entity.triggerEvent(`minecraft:become_charged`);
    } else if (familyTypes.includes("villager") && familyTypes.includes("mob")) {
      entity.triggerEvent(`become_witch`);
    } else {
      entity.applyDamage(10, {
        cause: EntityDamageCause13.lightning
      });
    }
  }
  const molangVarMap = new MolangVariableMap19();
  molangVarMap.setVector3("position", { x: 0, y: 0, z: 0 });
  dimension.spawnParticle("shapescape_bewe:lightning_bolt", strikeLocation, molangVarMap);
  const pitch = Math.random() * 0.2 + 0.9;
  dimension.playSound(`shapescape_bewe.thunderstorm.thunder_nearby`, strikeLocation, {
    volume: 3,
    pitch
  });
}
function checkClearSpaceAbove(dimension, location, height = 40) {
  for (let y = 1; y <= height; y++) {
    try {
      const blockAbove = dimension.getBlock({
        x: location.x,
        y: location.y + y,
        z: location.z
      });
      if (blockAbove && !blockAbove.isAir && !blockAbove.typeId.includes("minecraft:light_block")) {
        return false;
      }
    } catch {
      return false;
    }
  }
  return true;
}
system49.afterEvents.scriptEventReceive.subscribe((event) => {
  const message = event.message;
  const messageID = event.id;
  const entity = event.sourceEntity;
  if (!entity?.isValid)
    return;
  if (entity && messageID === "shapescape_bewe:tornado" && message === "teleport") {
    const player = entity.dimension.getEntities({
      tags: [`shapescape_bewe_TORNADO_${entity.id}`]
    })[0];
    if (player && player.isValid) {
      entity.teleport(player.location);
    } else {
      const isChested = entity.getComponent(EntityComponentTypes14.IsChested);
      if (!isChested)
        entity.triggerEvent(`shapescape_bewe:start_despawn`);
    }
  }
  if (entity && messageID === "shapescape_bewe:tornado" && message === "despawn") {
    const players = entity.dimension.getEntities({
      tags: [`shapescape_bewe_TORNADO_${entity.id}`]
    });
    for (const player of players) {
      player.removeTag(`shapescape_bewe_TORNADO_${entity.id}`);
    }
  }
});
world52.afterEvents.playerSpawn.subscribe((event) => {
  const player = event.player;
  for (const tag of player.getTags()) {
    if (tag.includes("shapescape_bewe_TORNADO_")) {
      const tornadoID = tag.replace("shapescape_bewe_TORNADO_", "");
      const tornado = world52.getEntity(tornadoID);
      if (tornado && tornado.isValid) {
        tornado.teleport(player.location);
      } else {
        player.removeTag(tag);
      }
    }
  }
});
world52.afterEvents.worldLoad.subscribe(() => {
  if (world52.getDynamicProperty("thunderstorm.daily_storm_today") === void 0) {
    generateDailyStormVariables();
  }
});
system49.runInterval(() => {
  checkDailyStorm();
  const currentTime = world52.getTimeOfDay();
  if (lastTimeOfDay2 > currentTime) {
    generateDailyStormVariables();
  }
  lastTimeOfDay2 = currentTime;
}, 40 + Math.floor(Math.random() * 10));
function generateDailyStormVariables() {
  const stormsFrequency = world52.getDynamicProperty(`shapescape_bewe:settings.options.storms`) ?? 50;
  const dailyStormToday = Math.random() < stormsFrequency / 100;
  const dailyStormTimeTick = Math.floor(Math.random() * 12e3 + (Math.random() > 0.5 ? 0 : Math.random() * 12e3));
  world52.setDynamicProperty("thunderstorm.daily_storm_today", dailyStormToday);
  world52.setDynamicProperty("thunderstorm.daily_storm_time", dailyStormTimeTick);
}
function checkDailyStorm() {
  if (!world52.getDynamicProperty("thunderstorm.daily_storm_today") || !world52.getDimension("minecraft:overworld"))
    return;
  const currentTime = world52.getTimeOfDay();
  const timeDifference = Math.abs(currentTime - world52.getDynamicProperty("thunderstorm.daily_storm_time"));
  if (timeDifference < 100) {
    world52.setDynamicProperty("thunderstorm.daily_storm_today", false);
    triggerDailyStorm();
  }
}
function triggerDailyStorm() {
  world52.setDynamicProperty("thunderstorm.previous_weather", "thunderstorm");
  world52.getDimension("minecraft:overworld").runCommand(`weather thunder ${STORM_DURATION}`);
}
world52.beforeEvents.weatherChange.subscribe((event) => {
  if (event.newWeather === WeatherType5.Thunder) {
    const stormsFrequency = world52.getDynamicProperty(`shapescape_bewe:settings.options.storms`) ?? 50;
    if (stormsFrequency === 0)
      event.cancel = true;
  }
});

// data/system_template_esbuild/subscripts/tumbleweed.ts
import { system as system50, world as world53 } from "@minecraft/server";
world53.afterEvents.entitySpawn.subscribe((event) => {
  const entity = event.entity;
  if (entity && entity.typeId === "shapescape_bewe:tumbleweed") {
    if ((world53.getDynamicProperty("shapescape_bewe:settings.particles.tumbleweed") ?? true) === true)
      return;
    entity.remove();
  }
});
system50.runInterval(() => {
  if (system50.currentTick % 5 === 0) {
    const tumbleweeds = world53.getDimension("overworld").getEntities({ type: "shapescape_bewe:tumbleweed" });
    const WIND_DIRECTION = world53.getDynamicProperty("shapescape_bewe:wind_direction") ?? { x: 1, y: 0, z: 0 };
    const WEATHER = world53.getDynamicProperty("shapescape_bewe:environment_detection.weather") ?? "clear";
    const speedModifier = WEATHER === `thunderstorm` ? 2 : 1;
    for (let tumbleweed of tumbleweeds) {
      try {
        if (tumbleweed.isValid) {
          tumbleweed.applyImpulse({
            x: WIND_DIRECTION.x / 2.5 * speedModifier,
            y: WIND_DIRECTION.y,
            z: WIND_DIRECTION.z / 2.5 * speedModifier
          });
          if (Math.random() < 0.5) {
            const velocity = tumbleweed.getVelocity();
            const speed = Math.sqrt(velocity.x ** 2 + velocity.y ** 2 + velocity.z ** 2);
            if (speed < 0.01)
              tumbleweed.applyImpulse({ x: 0, y: 0.5, z: 0 });
          }
        }
      } catch {
        continue;
      }
    }
  }
}, 1);

// data/system_template_esbuild/subscripts/no_tool_dmg.ts
import { EntityDamageCause as EntityDamageCause14, system as system51, world as world54, GameMode as GameMode12 } from "@minecraft/server";
var blockTypes = [
  "minecraft:oak_log",
  "minecraft:stripped_oak_log",
  "minecraft:oak_wood",
  "minecraft:stripped_oak_wood",
  "minecraft:spruce_log",
  "minecraft:stripped_spruce_log",
  "minecraft:spruce_wood",
  "minecraft:stripped_spruce_wood",
  "minecraft:birch_log",
  "minecraft:stripped_birch_log",
  "minecraft:birch_wood",
  "minecraft:stripped_birch_wood",
  "minecraft:jungle_log",
  "minecraft:stripped_jungle_log",
  "minecraft:jungle_wood",
  "minecraft:stripped_jungle_wood",
  "minecraft:acacia_log",
  "minecraft:stripped_acacia_log",
  "minecraft:acacia_wood",
  "minecraft:stripped_acacia_wood",
  "minecraft:dark_oak_log",
  "minecraft:stripped_dark_oak_log",
  "minecraft:dark_oak_wood",
  "minecraft:stripped_dark_oak_wood",
  "minecraft:mangrove_log",
  "minecraft:stripped_mangrove_log",
  "minecraft:mangrove_wood",
  "minecraft:stripped_mangrove_wood",
  "minecraft:cherry_log",
  "minecraft:stripped_cherry_log",
  "minecraft:cherry_wood",
  "minecraft:stripped_cherry_wood",
  "minecraft:pale_oak_log",
  "minecraft:stripped_pale_oak_log",
  "minecraft:pale_oak_wood",
  "minecraft:stripped_pale_oak_wood",
  "minecraft:crimson_stem",
  "minecraft:crimson_hyphae",
  "minecraft:stripped_crimson_stem",
  "minecraft:stripped_crimson_hyphae",
  "minecraft:warped_stem",
  "minecraft:warped_hyphae",
  "minecraft:stripped_warped_stem",
  "minecraft:stripped_warped_hyphae",
  "minecraft:oak_planks",
  "minecraft:spruce_planks",
  "minecraft:birch_planks",
  "minecraft:jungle_planks",
  "minecraft:acacia_planks",
  "minecraft:dark_oak_planks",
  "minecraft:mangrove_planks",
  "minecraft:cherry_planks",
  "minecraft:pale_oak_planks",
  "minecraft:crimson_planks",
  "minecraft:warped_planks"
];
world54.beforeEvents.playerBreakBlock.subscribe((event) => {
  const { itemStack, player, block, dimension } = event;
  const allowedGamemode = player.getGameMode() !== GameMode12.Creative;
  if (!allowedGamemode)
    return;
  if (!blockTypes.includes(block.typeId) && !block.typeId.includes("wood") && !block.typeId.includes("log") && !block.typeId.includes("stem") && !block.typeId.includes("hyphae") && !block.typeId.includes("planks"))
    return;
  if (itemStack === void 0 || itemStack.typeId.includes("minecraft:") && !itemStack.typeId.includes("sword") && !itemStack.typeId.includes("axe") && !itemStack.typeId.includes("pickaxe") && !itemStack.typeId.includes("shovel") && !itemStack.typeId.includes("hoe")) {
    event.cancel = true;
    system51.run(() => {
      block.setType("minecraft:air");
      player.addEffect("minecraft:mining_fatigue", 600);
      player.applyDamage(3.1, {
        cause: EntityDamageCause14.none
      });
      player.playAnimation("animation.shapescape_bewe.player.hurt_hand", {
        blendOutTime: 0.2
      });
    });
  }
});

// data/system_template_esbuild/subscripts/bed_limitations.ts
import {
  EntityComponentTypes as EntityComponentTypes15,
  system as system52,
  world as world55
} from "@minecraft/server";
world55.beforeEvents.playerInteractWithBlock.subscribe((event) => {
  if (event.block.typeId === "minecraft:bed") {
    const player = event.player;
    if (world55.getTimeOfDay() < 13e3 || world55.getTimeOfDay() > 23e3) {
      event.cancel = true;
      player.sendMessage({
        rawtext: [{ translate: `shapescape_bewe.bed_limitations.night_sleep` }]
      });
      setPlayerSpawnPoint(player);
      return;
    }
    const WEATHER = world55.getDynamicProperty(
      "shapescape_bewe:environment_detection.weather"
    ) ?? "clear";
    if (WEATHER === "thunderstorm") {
      event.cancel = true;
      player.sendMessage({
        rawtext: [{ translate: `shapescape_bewe.bed_limitations.storm_sleep` }]
      });
      setPlayerSpawnPoint(player);
      return;
    }
    const temperature = player.getDynamicProperty("shapescape_bewe:temperature") ?? 0;
    if (temperature >= 0.715) {
      event.cancel = true;
      player.sendMessage({
        rawtext: [{ translate: `shapescape_bewe.bed_limitations.temperature_warm` }]
      });
      setPlayerSpawnPoint(player);
      return;
    } else if (temperature <= -0.75) {
      event.cancel = true;
      player.sendMessage({
        rawtext: [{ translate: `shapescape_bewe.bed_limitations.temperature_cold` }]
      });
      setPlayerSpawnPoint(player);
      return;
    }
    const health = player.getComponent(
      EntityComponentTypes15.Health
    );
    if (health.currentValue < 6) {
      event.cancel = true;
      player.sendMessage({
        rawtext: [{ translate: `shapescape_bewe.bed_limitations.health` }]
      });
      setPlayerSpawnPoint(player);
      return;
    }
  }
});
function setPlayerSpawnPoint(player) {
  const location = player.location;
  const dimension = player.dimension;
  player.sendMessage({
    rawtext: [{ translate: `shapescape_bewe.bed_limitations.spawnpoint` }]
  });
  const dimensionLocation = {
    dimension,
    x: location.x,
    y: location.y,
    z: location.z
  };
  system52.run(() => {
    player.setSpawnPoint(dimensionLocation);
    player.playSound(`note.bass`, {
      location: player.location
    });
  });
}

// data/system_template_esbuild/subscripts/wet_state.ts
import {
  BlockVolume as BlockVolume11,
  EntityComponentTypes as EntityComponentTypes16,
  MolangVariableMap as MolangVariableMap20,
  system as system53,
  TicksPerSecond as TicksPerSecond11,
  WeatherType as WeatherType6,
  world as world56
} from "@minecraft/server";
var DEBUG21 = false;
var DATA4 = { "getting_wet": { "in_rain": 20, "in_snowfall": 40, "in_water": 0 }, "getting_dry": { "temperate_biome": 60, "warm_biome": 5, "next_to_campfire": 15, "next_to_fire": 15, "next_to_lava": 5, "in_lava": 0, "on_fire": 0 }, "radius": 5, "effects_threshold": 0.5 };
var THRESHOLD3 = DATA4.effects_threshold;
var MAX_STATE3 = 1;
var INTERVAL5 = 1 * TicksPerSecond11;
var TAG5 = "shapescape_bewe_WET_STATE";
system53.runInterval(() => {
  const players = world56.getAllPlayers();
  for (const player of players) {
    checkWetState(player);
  }
}, INTERVAL5);
world56.afterEvents.playerSpawn.subscribe((event) => {
  if (event.initialSpawn === false) {
    updateWetState(event.player, 0, true);
  }
});
function checkWetState(player) {
  const setting = player.getDynamicProperty(`shapescape_bewe:settings.states.wet_state`) ?? true;
  if (!setting) {
    updateWetState(player, 0, true);
    return;
  }
  const biomeTemperature = player.getDynamicProperty("shapescape_bewe:environment_detection.biome_temperature") ?? 0.5 /* TEMPERATE */;
  const currentWeather = world56.getDynamicProperty("shapescape_bewe:environment_detection.weather") ?? "clear";
  const currentWetState = player.getDynamicProperty("wet_state") ?? 0;
  if (currentWetState > THRESHOLD3 * MAX_STATE3) {
    if (!player.hasTag(TAG5)) {
      player.sendMessage({ translate: `shapescape_bewe.wet_state.tip` });
      player.playSound(`note.bass`, { location: player.location });
      player.addTag(TAG5);
    }
    particlesWet(player);
  }
  if (player.isInWater) {
    updateWetState(player, DATA4.getting_wet.in_water);
    return;
  }
  if (currentWeather.toUpperCase() === WeatherType6.Rain.toUpperCase() && biomeTemperature > 0.15 /* COLD */ && !hasRoof3(player.location, player.dimension)) {
    updateWetState(player, DATA4.getting_wet.in_rain);
  }
  if (currentWeather.toUpperCase() === WeatherType6.Rain.toUpperCase() && biomeTemperature <= 0.15 /* COLD */ && !hasRoof3(player.location, player.dimension)) {
    updateWetState(player, DATA4.getting_wet.in_snowfall);
  }
  let block = void 0;
  try {
    block = player.dimension.getBlock(player.location);
  } catch {
  }
  if (block && block.typeId.includes("minecraft:") && block.typeId.includes("lava")) {
    updateWetState(player, DATA4.getting_dry.in_lava, true);
    return;
  }
  if (player.getComponent(EntityComponentTypes16.OnFire) !== void 0) {
    updateWetState(player, DATA4.getting_dry.on_fire, true);
    return;
  }
  if (biomeTemperature > 0.15 /* COLD */ && biomeTemperature < 1 /* WARM */) {
    updateWetState(player, DATA4.getting_dry.temperate_biome, true);
  }
  if (biomeTemperature >= 1 /* WARM */) {
    updateWetState(player, DATA4.getting_dry.warm_biome, true);
  }
  const P1 = {
    x: player.location.x - DATA4.radius / 2,
    y: player.location.y - DATA4.radius / 2,
    z: player.location.z - DATA4.radius / 2
  };
  const P2 = {
    x: player.location.x + DATA4.radius / 2,
    y: player.location.y + DATA4.radius / 2,
    z: player.location.z + DATA4.radius / 2
  };
  const volume = new BlockVolume11(P1, P2);
  const locations = volume.getBlockLocationIterator();
  for (const location of locations) {
    let block2 = void 0;
    try {
      block2 = player.dimension.getBlock(location);
    } catch {
    }
    if (block2?.typeId === "minecraft:soul_fire") {
      updateWetState(player, DATA4.getting_dry.next_to_fire, true);
      return;
    } else if (block2?.typeId === "minecraft:campfire") {
      updateWetState(player, DATA4.getting_dry.next_to_campfire, true);
      return;
    } else if (block2?.typeId === "minecraft:fire") {
      updateWetState(player, DATA4.getting_dry.next_to_fire, true);
      return;
    } else if (block2?.typeId === "minecraft:soul_campfire") {
      updateWetState(player, DATA4.getting_dry.next_to_campfire, true);
      return;
    } else if (block2?.typeId === "minecraft:lava") {
      updateWetState(player, DATA4.getting_dry.next_to_lava, true);
      return;
    }
  }
}
function updateWetState(player, time, drying = false) {
  const currentWetState = player.getDynamicProperty("wet_state") ?? 0;
  const step = MAX_STATE3 / (time === 0 ? 1 * (INTERVAL5 / TicksPerSecond11) : time) * (INTERVAL5 / TicksPerSecond11) * (drying ? -1 : 1);
  let newWetState = Number((currentWetState + step).toPrecision(5));
  if (newWetState >= MAX_STATE3) {
    newWetState = MAX_STATE3;
  } else if (newWetState <= 0) {
    newWetState = 0;
  }
  if (DEBUG21) {
    world56.sendMessage(`wet state: ` + JSON.stringify(newWetState));
  }
  player.setDynamicProperty("wet_state", newWetState);
}
function particlesWet(player) {
  const locator = player.location;
  const direction = player.getViewDirection();
  const velocity = player.getVelocity();
  const particleLocation = {
    x: locator.x + direction.x * 0.1 + velocity.x * 5,
    y: locator.y + 0.1 + direction.y * 0.1 + velocity.y * 5,
    z: locator.z + direction.z * 0.1 + velocity.z * 5
  };
  let speed = Math.sqrt(velocity.x ** 2 + velocity.y ** 2 + velocity.z ** 2);
  const molang = new MolangVariableMap20();
  molang.setFloat("variable.size_from_velocity", 1 + speed * 4);
  try {
    player.dimension.spawnParticle("shapescape_bewe:wet", particleLocation, molang);
  } catch {
  }
}
world56.beforeEvents.playerInteractWithBlock.subscribe((event) => {
  const { block, player, itemStack } = event;
  const blockAbove = block.above(1);
  if (blockAbove === void 0)
    return;
  const currentWeather = world56.getDynamicProperty("shapescape_bewe:environment_detection.weather");
  if (itemStack?.typeId === "minecraft:flint_and_steel" || itemStack?.typeId === "minecraft:fire_charge") {
    const currentWetState = player.getDynamicProperty("wet_state") ?? 0;
    if (currentWetState >= THRESHOLD3 * MAX_STATE3 || currentWeather.toUpperCase() === WeatherType6.Rain.toUpperCase() && !hasRoof3(blockAbove.location, block.dimension)) {
      system53.run(() => {
        player.playSound(`random.fizz`, {
          location: player.location,
          volume: 1,
          pitch: 2.15
        });
      });
      event.cancel = true;
    }
  }
});
function hasRoof3(location, dimension) {
  if (location.y < 40)
    return true;
  const P1 = {
    x: location.x,
    y: location.y + 1,
    z: location.z
  };
  const P2 = {
    x: location.x,
    y: location.y + 20,
    z: location.z
  };
  const volume = new BlockVolume11(P1, P2);
  const locations = volume.getBlockLocationIterator();
  for (const location2 of locations) {
    let block = void 0;
    try {
      block = dimension.getBlock(location2);
    } catch {
    }
    if (!block?.isAir && !block?.typeId.includes("light_block"))
      return true;
  }
  return false;
}

// data/system_template_esbuild/subscripts/wind_sock.ts
import { system as system54, world as world57 } from "@minecraft/server";
var DEBUG22 = false;
world57.afterEvents.entitySpawn.subscribe((event) => {
  const entity = event.entity;
  if (entity.typeId === "shapescape_bewe:wind_sock") {
    setWindSource(entity, world57.getDynamicProperty("shapescape_bewe:wind_source") ?? 2);
    const windDirection = world57.getDynamicProperty("shapescape_bewe:wind_direction") ?? { x: 1, y: 0, z: 0 };
    const windSpeedX = Math.abs(windDirection.x);
    const windSpeedZ = Math.abs(windDirection.z);
    const windSpeed = Math.round(Math.max(windSpeedX, windSpeedZ) * 100) / 100;
    setWindForce(entity, windSpeed);
  }
});
system54.runInterval(() => {
  const windDirection = world57.getDynamicProperty("shapescape_bewe:wind_direction") ?? { x: 1, y: 0, z: 0 };
  const windSpeedX = Math.abs(windDirection.x);
  const windSpeedZ = Math.abs(windDirection.z);
  const windSpeed = Math.round(Math.max(windSpeedX, windSpeedZ) * 100) / 100;
  const windSource = world57.getDynamicProperty("shapescape_bewe:wind_source") ?? 2;
  const entities = world57.getDimension("Overworld").getEntities({ families: ["shapescape_bewe_wind_sock"] });
  for (let entity of entities) {
    const windSpeedPrevious = entity.getDynamicProperty("shapescape_bewe:wind_sock.wind_speed_previous");
    const windSourcePrevious = entity.getDynamicProperty("shapescape_bewe:wind_sock.wind_source_previous");
    if (windSpeed !== windSpeedPrevious) {
      setWindForce(entity, windSpeed);
    }
    if (windSource !== windSourcePrevious) {
      setWindSource(entity, windSource);
    }
  }
}, 100);
function setWindForce(entity, windSpeed) {
  entity.setDynamicProperty("shapescape_bewe:wind_sock.wind_speed_previous", windSpeed);
  if (windSpeed < 0.21) {
    entity.runCommand("event entity @s wind_force_0");
  } else if (windSpeed < 0.42) {
    entity.runCommand("event entity @s wind_force_1");
  } else if (windSpeed < 0.63) {
    entity.runCommand("event entity @s wind_force_2");
  } else if (windSpeed < 0.84) {
    entity.runCommand("event entity @s wind_force_3");
  } else if (windSpeed >= 0.84) {
    entity.runCommand("event entity @s wind_force_4");
  }
}
function setWindSource(entity, windSource) {
  if (DEBUG22)
    console.warn("wind source: " + windSource);
  entity.setDynamicProperty("shapescape_bewe:wind_sock.wind_source_previous", windSource);
  if (windSource == 0) {
    entity.runCommand("event entity @s wind_direction_0");
  } else if (windSource == 1) {
    entity.runCommand("event entity @s wind_direction_1");
  } else if (windSource == 2) {
    entity.runCommand("event entity @s wind_direction_2");
  } else if (windSource == 3) {
    entity.runCommand("event entity @s wind_direction_3");
  }
}

// data/system_template_esbuild/subscripts/wind.ts
import {
  system as system55,
  world as world58,
  MolangVariableMap as MolangVariableMap21,
  Player as Player32,
  GameMode as GameMode13
} from "@minecraft/server";
var DEBUG23 = false;
var REFRESH_RATE_UPDATE2 = 1 * 20;
var DIMENSIONS = [
  "minecraft:overworld",
  "minecraft:nether",
  "minecraft:the_end"
];
var applyParticles = true;
var COOLDOWN_WIND_QUIET = "shapescape_bewe_wind_quiet_cooldown";
var COOLDOWN_WIND_LOUD = "shapescape_bewe_wind_loud_cooldown";
var cooldown_tags2 = [COOLDOWN_WIND_QUIET, COOLDOWN_WIND_LOUD];
function easeOutCirc2(x) {
  return Math.sqrt(1 - Math.pow(x - 1, 2));
}
function random_int2(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
world58.afterEvents.playerSpawn.subscribe((event) => {
  clear_cooldowns4(event.player);
});
function clear_cooldowns4(player) {
  for (let tag of cooldown_tags2) {
    player.removeTag(tag);
  }
}
system55.runInterval(() => {
  if (world58.getDynamicProperty(
    "shapescape_bewe:settings.weather.wind_system"
  ) ?? true) {
    const timeOfDay = world58.getTimeOfDay();
    if (timeOfDay >= 0 && timeOfDay <= 100) {
      setWindForce2();
      const windDirection = world58.getDynamicProperty(
        "shapescape_bewe:wind_system.wind_direction.set_in_morning"
      ) ?? { x: 1, y: 0, z: 0 };
      const windForceX = Math.abs(windDirection.x);
      const windForceZ = Math.abs(windDirection.z);
      const windForce = Math.max(windForceX, windForceZ);
      if (windForce > 0.5)
        world58.setDynamicProperty(
          "shapescape_bewe:wind_system.push_entities_this_day",
          true
        );
      else
        world58.setDynamicProperty(
          "shapescape_bewe:wind_system.push_entities_this_day",
          false
        );
    }
    setWindForceForRainInWindlessDay();
    updateWindForceDependingOnWeather();
  }
}, 100);
system55.runInterval(() => {
  if ((world58.getDynamicProperty(
    "shapescape_bewe:wind_system.push_entities_this_day"
  ) ?? false) && (world58.getDynamicProperty(
    "shapescape_bewe:environment_detection.weather"
  ) ?? "clear") === "clear" && (world58.getDynamicProperty(
    "shapescape_bewe:settings.weather.wind_system"
  ) ?? true)) {
    if (DEBUG23)
      console.warn("Try to push player");
    if (Math.random() > 0.4) {
      if (DEBUG23)
        console.warn("Push player");
      world58.setDynamicProperty("shapescape_bewe:wind_system.push_entities", true);
      let stopPushingEntities = system55.runTimeout(() => {
        world58.setDynamicProperty("shapescape_bewe:wind_system.push_entities", false);
        system55.clearRun(stopPushingEntities);
        if (DEBUG23)
          console.warn("Stop pushing player");
      }, 40 + 20 * Math.random() * 20);
    }
  }
}, 10 + 20 * Math.random() * 10 * 60);
function setWindForce2() {
  const windForce = { x: 0, y: 0, z: 0 };
  const mainForce = Math.random() + 0.01;
  const additionalForce = Math.random() * 0.4 - 0.2;
  const windSource = Math.floor(Math.random() * 4);
  world58.setDynamicProperty("shapescape_bewe:wind_source", windSource);
  switch (windSource) {
    case 0:
      windForce.x = additionalForce;
      windForce.y = 0;
      windForce.z = mainForce;
      if (DEBUG23)
        console.warn("Wind Source - north");
      break;
    case 1:
      windForce.x = additionalForce;
      windForce.y = 0;
      windForce.z = mainForce * -1;
      if (DEBUG23)
        console.warn("Wind Source - south");
      break;
    case 2:
      windForce.x = mainForce;
      windForce.y = 0;
      windForce.z = additionalForce;
      if (DEBUG23)
        console.warn("Wind Source - west");
      break;
    case 3:
      windForce.x = mainForce * -1;
      windForce.y = 0;
      windForce.z = additionalForce;
      if (DEBUG23)
        console.warn("Wind Source - east");
      break;
    default:
      break;
  }
  world58.setDynamicProperty(
    "shapescape_bewe:wind_system.wind_direction.set_in_morning",
    windForce
  );
}
function setWindForceForRainInWindlessDay() {
  const weather2 = world58.getDynamicProperty(
    "shapescape_bewe:environment_detection.weather"
  ) ?? "clear";
  const weatherStatus = world58.getDynamicProperty(
    "shapescape_bewe:wind_system.weather_previous_status"
  ) ?? "clear";
  if (weather2 === "clear" && weatherStatus !== "clear") {
    world58.setDynamicProperty(
      "shapescape_bewe:wind_system.weather_previous_status",
      "clear"
    );
    if (DEBUG23)
      console.warn("weather changed to clear");
    world58.setDynamicProperty("shapescape_bewe:wind_system.push_entities", false);
  } else if ((weather2 === "rain" || weather2 === "thunderstorm") && weatherStatus !== "notClear") {
    world58.setDynamicProperty(
      "shapescape_bewe:wind_system.weather_previous_status",
      "notClear"
    );
    world58.setDynamicProperty("shapescape_bewe:wind_system.push_entities", true);
    if (DEBUG23)
      console.warn("weather changed to rain");
  }
}
function updateWindForceDependingOnWeather() {
  const newTargetWindForce = world58.getDynamicProperty(
    "shapescape_bewe:wind_system.wind_direction.set_in_morning"
  ) ?? { x: 1, y: 0, z: 0 };
  const weather2 = world58.getDynamicProperty(
    "shapescape_bewe:environment_detection.weather"
  ) ?? "clear";
  if (weather2 === "rain") {
    newTargetWindForce.x *= 1.5 / 1 /* weatherRain */;
    newTargetWindForce.z *= 1.5 / 1 /* weatherRain */;
  } else if (weather2 === "thunderstorm") {
    newTargetWindForce.x *= 2 / 1 /* weatherThunder */;
    newTargetWindForce.z *= 2 / 1 /* weatherThunder */;
  }
  world58.setDynamicProperty(
    "shapescape_bewe:wind_system.wind_direction.target",
    newTargetWindForce
  );
}
system55.runInterval(() => {
  if (world58.getDynamicProperty(
    "shapescape_bewe:settings.weather.wind_system"
  ) ?? true) {
    const currentWindForce = world58.getDynamicProperty(
      "shapescape_bewe:wind_direction"
    ) ?? { x: 1, y: 0, z: 0 };
    const targetWindForce = world58.getDynamicProperty(
      "shapescape_bewe:wind_system.wind_direction.target"
    ) ?? {
      x: 1,
      y: 0,
      z: 0
    };
    if (currentWindForce != targetWindForce)
      easingWindForceChange(currentWindForce, targetWindForce);
  }
}, 20);
function easingWindForceChange(currentWindForce, targetWindForce) {
  const differenceX = Math.abs(targetWindForce.x - currentWindForce.x);
  const differenceZ = Math.abs(targetWindForce.z - currentWindForce.z);
  const interpolationFactorX = Math.min(1e-4 + differenceX * 1e-4, 0.05) * REFRESH_RATE_UPDATE2;
  const interpolationFactorZ = Math.min(1e-4 + differenceZ * 1e-4, 0.05) * REFRESH_RATE_UPDATE2;
  const easedWindForceX = easeOutCirc2(interpolationFactorX);
  const easedWindForceZ = easeOutCirc2(interpolationFactorZ);
  const newWindForce = {
    x: currentWindForce.x + (targetWindForce.x - currentWindForce.x) * easedWindForceX,
    y: 0,
    z: currentWindForce.z + (targetWindForce.z - currentWindForce.z) * easedWindForceZ
  };
  world58.setDynamicProperty("shapescape_bewe:wind_direction", newWindForce);
  if (DEBUG23) {
    const display_currentWindForceX = Math.round(newWindForce.x * 100) / 100;
    const display_targetWindForceX = Math.round(targetWindForce.x * 100) / 100;
    const display_currentWindForceZ = Math.round(newWindForce.z * 100) / 100;
    const display_targetWindForceZ = Math.round(targetWindForce.z * 100) / 100;
    const message = `\xA7bwindForce: \xA7f${display_currentWindForceX}, \xA7f${display_currentWindForceZ} \xA76| \xA7bTarget windForce: \xA7f${display_targetWindForceX}, \xA7f${display_targetWindForceZ}`;
    let players = world58.getPlayers();
    for (let player of players) {
      player.onScreenDisplay.setActionBar({ text: message });
    }
  }
}
system55.runInterval(() => {
  if (world58.getDynamicProperty(
    "shapescape_bewe:settings.weather.wind_system"
  ) ?? true) {
    const entities_player = [];
    const entities_mob = [];
    const entities_monster = [];
    for (const dimensionID of DIMENSIONS) {
      const dimension = world58.getDimension(dimensionID);
      entities_player.push(...dimension.getEntities({ families: ["player"] }));
      entities_mob.push(...dimension.getEntities({ families: ["mob"] }));
      entities_monster.push(
        ...dimension.getEntities({ families: ["monster"] })
      );
    }
    let entities = entities_player.concat(entities_mob).concat(entities_monster);
    const enderstorm = world58.getDynamicProperty("enderstorm") ?? false;
    const netherstorm = world58.getDynamicProperty("netherstorm") ?? false;
    for (let entity of entities) {
      const dimensionID = entity.dimension.id;
      const windDirection = calculatingWindForce(entity);
      if (dimensionID === "minecraft:overworld" && (Math.round(windDirection.x * 100) / 100 != 0 || Math.round(windDirection.z * 100) / 100 != 0) && (world58.getDynamicProperty(
        "shapescape_bewe:wind_system.push_entities"
      ) ?? false)) {
        if (entity instanceof Player32) {
          const allowedGamemode = entity.getGameMode() !== GameMode13.Creative && entity.getGameMode() !== GameMode13.Spectator;
          if (!allowedGamemode)
            continue;
        }
        if (entity instanceof Player32 && entity.isGliding)
          continue;
        applyWindImpulse(entity, windDirection);
        if (entity.typeId === "minecraft:player")
          windLoudSounds(entity);
      } else if (dimensionID === "minecraft:the_end" && enderstorm) {
        applyWindImpulse(entity, windDirection);
        if (entity.typeId === "minecraft:player")
          windLoudSounds(entity);
      } else if (dimensionID === "minecraft:nether" && netherstorm) {
        applyWindImpulse(entity, windDirection);
        if (entity.typeId === "minecraft:player")
          windLoudSounds(entity);
      }
    }
  }
}, 1);
system55.runInterval(() => {
  if (world58.getDynamicProperty(
    "shapescape_bewe:settings.weather.wind_system"
  ) ?? true) {
    let players = world58.getPlayers();
    for (let player of players) {
      try {
        if (applyParticles)
          windParticles(player);
        const weather2 = world58.getDynamicProperty(
          "shapescape_bewe:environment_detection.weather"
        ) ?? "clear";
        if (weather2 !== "clear") {
          system55.runTimeout(() => {
            if (applyParticles)
              windParticles(player);
          }, 40);
        }
      } catch {
        continue;
      }
    }
  }
}, 100 + Math.random() * 50);
system55.runInterval(() => {
  let players = world58.getPlayers();
  for (let player of players) {
    try {
      if (player.location.y > 50 && player.location.y < 200) {
        windQuietSounds(player);
      }
    } catch {
      continue;
    }
  }
}, 15 + Math.min(Math.random() * 50, 30));
function calculatingWindForce(entity) {
  let player;
  if (entity?.typeId === "minecraft:player")
    player = entity;
  const windDirection = world58.getDynamicProperty(
    "shapescape_bewe:wind_direction"
  ) ?? { x: 1, y: 0, z: 0 };
  if (player)
    windForceInfluenceSneaking();
  windForceInfluenceAir();
  windForceInfluenceArmor();
  windForceInfluenceWall();
  if (player)
    windForceInfluenceShelter();
  windForceInfluenceMovement();
  if (player)
    windForceInfluenceGamemode();
  function windForceInfluenceSneaking() {
    if (player.isSneaking) {
      windDirection.x *= 0.2 * 1 /* sneaking */;
      windDirection.z *= 0.2 * 1 /* sneaking */;
    }
  }
  function windForceInfluenceAir() {
    if (!entity.isOnGround) {
      windDirection.x *= 2 * 1 /* inAir */;
      windDirection.z *= 2 * 1 /* inAir */;
    }
  }
  function windForceInfluenceArmor() {
    let armorWeightMax = world58.getDynamicProperty("shapescape_bewe:max_armorWeight") ?? 100;
    armorWeightMax = armorWeightMax * 1 /* armorWeight */;
    let armorWeight = entity.getDynamicProperty("shapescape_bewe:armorWeight") ?? 0;
    armorWeight = armorWeight * 1 /* armorWeight */;
    let armorImpact = 1 - armorWeight / (armorWeightMax * 2 + 1);
    windDirection.x *= armorImpact;
    windDirection.z *= armorImpact;
  }
  function windForceInfluenceWall() {
    let wall = entity.getDynamicProperty("shapescape_bewe:detected_walls") ?? 0;
    if (wall > 0) {
      windDirection.x = 0;
      windDirection.z = 0;
    }
  }
  function windForceInfluenceShelter() {
    applyParticles = true;
    let shelterDetection = player.getDynamicProperty("shapescape_bewe:temperature.shelter") ?? 0;
    if (shelterDetection >= 4) {
      windDirection.x = 0;
      windDirection.z = 0;
      applyParticles = false;
    }
  }
  function windForceInfluenceMovement() {
    const windSource = world58.getDynamicProperty("shapescape_bewe:wind_source") ?? 2;
    const velocity = entity.getVelocity();
    switch (windSource) {
      case 0:
        if (velocity.z > 0)
          windDirection.z *= 5 * 1 /* movingDirection */;
        break;
      case 1:
        if (velocity.z < 0)
          windDirection.z *= 5 * 1 /* movingDirection */;
        break;
      case 2:
        if (velocity.x > 0)
          windDirection.x *= 5 * 1 /* movingDirection */;
        break;
      case 3:
        if (velocity.x < 0)
          windDirection.x *= 5 * 1 /* movingDirection */;
        break;
      default:
        break;
    }
  }
  function windForceInfluenceGamemode() {
    if (player.getGameMode() === "creative" || player.getGameMode() === "spectator") {
      windDirection.x = 0;
      windDirection.z = 0;
    }
  }
  return windDirection;
}
function applyWindImpulse(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 isMovingWithWind = (velocity, direction, threshold) => {
    return direction !== 0 && (direction > 0 && velocity > threshold || direction < 0 && velocity < threshold);
  };
  if (isMovingWithWind(previousVelocity.x, directionX, directionX / 40)) {
    return;
  }
  if (isMovingWithWind(previousVelocity.z, directionZ, directionZ / 40)) {
    return;
  }
  const verticalStrength = y + previousVelocity.y * 0.75;
  entity.applyKnockback(
    { x: directionX / 50, z: directionZ / 50 },
    verticalStrength
  );
}
function windParticles(player) {
  try {
    let location = player.location;
  } catch {
    return;
  }
  const windDirection = world58.getDynamicProperty(
    "shapescape_bewe:wind_direction"
  ) ?? { x: 1, y: 0, z: 0 };
  const windParticleForce = new MolangVariableMap21();
  const playerLocation = player.getHeadLocation();
  const windDirectionX = windDirection.x * 100 + (Math.random() - 0.5) * 2;
  const windDirectionY = (Math.random() - 0.5) * 2;
  const windDirectionZ = windDirection.z * 100 + (Math.random() - 0.5) * 2;
  const windSpeedX = Math.abs(windDirection.x);
  const windSpeedZ = Math.abs(windDirection.z);
  const windSpeed = Math.max(windSpeedX, windSpeedZ) * 7;
  windParticleForce.setSpeedAndDirection("variable.wind_direction", windSpeed, {
    x: windDirectionX,
    y: windDirectionY,
    z: windDirectionZ
  });
  try {
    player.dimension.spawnParticle(
      "shapescape_bewe:wind",
      playerLocation,
      windParticleForce
    );
  } catch {
  }
}
function windQuietSounds(player) {
  if ((player.getDynamicProperty("shapescape_bewe:settings.sounds.wind") ?? true) === false)
    return;
  if (!player.hasTag(COOLDOWN_WIND_QUIET)) {
    player.addTag(COOLDOWN_WIND_QUIET);
    let location = {
      x: player.location.x + (Math.random() < 0.5 ? -1 : 1) * random_int2(2, 4),
      y: player.location.y,
      z: player.location.z + (Math.random() < 0.5 ? -1 : 1) * random_int2(2, 4)
    };
    let volume = 4;
    let pitch = 1.05 - random_int2(1, 10) * 0.01;
    player.playSound("shapescape_bewe.wind_quiet", {
      location,
      volume,
      pitch
    });
    let COOLDOWN3 = random_int2(1, 2) + Math.random();
    system55.runTimeout(() => {
      if (!player.isValid)
        return;
      player.removeTag(COOLDOWN_WIND_QUIET);
    }, COOLDOWN3 * 20);
  }
}
function windLoudSounds(player) {
  if ((player.getDynamicProperty("shapescape_bewe:settings.sounds.wind") ?? true) === false)
    return;
  if (!player.hasTag(COOLDOWN_WIND_LOUD)) {
    player.addTag(COOLDOWN_WIND_LOUD);
    let location = {
      x: player.location.x + (Math.random() < 0.5 ? -1 : 1) * random_int2(2, 4),
      y: player.location.y,
      z: player.location.z + (Math.random() < 0.5 ? -1 : 1) * random_int2(2, 4)
    };
    let volume = 4;
    let pitch = 1.05 - random_int2(0, 5) * 0.01;
    player.playSound("shapescape_bewe.wind_loud", {
      location,
      volume,
      pitch
    });
    let COOLDOWN3 = random_int2(6, 9);
    system55.runTimeout(() => {
      if (!player.isValid)
        return;
      player.removeTag(COOLDOWN_WIND_LOUD);
    }, COOLDOWN3 * 20);
  }
}

// data/system_template_esbuild/subscripts/armor_weight.ts
import { system as system56, world as world59 } from "@minecraft/server";
var DEBUG24 = false;
var REFRESH_RATE19 = 1 * 20;
world59.afterEvents.worldLoad.subscribe(() => {
  world59.setDynamicProperty("shapescape_bewe:max_armor_weight", 19);
});
var STATS_ARMOR = {
  // LEATHER
  "minecraft:leather_helmet": 2,
  "minecraft:leather_chestplate": 4,
  "minecraft:leather_leggings": 3,
  "minecraft:leather_boots": 2,
  // IRON
  "minecraft:iron_helmet": 3,
  "minecraft:iron_chestplate": 5,
  "minecraft:iron_leggings": 4,
  "minecraft:iron_boots": 3,
  // CHAINMAIL
  "minecraft:chainmail_helmet": 2,
  "minecraft:chainmail_chestplate": 4,
  "minecraft:chainmail_leggings": 3,
  "minecraft:chainmail_boots": 2,
  // GOLD
  "minecraft:gold_helmet": 5,
  "minecraft:gold_chestplate": 7,
  "minecraft:gold_leggings": 6,
  "minecraft:gold_boots": 5,
  // DIAMOND
  "minecraft:diamond_helmet": 3,
  "minecraft:diamond_chestplate": 5,
  "minecraft:diamond_leggings": 4,
  "minecraft:diamond_boots": 3,
  // NETHERITE
  "minecraft:netherite_helmet": 4,
  "minecraft:netherite_chestplate": 6,
  "minecraft:netherite_leggings": 5,
  "minecraft:netherite_boots": 4,
  // OTHER
  "minecraft:turtle_helmet": 2,
  "minecraft:carved_pumpkin": 2,
  // CUSTOM ARMOR / UNASSIGNED
  custom_helmet: 2,
  custom_chestplate: 2,
  custom_leggings: 2,
  custom_boots: 2
};
function get_armor_weight(player) {
  const equippable = player.getComponent("equippable");
  const helmet = equippable.getEquipment("Head");
  const chestplate = equippable.getEquipment("Chest");
  const leggings = equippable.getEquipment("Legs");
  const boots = equippable.getEquipment("Feet");
  let armor_weight = 0;
  const armor = [helmet, chestplate, leggings, boots];
  for (const part of armor) {
    if (!part)
      continue;
    if (part.typeId in STATS_ARMOR) {
      armor_weight += STATS_ARMOR[part.typeId];
    } else {
      switch (part) {
        case helmet:
          armor_weight += STATS_ARMOR.custom_helmet;
          break;
        case chestplate:
          armor_weight += STATS_ARMOR.custom_chestplate;
          break;
        case leggings:
          armor_weight += STATS_ARMOR.custom_leggings;
          break;
        case boots:
          armor_weight += STATS_ARMOR.custom_boots;
          break;
        default:
          break;
      }
    }
  }
  if (DEBUG24) {
    console.warn("Armor weight:", armor_weight);
  }
  player.setDynamicProperty("shapescape_bewe:armor_weight", armor_weight);
}
system56.runInterval(() => {
  let players = world59.getPlayers();
  for (let player of players) {
    get_armor_weight(player);
  }
}, REFRESH_RATE19);

// data/system_template_esbuild/subscripts/wall_detection.ts
import { system as system57, world as world60 } from "@minecraft/server";
var DEBUG25 = false;
var REFRESH_RATE20 = 5;
var RADIUS2 = 3;
var PROCESSING_TAG3 = "shapescape_bewe_wall_detection_process";
system57.runInterval(() => {
  let players = world60.getPlayers();
  for (let player of players) {
    if (!player.hasTag(PROCESSING_TAG3)) {
      try {
        wallCheck(player);
      } catch {
        continue;
      }
    }
  }
}, REFRESH_RATE20);
world60.afterEvents.playerSpawn.subscribe((event) => {
  event.player.removeTag(PROCESSING_TAG3);
});
function getWallsInRadius2(player, radius) {
  return new Promise((resolve) => {
    const generator = function* () {
      const windSource = world60.getDynamicProperty("shapescape_bewe:wind_source") ?? 2;
      const location = {
        x: player.location.x,
        y: player.location.y + 1,
        z: player.location.z
      };
      let direction = { x: 0, y: 0, z: 0 };
      let walls = 0;
      switch (windSource) {
        case 0:
          direction.z = -1;
          break;
        case 1:
          direction.z = 1;
          break;
        case 2:
          direction.x = -1;
          break;
        case 3:
          direction.x = 1;
          break;
        default:
          break;
      }
      const block = player.dimension.getBlockFromRay(location, direction, {
        includeLiquidBlocks: true,
        includePassableBlocks: false,
        maxDistance: radius
      })?.block;
      if (block)
        walls += 1;
      yield;
      resolve(walls);
    };
    system57.runJob(generator());
  });
}
async function wallCheck(player) {
  player.addTag(PROCESSING_TAG3);
  const wall = await getWallsInRadius2(player, RADIUS2);
  if (DEBUG25)
    console.warn("wall:", wall);
  player.setDynamicProperty("shapescape_bewe:detected_walls", wall);
  player.removeTag(PROCESSING_TAG3);
}

// data/system_template_esbuild/subscripts/wind_turbine.ts
import { system as system58, world as world61 } from "@minecraft/server";
var DEBUG26 = false;
world61.afterEvents.entitySpawn.subscribe((event) => {
  const entity = event.entity;
  if (entity.typeId === "shapescape_bewe:wind_turbine" && entity.isValid) {
    entity.runCommand("setblock ~ ~ ~ trapped_chest");
    entity.setDynamicProperty("shapescape_bewe:wind_turbine.wind_speed_previous", 0);
  }
});
system58.runInterval(() => {
  const windDirection = world61.getDynamicProperty("shapescape_bewe:wind_direction") ?? {
    x: 1,
    y: 0,
    z: 0
  };
  const windSpeedX = Math.abs(windDirection.x);
  const windSpeedZ = Math.abs(windDirection.z);
  const windSpeed = Math.round(Math.max(windSpeedX, windSpeedZ) * 100) / 100;
  const entities = world61.getDimension("Overworld").getEntities({ families: ["shapescape_bewe_wind_turbine"] });
  for (let entity of entities) {
    if (!entity.isValid)
      continue;
    const windSpeedPrevious = entity.getDynamicProperty("shapescape_bewe:wind_turbine.wind_speed_previous");
    if (windSpeed !== windSpeedPrevious && entity.getDynamicProperty("shapescape_bewe:wind_turbine.block_check") == "is_iron_block") {
      entity.setDynamicProperty("shapescape_bewe:wind_turbine.wind_speed_previous", windSpeed);
      if (windSpeed < 0.07) {
        entity.runCommand("event entity @s wind_speed_0_07");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 0 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 1 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 2 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 3 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 4 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 5 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 6 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 7 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 8 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 9 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 10 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 11 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 12 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 13 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 14 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 15 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 16 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 17 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 18 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 19 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 20 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 21 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 22 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 23 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 24 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 25 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 26 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 27 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 28 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 29 air");
      } else if (windSpeed < 0.14) {
        entity.runCommand("event entity @s wind_speed_0_14");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 0 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 1 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 2 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 3 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 4 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 5 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 6 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 7 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 8 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 9 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 10 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 11 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 12 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 13 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 14 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 15 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 16 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 17 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 18 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 19 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 20 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 21 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 22 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 23 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 24 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 25 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 26 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 27 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 28 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 29 air");
      } else if (windSpeed < 0.21) {
        entity.runCommand("event entity @s wind_speed_0_21");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 0 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 1 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 2 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 3 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 4 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 5 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 6 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 7 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 8 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 9 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 10 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 11 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 12 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 13 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 14 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 15 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 16 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 17 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 18 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 19 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 20 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 21 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 22 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 23 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 24 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 25 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 26 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 27 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 28 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 29 air");
      } else if (windSpeed < 0.28) {
        entity.runCommand("event entity @s wind_speed_0_28");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 0 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 1 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 2 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 3 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 4 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 5 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 6 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 7 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 8 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 9 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 10 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 11 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 12 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 13 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 14 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 15 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 16 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 17 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 18 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 19 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 20 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 21 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 22 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 23 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 24 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 25 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 26 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 27 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 28 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 29 air");
      } else if (windSpeed < 0.35) {
        entity.runCommand("event entity @s wind_speed_0_35");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 0 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 1 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 2 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 3 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 4 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 5 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 6 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 7 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 8 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 9 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 10 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 11 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 12 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 13 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 14 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 15 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 16 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 17 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 18 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 19 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 20 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 21 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 22 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 23 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 24 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 25 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 26 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 27 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 28 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 29 air");
      } else if (windSpeed < 0.42) {
        entity.runCommand("event entity @s wind_speed_0_42");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 0 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 1 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 2 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 3 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 4 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 5 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 6 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 7 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 8 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 9 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 10 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 11 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 12 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 13 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 14 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 15 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 16 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 17 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 18 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 19 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 20 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 21 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 22 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 23 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 24 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 25 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 26 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 27 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 28 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 29 air");
      } else if (windSpeed < 0.49) {
        entity.runCommand("event entity @s wind_speed_0_49");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 0 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 1 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 2 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 3 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 4 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 5 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 6 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 7 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 8 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 9 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 10 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 11 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 12 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 13 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 14 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 15 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 16 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 17 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 18 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 19 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 20 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 21 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 22 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 23 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 24 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 25 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 26 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 27 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 28 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 29 air");
      } else if (windSpeed < 0.56) {
        entity.runCommand("event entity @s wind_speed_0_56");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 0 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 1 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 2 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 3 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 4 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 5 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 6 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 7 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 8 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 9 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 10 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 11 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 12 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 13 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 14 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 15 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 16 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 17 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 18 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 19 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 20 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 21 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 22 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 23 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 24 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 25 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 26 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 27 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 28 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 29 air");
      } else if (windSpeed < 0.63) {
        entity.runCommand("event entity @s wind_speed_0_63");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 0 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 1 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 2 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 3 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 4 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 5 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 6 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 7 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 8 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 9 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 10 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 11 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 12 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 13 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 14 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 15 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 16 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 17 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 18 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 19 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 20 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 21 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 22 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 23 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 24 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 25 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 26 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 27 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 28 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 29 air");
      } else if (windSpeed < 0.7) {
        entity.runCommand("event entity @s wind_speed_0_7");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 0 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 1 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 2 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 3 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 4 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 5 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 6 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 7 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 8 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 9 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 10 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 11 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 12 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 13 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 14 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 15 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 16 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 17 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 18 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 19 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 20 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 21 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 22 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 23 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 24 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 25 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 26 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 27 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 28 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 29 air");
      } else if (windSpeed < 0.77) {
        entity.runCommand("event entity @s wind_speed_0_77");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 0 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 1 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 2 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 3 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 4 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 5 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 6 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 7 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 8 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 9 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 10 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 11 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 12 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 13 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 14 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 15 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 16 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 17 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 18 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 19 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 20 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 21 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 22 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 23 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 24 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 25 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 26 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 27 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 28 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 29 air");
      } else if (windSpeed < 0.84) {
        entity.runCommand("event entity @s wind_speed_0_84");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 0 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 1 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 2 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 3 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 4 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 5 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 6 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 7 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 8 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 9 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 10 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 11 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 12 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 13 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 14 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 15 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 16 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 17 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 18 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 19 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 20 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 21 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 22 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 23 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 24 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 25 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 26 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 27 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 28 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 29 air");
      } else if (windSpeed < 0.91) {
        entity.runCommand("event entity @s wind_speed_0_91");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 0 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 1 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 2 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 3 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 4 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 5 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 6 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 7 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 8 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 9 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 10 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 11 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 12 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 13 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 14 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 15 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 16 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 17 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 18 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 19 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 20 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 21 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 22 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 23 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 24 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 25 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 26 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 27 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 28 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 29 air");
      } else if (windSpeed < 0.98) {
        entity.runCommand("event entity @s wind_speed_0_98");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 0 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 1 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 2 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 3 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 4 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 5 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 6 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 7 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 8 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 9 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 10 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 11 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 12 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 13 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 14 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 15 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 16 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 17 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 18 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 19 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 20 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 21 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 22 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 23 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 24 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 25 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 26 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 27 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 28 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 29 air");
      } else if (windSpeed < 1.05) {
        entity.runCommand("event entity @s wind_speed_1_05");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 0 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 1 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 2 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 3 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 4 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 5 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 6 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 7 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 8 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 9 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 10 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 11 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 12 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 13 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 14 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 15 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 16 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 17 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 18 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 19 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 20 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 21 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 22 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 23 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 24 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 25 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 26 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 27 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 28 air");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 29 air");
      } else if (windSpeed >= 1.05) {
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 0 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 1 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 2 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 3 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 4 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 5 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 6 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 7 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 8 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 9 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 10 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 11 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 12 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 13 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 14 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 15 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 16 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 17 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 18 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 19 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 20 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 21 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 22 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 23 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 24 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 25 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 26 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 27 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 28 shapescape_bewe:wood_scrap");
        entity.runCommand("replaceitem block ~ ~ ~ slot.container 29 shapescape_bewe:wood_scrap");
      }
      if (DEBUG26)
        console.warn("wind_turbine | Update signal");
    }
  }
}, 100);
system58.runInterval(() => {
  const entities = world61.getDimension("Overworld").getEntities({ families: ["shapescape_bewe_wind_turbine"] });
  for (let entity of entities) {
    let location = {
      x: entity.location.x,
      y: entity.location.y - 1,
      z: entity.location.z
    };
    const blockCheck = entity.getDynamicProperty("shapescape_bewe:wind_turbine.block_check");
    if (entity.dimension.getBlock(location)?.typeId !== "minecraft:iron_block" && blockCheck !== "not_iron_block") {
      entity.runCommand("setblock ~ ~ ~ trapped_chest");
      entity.setDynamicProperty("shapescape_bewe:wind_turbine.block_check", "not_iron_block");
      entity.addTag("shapescape_bewe_wind_turbine_without_iron_block");
    } else if (entity.dimension.getBlock(location)?.typeId === "minecraft:iron_block" && blockCheck !== "is_iron_block" && entity.isValid) {
      entity.setDynamicProperty("shapescape_bewe:wind_turbine.block_check", "is_iron_block");
      entity.setDynamicProperty("shapescape_bewe:wind_turbine.wind_speed_previous", 0);
      if (entity.hasTag("shapescape_bewe_wind_turbine_without_iron_block")) {
        entity.removeTag("shapescape_bewe_wind_turbine_without_iron_block");
      }
    }
    if (entity.hasTag("shapescape_bewe_wind_turbine_without_iron_block") && entity.isValid) {
      entity.removeTag("shapescape_bewe_wind_turbine_without_iron_block");
      iron_block_warn2(entity);
    }
  }
}, 10);
function iron_block_warn2(windTurbine) {
  const nearest_players = windTurbine.dimension.getPlayers({
    location: windTurbine.location,
    closest: 1
  });
  if (!nearest_players)
    return;
  const nearest_player = nearest_players[0];
  if (!nearest_player)
    return;
  nearest_player.sendMessage({
    rawtext: [{ translate: `shapescape_bewe.wind_turbine.missing_iron_block` }]
  });
  windTurbine.runCommand('/loot spawn ~~~ loot "shapescape/bewe/wind_turbine.loot"');
  windTurbine.runCommand("/fill ~~~ ~~~ air [] replace minecraft:trapped_chest");
  windTurbine.remove();
}
