Skip to content

Commit

Permalink
Make many rules async and separate slimeChunk & moonPhase
Browse files Browse the repository at this point in the history
  • Loading branch information
ForestOfLight committed Aug 18, 2024
1 parent 35bc304 commit 24c320f
Show file tree
Hide file tree
Showing 30 changed files with 108 additions and 92 deletions.
4 changes: 2 additions & 2 deletions Canopy [BP]/scripts/lib/canopy/Command.js
Original file line number Diff line number Diff line change
Expand Up @@ -143,10 +143,10 @@ class Command {
}

world.beforeEvents.chatSend.subscribe((ev) => {
const { message, sender } = ev;
const { sender, message } = ev;

let [name, ...args] = ArgumentParser.parseArgs(message);
if (!name.startsWith(Command.prefix))
if (!String(name).startsWith(Command.prefix))
return;
ev.cancel = true;
if (!commands[name])
Expand Down
8 changes: 8 additions & 0 deletions Canopy [BP]/scripts/lib/canopy/Rule.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,10 @@ class Rule {
}
}

getDependentRuleIDs() {
return Object.values(rules).filter(rule => rule.#contingentRules.includes(this.#identifier)).map(rule => rule.#identifier);
}

static exists(identifier) {
return rules[identifier] !== undefined;
}
Expand All @@ -98,6 +102,10 @@ class Rule {
return await Rule.getRule(identifier).getValue();
}

static getNativeValue(identifier) {
return Rule.getRule(identifier).parseString(world.getDynamicProperty(identifier));
}

static setValue(identifier, value) {
Rule.getRule(identifier).setValue(value);
}
Expand Down
2 changes: 1 addition & 1 deletion Canopy [BP]/scripts/src/classes/ProbeManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ class ProbeManager {

removeProbe(player) {
const probe = this.probeMap[player.id];
if (!probe) return console.warn(`[Probe Manager] Error while removing: No probe found for player ${player?.name}`);
if (!probe) return;
probe.detachFromPlayer();
if (probe.entity.isValid())
probe.entity.remove();
Expand Down
16 changes: 8 additions & 8 deletions Canopy [BP]/scripts/src/commands/camera.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,22 +70,22 @@ class BeforeSpectatorPlayer {
}
}

world.beforeEvents.playerGameModeChange.subscribe((ev) => {
const player = ev.player;
if (player.getDynamicProperty('isSpectating') && ev.fromGameMode === 'spectator' && ev.toGameMode !== 'spectator') {
world.beforeEvents.playerGameModeChange.subscribe((event) => {
const player = event.player;
if (player.getDynamicProperty('isSpectating') && event.fromGameMode === 'spectator' && event.toGameMode !== 'spectator') {
system.run(() => {
player.setGameMode(ev.fromGameMode);
player.setGameMode(event.fromGameMode);
player.onScreenDisplay.setActionBar('§cYou cannot change your gamemode while spectating.');
});
}
});

world.beforeEvents.playerLeave.subscribe((ev) => {
ev.player.setDynamicProperty('isViewingCamera', false);
world.beforeEvents.playerLeave.subscribe((event) => {
event.player.setDynamicProperty('isViewingCamera', false);
});

world.afterEvents.playerDimensionChange.subscribe((ev) => {
const player = ev.player;
world.afterEvents.playerDimensionChange.subscribe((event) => {
const player = event.player;
if (!player.getDynamicProperty('isViewingCamera')) return;
player.camera.clear();
player.setDynamicProperty('isViewingCamera', false);
Expand Down
12 changes: 7 additions & 5 deletions Canopy [BP]/scripts/src/commands/canopy.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,11 @@ async function canopyCommand(sender, args) {
if (ruleID === 'hopperCounters' && !enable)
resetCounterMap();

updateRules(sender, rule.getContigentRuleIDs(), enable);
updateRules(sender, rule.getIndependentRuleIDs(), !enable);
if (!enable)
await updateRules(sender, rule.getDependentRuleIDs(), enable);
else
await updateRules(sender, rule.getContigentRuleIDs(), enable);
await updateRules(sender, rule.getIndependentRuleIDs(), false);

updateRule(sender, ruleID, ruleValue, enable);
}
Expand All @@ -42,9 +45,8 @@ function updateRule(sender, ruleID, ruleValue, enable) {
sender.sendMessage(`§7${ruleID} is now ${enable ? '§l§aenabled' : '§l§cdisabled'}§r§7.`);
}

function updateRules(sender, ruleIDs, enable) {
async function updateRules(sender, ruleIDs, enable) {
for (const ruleID of ruleIDs) {
const rule = Rule.getRule(ruleID);
updateRule(sender, rule, enable);
updateRule(sender, ruleID, await Rule.getValue(ruleID), enable);
}
}
7 changes: 5 additions & 2 deletions Canopy [BP]/scripts/src/commands/info.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,10 @@ function infoCommand(sender, args) {
clearInfoDisplay(sender);

const rule = InfoDisplayRule.getRule(ruleID);
updateRules(sender, rule.getContigentRuleIDs(), enable);
if (!enable)
updateRules(sender, rule.getDependentRuleIDs(), enable);
else
updateRules(sender, rule.getContigentRuleIDs(), enable);
updateRules(sender, rule.getIndependentRuleIDs(), !enable);

updateRule(sender, ruleID, InfoDisplayRule.getValue(sender, ruleID), enable);
Expand All @@ -70,6 +73,6 @@ function updateRule(sender, ruleID, ruleValue, enable) {
function updateRules(sender, ruleIDs, enable) {
for (const ruleID of ruleIDs) {
const rule = InfoDisplayRule.getRule(ruleID);
updateRule(sender, rule, enable);
updateRule(sender, ruleID, InfoDisplayRule.getValue(sender, ruleID), enable);
}
}
4 changes: 2 additions & 2 deletions Canopy [BP]/scripts/src/commands/jump.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@ new Command({
helpHidden: true
})

function jumpCommand(sender) {
async function jumpCommand(sender) {
let blockRayResult;
let maxDistance = 64*16;
let jumpLocation;
if (!Rule.getValue('commandJumpSurvival') && sender.getGameMode() === 'survival')
if (!await Rule.getValue('commandJumpSurvival') && sender.getGameMode() === 'survival')
return sender.sendMessage('§cThe commandJumpSurvival feature is disabled.');

blockRayResult = Data.getLookingAtBlock(sender, maxDistance);
Expand Down
4 changes: 2 additions & 2 deletions Canopy [BP]/scripts/src/commands/scriptevents/counter.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ import { Rule } from 'lib/canopy/Canopy';
import { channelMap, formatColor, query, queryAll } from 'src/commands/counter';
import Utils from 'stickycore/utils';

system.afterEvents.scriptEventReceive.subscribe((event) => {
system.afterEvents.scriptEventReceive.subscribe(async (event) => {
if (event.id !== 'canopy:counter') return;
if (!Rule.getValue('hopperCounters')) return Utils.broadcastActionBar('§cThe hopperCounters feature is disabled.');
if (!await Rule.getValue('hopperCounters')) return Utils.broadcastActionBar('§cThe hopperCounters feature is disabled.');
const sourceName = Utils.getScriptEventSourceName(event);
const message = event.message;

Expand Down
8 changes: 4 additions & 4 deletions Canopy [BP]/scripts/src/commands/spawn.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,11 @@ let isMocking = false;
let currMobIds = [];
let currActiveArea = null;

world.afterEvents.entitySpawn.subscribe((event) => {
world.afterEvents.entitySpawn.subscribe(async (event) => {
const entity = event.entity;
if (worldSpawns && entity.typeId !== 'minecraft:item') worldSpawns.sendMobToTrackers(event.entity);

if (!isMocking || event.cause === 'Loaded' || !Rule.getValue('commandSpawnMocking')) return;
if (!isMocking || event.cause === 'Loaded' || !await Rule.getValue('commandSpawnMocking')) return;
let shouldCancelSpawn = false;
for (const category in categoryToMobMap) {
if (categoryToMobMap[category].includes(event.entity.typeId.replace('minecraft:', ''))) shouldCancelSpawn = true;
Expand Down Expand Up @@ -82,8 +82,8 @@ function printAllEntities(sender) {
});
}

function handleMockingCmd(sender, enable) {
if (!Rule.getValue('commandSpawnMocking')) return sender.sendMessage('§cThe commandSpawnMocking rule is disabled.');
async function handleMockingCmd(sender, enable) {
if (!await Rule.getValue('commandSpawnMocking')) return sender.sendMessage('§cThe commandSpawnMocking rule is disabled.');
if (enable === null) return sender.sendMessage('§cUsage: ./spawn mocking <true/false>');
isMocking = enable;
const messageColor = enable ? '§c' : '§a';
Expand Down
4 changes: 2 additions & 2 deletions Canopy [BP]/scripts/src/commands/tick.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ let targetMSPT = 50.0;
let shouldReset = false;
let shouldStep = 0;

system.beforeEvents.watchdogTerminate.subscribe((event) => {
if (!Rule.getValue('commandTick')) return;
system.beforeEvents.watchdogTerminate.subscribe(async (event) => {
if (!await Rule.getValue('commandTick')) return;
if (event.terminateReason === 'Hang' && targetMSPT > 50.0) {
console.warn(`[Watchdog] Terminate hang ignored.`);
event.cancel = true;
Expand Down
4 changes: 2 additions & 2 deletions Canopy [BP]/scripts/src/commands/tntfuse.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ const cmd = new Command({
contingentRules: ['commandTntFuse']
});

world.afterEvents.entitySpawn.subscribe(event => {
world.afterEvents.entitySpawn.subscribe(async (event) => {
if (event.entity.typeId !== 'minecraft:tnt') return;
const fuseTimeProperty = world.getDynamicProperty('tntFuseTime');
let fuseTime = 80;
if (fuseTimeProperty !== undefined && Rule.getValue('commandTntFuse'))
if (fuseTimeProperty !== undefined && await Rule.getValue('commandTntFuse'))
fuseTime = fuseTimeProperty;

if (fuseTime === 80) {
Expand Down
10 changes: 4 additions & 6 deletions Canopy [BP]/scripts/src/commands/warp.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,8 @@ class Warps {
}
}

function warpActionCommand(sender, args) {
if (!Rule.getValue('commandWarpSurvival') && ['survival', 'adventure'].includes(sender.getGameMode()))
async function warpActionCommand(sender, args) {
if (!await Rule.getValue('commandWarpSurvival') && ['survival', 'adventure'].includes(sender.getGameMode()))
return sender.sendMessage('§cThe commandWarpSurvival rule is disabled.');

let { action, name } = args;
Expand Down Expand Up @@ -139,10 +139,8 @@ function setWarpMap(newWarpMap) {
world.setDynamicProperty(`warps`, JSON.stringify(warps));
}

function warpListCommand(sender) {
if (!Rule.getValue('commandWarp'))
return sender.sendMessage('§cThe commandWarp rule is disabled.');
else if (!Rule.getValue('commandWarpSurvival') && sender.getGameMode() === 'survival')
async function warpListCommand(sender) {
if (!await Rule.getValue('commandWarpSurvival') && sender.getGameMode() === 'survival')
return sender.sendMessage('§cThe commandWarpSurvival rule is disabled.');

let warpMap = getWarpMapCopy();
Expand Down
13 changes: 11 additions & 2 deletions Canopy [BP]/scripts/src/rules/InfoDisplay.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ function InfoDisplay(player) {
function parseCoordsAndFacing(player) {
const showCoords = InfoDisplayRule.getValue(player, 'coords');
const showFacing = InfoDisplayRule.getValue(player, 'facing');
if (!showCoords && !showFacing) return '';
let coords = player.location;
let facing;
let output = '';
Expand All @@ -131,6 +132,7 @@ function parseCoordsAndFacing(player) {
function parseTPSAndEntities(player) {
const showTPS = InfoDisplayRule.getValue(player, 'tps');
const showEntities = InfoDisplayRule.getValue(player, 'entities');
if (!showTPS && !showEntities) return '';
let tpsData;
let tps;
let fovEntities;
Expand All @@ -151,6 +153,7 @@ function parseTPSAndEntities(player) {
function parseLightAndBiome(player) {
const showLight = InfoDisplayRule.getValue(player, 'light');
const showBiome = InfoDisplayRule.getValue(player, 'biome');
if (!showLight && !showBiome) return '';
let lightLevel;
let biome;
let output = '';
Expand All @@ -167,6 +170,7 @@ function parseLightAndBiome(player) {
function parseDayAndTime(player) {
const showDay = InfoDisplayRule.getValue(player, 'worldDay');
const showTimeOfDay = InfoDisplayRule.getValue(player, 'timeOfDay');
if (!showDay && !showTimeOfDay) return '';
let day;
let dayTime;
let output = '';
Expand Down Expand Up @@ -196,13 +200,17 @@ function parseSessionTime(player) {
function parseMoonPhaseAndSlimeChunk(player) {
const showMoonPhase = InfoDisplayRule.getValue(player, 'moonPhase');
const showSlimeChunk = InfoDisplayRule.getValue(player, 'slimeChunk');
const isSlime = player.dimension.id === "minecraft:overworld" && Data.isSlime(player.location.x, player.location.z);
if (!showMoonPhase && !showSlimeChunk) return '';
let isSlime = false;
let moonPhase;
let slimeChunk;
let output = '';

if (showMoonPhase) moonPhase = Data.getMoonPhase();
if (showSlimeChunk) slimeChunk = isSlime ? '§7(§aSlime Chunk§7)§r' : '';
if (showSlimeChunk) {
isSlime = player.dimension.id === "minecraft:overworld" && Data.isSlime(player.location.x, player.location.z);
slimeChunk = isSlime ? '§7(§aSlime Chunk§7)§r' : '';
}
if (showMoonPhase && showSlimeChunk) output += `§rMoon: §7${moonPhase}§r ${slimeChunk}\n`;
else if (showMoonPhase) output += `§rMoon: §7${moonPhase}§r\n`;
else if (showSlimeChunk && isSlime) output += `§r${slimeChunk}\n`;
Expand All @@ -225,6 +233,7 @@ function parseHopperCounters(player) {
function parseLookingAtAndPeek(player) {
const showLookingAt = InfoDisplayRule.getValue(player, 'lookingAt');
const showPeekInventory = InfoDisplayRule.getValue(player, 'peekInventory');
// if (!showLookingAt && !showPeekInventory) return '';
let blockRayResult;
let entityRayResult;
let lookingAtName;
Expand Down
4 changes: 2 additions & 2 deletions Canopy [BP]/scripts/src/rules/armorStandRespawning.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ new Rule({
description: 'Armor stands respawn when hit by a projectile, dropping their items.',
});

world.afterEvents.projectileHitEntity.subscribe((event) => {
if (!Rule.getValue('armorStandRespawning') || event.projectile.typeId === "minecraft:fishing_hook") return;
world.afterEvents.projectileHitEntity.subscribe(async (event) => {
if (!await Rule.getValue('armorStandRespawning') || event.projectile.typeId === "minecraft:fishing_hook") return;
const entity = event.getEntityHit().entity;
if (entity?.typeId === "minecraft:armor_stand") {
const hasCleanedItem = cleanDroppedItem(event);
Expand Down
8 changes: 4 additions & 4 deletions Canopy [BP]/scripts/src/rules/autoItemPickup.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@ system.runInterval(() => {
brokenBlockEventsThisTick = [];
});

world.afterEvents.playerBreakBlock.subscribe(blockEvent => {
if (!Rule.getValue('autoItemPickup')) return;
world.afterEvents.playerBreakBlock.subscribe(async (blockEvent) => {
if (!await Rule.getValue('autoItemPickup')) return;
if (blockEvent.player.getGameMode() === 'creative') return;
brokenBlockEventsThisTick.push(blockEvent);
});

world.afterEvents.entitySpawn.subscribe(entityEvent => {
world.afterEvents.entitySpawn.subscribe(async (entityEvent) => {
if (entityEvent.cause !== 'Spawned' || entityEvent.entity.typeId !== 'minecraft:item') return;
if (!Rule.getValue('autoItemPickup')) return;
if (!await Rule.getValue('autoItemPickup')) return;

const item = entityEvent.entity;
let brokenBlockEvent;
Expand Down
4 changes: 2 additions & 2 deletions Canopy [BP]/scripts/src/rules/dupeTnt.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ system.runInterval(() => {
}, 1);

world.afterEvents.entitySpawn.subscribe((event) => {
if (event.entity.typeId !== 'minecraft:tnt' || !Rule.getValue('dupeTnt')) return;
if (event.entity.typeId !== 'minecraft:tnt' || !Rule.getNativeValue('dupeTnt')) return;
const entity = event.entity;
spawnedEntitiesThisTick.push(entity);
});

world.afterEvents.pistonActivate.subscribe((event) => {
if (!Rule.getValue('dupeTnt')) return;
if (!Rule.getNativeValue('dupeTnt')) return;
const block = event.block;
const direction = block.permutation.getState('facing_direction');
let pistonState;
Expand Down
2 changes: 1 addition & 1 deletion Canopy [BP]/scripts/src/rules/entityInstantDeath.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ new Rule({
});

world.afterEvents.entityDie.subscribe(async (event) => {
if (!await Rule.getValue('entityInstantDeath')) return;
if (!await Rule.getNativeValue('entityInstantDeath')) return;
try {
event.deadEntity.remove();
} catch {} // already dead
Expand Down
4 changes: 2 additions & 2 deletions Canopy [BP]/scripts/src/rules/explosionChainReactionOnly.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ new Rule({
category: 'Rules',
identifier: 'explosionChainReactionOnly',
description: 'Makes explosion only affect TNT blocks.',
independentRules: ['explosionNoBlockDamage']
independentRules: ['explosionNoBlockDamage', 'explosionOff']
});

world.beforeEvents.explosion.subscribe((event) => {
if (!Rule.getValue('explosionChainReactionOnly')) return;
if (!Rule.getNativeValue('explosionChainReactionOnly')) return;
const explodedTntBlocks = event.getImpactedBlocks().filter(block => block.typeId === 'minecraft:tnt');
event.setImpactedBlocks(explodedTntBlocks);
});
8 changes: 4 additions & 4 deletions Canopy [BP]/scripts/src/rules/explosionNoBlockDamage.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ new Rule({
category: 'Rules',
identifier: 'explosionNoBlockDamage',
description: 'Makes explosions not affect blocks.',
independantRules: ['explosionChainReactionOnly']
independentRules: ['explosionChainReactionOnly', 'explosionOff']
});

world.beforeEvents.explosion.subscribe(ev => {
if (!Rule.getValue('explosionNoBlockDamage')) return;
ev.setImpactedBlocks([]);
world.beforeEvents.explosion.subscribe((event) => {
if (!Rule.getNativeValue('explosionNoBlockDamage')) return;
event.setImpactedBlocks([]);
});
3 changes: 2 additions & 1 deletion Canopy [BP]/scripts/src/rules/explosionOff.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@ new Rule({
category: 'Rules',
identifier: 'explosionOff',
description: 'Disables explosions entirely.',
independentRules: ['explosionChainReactionOnly', 'explosionNoBlockDamage']
});

world.beforeEvents.explosion.subscribe((event) => {
if (!Rule.getValue('explosionOff')) return;
if (!Rule.getNativeValue('explosionOff')) return;
event.cancel = true;
});
Loading

0 comments on commit 24c320f

Please sign in to comment.