Skip to content

Commit

Permalink
add player & entity validity checks
Browse files Browse the repository at this point in the history
  • Loading branch information
ForestOfLight committed Aug 19, 2024
1 parent 24c320f commit 40867f6
Show file tree
Hide file tree
Showing 18 changed files with 39 additions and 24 deletions.
8 changes: 7 additions & 1 deletion Canopy [BP]/scripts/lib/canopy/Canopy.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,11 @@ import { RuleHelpEntry, CommandHelpEntry, InfoDisplayRuleHelpEntry } from './hel
import { RuleHelpPage, CommandHelpPage, InfoDisplayRuleHelpPage } from './help/HelpPage';
import HelpBook from './help/HelpBook';

function getLoadedExtensions() {
const ruleExtensions = Rule.getExtensionNames();
const commandExtensions = Command.getExtensionNames();
return [...new Set([...ruleExtensions, ...commandExtensions])];
}

export { Command, Rule, InfoDisplayRule, RuleHelpEntry, CommandHelpEntry, InfoDisplayRuleHelpEntry,
RuleHelpPage, CommandHelpPage, InfoDisplayRuleHelpPage, HelpBook };
RuleHelpPage, CommandHelpPage, InfoDisplayRuleHelpPage, HelpBook, getLoadedExtensions };
10 changes: 5 additions & 5 deletions Canopy [BP]/scripts/lib/canopy/Command.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,17 +106,17 @@ class Command {
result.sort((a, b) => a.getName().localeCompare(b.getName()));
return result;
}

static getExtensionNames() {
return Object.values(commands).map(cmd => cmd.getExtensionName()).filter(name => name);
}


static getCommandsByExtension(extensionName) {
let result = Object.values(commands).filter(cmd => cmd.getExtensionName() === extensionName);
result.sort((a, b) => a.getName().localeCompare(b.getName()));
return result;
}

static getExtensionNames() {
return Object.values(commands).map(cmd => cmd.getExtensionName()).filter(name => name);
}

static checkArg(value, type) {
let data;
if (type == 'array' && Array.isArray(value)) data = value;
Expand Down
2 changes: 1 addition & 1 deletion Canopy [BP]/scripts/lib/canopy/registry/CommandRegistry.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@ system.afterEvents.scriptEventReceive.subscribe((event) => {
}
if (!cmdData) return;
new Command(cmdData);
console.warn(`[Canopy] Registered command: ${cmdData.extensionName}:${cmdData.name}`);
// console.warn(`[Canopy] Registered command: ${cmdData.extensionName}:${cmdData.name}`);
}, { namespaces: ['canopyExtension']});
2 changes: 1 addition & 1 deletion Canopy [BP]/scripts/lib/canopy/registry/RuleRegistry.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@ system.afterEvents.scriptEventReceive.subscribe((event) => {
}
if (!ruleData) return;
new Rule(ruleData);
console.warn(`[Canopy] Registered rule: ${ruleData.extensionName}:${ruleData.identifier}`);
// console.warn(`[Canopy] Registered rule: ${ruleData.extensionName}:${ruleData.identifier}`);
}, { namespaces: ['canopyExtension']});
2 changes: 1 addition & 1 deletion Canopy [BP]/scripts/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ import ProbeManager from 'src/classes/ProbeManager';
import { Command } from 'lib/canopy/Canopy';

const players = world.getAllPlayers();
if (players[0] !== undefined && players[0].isValid()) {
if (players[0]?.isValid()) {
Utils.broadcastActionBar('§aBehavior packs have been reloaded.');
ProbeManager.startCleanupCycle();
Command.broadcastPrefix();
Expand Down
4 changes: 2 additions & 2 deletions Canopy [BP]/scripts/src/classes/ProbeManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -189,14 +189,14 @@ class ProbeManager {
world.beforeEvents.playerLeave.subscribe((event) => {
const player = event.player;
system.run(() => {
if (player.getDynamicProperty('light') || player.getDynamicProperty('biome'))
if (player?.getDynamicProperty('light') || player?.getDynamicProperty('biome'))
this.removeProbe(player);
});
});

world.afterEvents.playerDimensionChange.subscribe((event) => {
const player = event.player;
if (player.getDynamicProperty('light') || player.getDynamicProperty('biome'))
if (player?.getDynamicProperty('light') || player?.getDynamicProperty('biome'))
this.removeProbe(player);
});

Expand Down
4 changes: 2 additions & 2 deletions Canopy [BP]/scripts/src/commands/camera.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ class BeforeSpectatorPlayer {

world.beforeEvents.playerGameModeChange.subscribe((event) => {
const player = event.player;
if (player.getDynamicProperty('isSpectating') && event.fromGameMode === 'spectator' && event.toGameMode !== 'spectator') {
if (player?.getDynamicProperty('isSpectating') && event.fromGameMode === 'spectator' && event.toGameMode !== 'spectator') {
system.run(() => {
player.setGameMode(event.fromGameMode);
player.onScreenDisplay.setActionBar('§cYou cannot change your gamemode while spectating.');
Expand All @@ -81,7 +81,7 @@ world.beforeEvents.playerGameModeChange.subscribe((event) => {
});

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

world.afterEvents.playerDimensionChange.subscribe((event) => {
Expand Down
4 changes: 2 additions & 2 deletions Canopy [BP]/scripts/src/commands/counter.js
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ function realtimeQueryAll(sender) {

function query(sender, color) {
const channel = channelMap.getChannel(color);
sender.sendMessage(channelMap.getQueryOutput(channel));
sender?.sendMessage(channelMap.getQueryOutput(channel));
}

function queryAll(sender) {
Expand All @@ -306,7 +306,7 @@ function queryAll(sender) {
});

if (output === '') output = '§7There are no hopper counters in use.';
sender.sendMessage(output);
sender?.sendMessage(output);
}

function setMode(sender, color, mode) {
Expand Down
2 changes: 1 addition & 1 deletion Canopy [BP]/scripts/src/commands/log.js
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ world.afterEvents.entitySpawn.subscribe((event) => {

world.beforeEvents.entityRemove.subscribe((event) => {
const removedEntity = event.removedEntity;
if (removedEntity.typeId === 'minecraft:tnt') {
if (removedEntity?.typeId === 'minecraft:tnt') {
loggingPlayers.forEach(loggingPlayer => {
if (loggingPlayer.types.includes('tnt')) {
printTntLog(loggingPlayer.player, removedEntity);
Expand Down
2 changes: 1 addition & 1 deletion Canopy [BP]/scripts/src/commands/resetall.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ function resetallCommand(sender) {
world.clearDynamicProperties();
const players = world.getAllPlayers();
players.forEach(player => {
player.clearDynamicProperties();
player?.clearDynamicProperties();
});
world.sendMessage('§cPlayer and world dynamic properties have been reset.');
}
1 change: 1 addition & 0 deletions Canopy [BP]/scripts/src/entities.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ const Entities = {

let count = 0;
for (const entity of entities) {
if (!entity) continue;
try{
const toEntity = Utils.normalizeVector(subtractVectors(entity.location, player.location));
const dotProduct = Utils.dotProduct(viewDirection, toEntity);
Expand Down
5 changes: 3 additions & 2 deletions Canopy [BP]/scripts/src/rules/InfoDisplay.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,9 @@ new InfoDisplayRule({
});

system.runInterval(() => {
const Players = world.getAllPlayers();
for (const player of Players) {
const players = world.getAllPlayers();
for (const player of players) {
if (!player) continue;
if (InfoDisplayRule.getValue(player, 'showDisplay')) InfoDisplay(player);
}
});
Expand Down
1 change: 1 addition & 0 deletions Canopy [BP]/scripts/src/rules/hotbarSwitching.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ system.runInterval(async () => {
if (!await Rule.getValue('hotbarSwitching')) return;
const players = world.getAllPlayers();
for (const player of players) {
if (!player) continue;
if (!await hasAppropriateGameMode(player)) continue;
if (hotbarManagers[player.id] === undefined)
hotbarManagers[player.id] = new HotbarManager(player);
Expand Down
4 changes: 2 additions & 2 deletions Canopy [BP]/scripts/src/rules/renewableElytra.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ new Rule({
description: 'Phantoms have a 1%% chance to drop an elytra when killed by a shulker bullet.',
});

world.afterEvents.entityDie.subscribe(async (event) => {
if (!await Rule.getValue('renewableElytra')) return;
world.afterEvents.entityDie.subscribe((event) => {
if (!Rule.getValue('renewableElytra')) return;
const entity = event.deadEntity;
if (entity?.typeId === 'minecraft:phantom' && event.damageSource.damagingProjectile?.typeId === 'minecraft:shulker_bullet') {
if (Math.random() > 0.01) return;
Expand Down
2 changes: 1 addition & 1 deletion Canopy [BP]/scripts/src/rules/renewableSponge.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ new Rule({
});

world.afterEvents.entityHurt.subscribe(async (event) => {
if (event.hurtEntity.typeId !== 'minecraft:guardian' || !await Rule.getValue('renewableSponge') || event.damageSource.cause !== 'lightning')
if (event.hurtEntity?.typeId !== 'minecraft:guardian' || !await Rule.getValue('renewableSponge') || event.damageSource.cause !== 'lightning')
return;

const guardian = event.hurtEntity;
Expand Down
7 changes: 6 additions & 1 deletion Canopy [BP]/scripts/src/validWorld.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { world, system } from '@minecraft/server';
import Data from 'stickycore/data';
import ProbeManager from 'src/classes/ProbeManager';
import { getLoadedExtensions } from 'lib/canopy/Canopy';

let hasShownWelcome = false;

world.afterEvents.playerJoin.subscribe((event) => {
let runner = system.runInterval(() => {
const players = world.getPlayers({ name: event.playerName });
players.forEach(player => {
if (!hasShownWelcome && player.isValid()) {
if (!hasShownWelcome && player?.isValid()) {
system.clearRun(runner);
hasShownWelcome = true;
onValidWorld(player);
Expand All @@ -33,4 +34,8 @@ function displayWelcome(player) {
output += `§a+ ----- +\n`;
output += `§7This server is running §l§aCanopy§r§7. Type ./help to get started.§r\n`;
player.sendMessage(output);
const extensions = getLoadedExtensions();
if (extensions.length > 0) {
player.sendMessage(`§7Loaded extensions: §a${extensions.join('§7, §a')}`);
}
}
1 change: 1 addition & 0 deletions Canopy [BP]/scripts/stickycore/data.js
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ class Data {

if (!blockRayResult && !entityRayResult) return '';
target = Utils.getClosestTarget(sender, blockRayResult, entityRayResult);
if (!target) return '';
try {
inventory = target.getComponent('inventory');
} catch(error) {
Expand Down
2 changes: 1 addition & 1 deletion Canopy [BP]/scripts/stickycore/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ class Utils {
let players;
if (sender) players = world.getPlayers({ excludeNames: [sender.name] });
else players = world.getAllPlayers();
players.forEach(player => player.onScreenDisplay.setActionBar(message));
players.forEach(player => player?.onScreenDisplay.setActionBar(message));
}

static locationInArea(area, position) {
Expand Down

0 comments on commit 40867f6

Please sign in to comment.