-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathutils.js
More file actions
300 lines (269 loc) · 8.85 KB
/
Copy pathutils.js
File metadata and controls
300 lines (269 loc) · 8.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
import { world, system, ItemStack, DimensionTypes } from '@minecraft/server';
import { FormCancelationReason, uiManager } from '@minecraft/server-ui';
export function calcDistance(locationOne, locationTwo, useY = true) {
const dx = locationOne.x - locationTwo.x;
const dz = locationOne.z - locationTwo.z;
if (!useY) return Math.sqrt(dx*dx + dz*dz);
const dy = locationOne.y - locationTwo.y;
return Math.sqrt(dx*dx + dy*dy + dz*dz);
}
export function isString(str) {
return typeof str === 'string' || str instanceof String;
}
export function isNumeric(str) {
return !isNaN(Number(str)) && str !== null && typeof str !== 'boolean';
}
export function getClosestTarget(player, blockRayResult, entityRayResult) {
let entity;
let block;
if (entityRayResult.length > 0)
entity = entityRayResult[0]?.entity;
if (blockRayResult)
block = blockRayResult.block;
if (!entity)
return block;
if (!block)
return entity;
const entityDist = calcDistance(player.getHeadLocation(), entity.location);
const blockDist = calcDistance(player.getHeadLocation(), block.location);
return entityDist <= blockDist ? entity : block;
}
export function parseName(target, includePrefix = true) {
if (target.typeId === 'minecraft:player')
return `§o${target.name}§r`;
return includePrefix ? target.typeId : target.typeId.replace('minecraft:', '');
}
export function stringifyLocation(location, precision = 0) {
if (precision < 0)
throw new Error('Precision cannot be negative');
return `[${location.x.toFixed(precision)}, ${location.y.toFixed(precision)}, ${location.z.toFixed(precision)}]`
}
export function getColorCode(color) {
color = color.toLowerCase();
switch (color) {
case 'red': return '§c';
case 'orange': return '§6';
case 'yellow': return '§e';
case 'lime': return '§a';
case 'green': return '§2';
case 'cyan': return '§3';
case 'light_blue': return '§b';
case 'blue': return '§9';
case 'purple': return '§u';
case 'pink': return '§d';
case 'magenta': return '§5';
case 'brown': return '§n';
case 'black': return '§0';
case 'white': return '§f';
case 'light_gray': return '§7';
case 'gray': return '§8';
default: return '';
}
}
export function wait(ms) {
const startTime = Date.now();
let endTime = Date.now();
while (endTime - startTime < ms)
endTime = Date.now();
return { startTime, endTime };
}
export function getInventory(block) {
const container = block.getComponent('inventory')?.container;
if (container === undefined) return {};
const items = {};
for (let i = 0; i < container.size; i++) {
const itemStack = container.getItem(i);
if (itemStack === undefined) continue;
items[i] = { typeId: itemStack.type.id, amount: itemStack.amount };
}
return items;
}
export function restoreInventory(block, items) {
const container = block.getComponent('inventory')?.container;
if (container === undefined)
return;
for (let i = 0; i < container.size; i++) {
const item = items[i];
if (item === undefined)
continue;
container.getSlot(i).setItem(new ItemStack(item.typeId, item.amount));
}
}
export function broadcastActionBar(message, sender) {
let players;
if (sender)
players = world.getPlayers({ excludeNames: [sender.name] });
else
players = world.getAllPlayers();
players.forEach(player => player?.onScreenDisplay.setActionBar(message));
}
export function locationInArea(area, position) {
if (area?.dimensionId !== position?.dimensionId)
return false;
const { posOne, posTwo } = area;
const { location } = position;
const inX = location.x >= Math.min(posOne.x, posTwo.x) && location.x <= Math.max(posOne.x, posTwo.x);
const inY = location.y >= Math.min(posOne.y, posTwo.y) && location.y <= Math.max(posOne.y, posTwo.y);
const inZ = location.z >= Math.min(posOne.z, posTwo.z) && location.z <= Math.max(posOne.z, posTwo.z);
return inX && inY && inZ;
}
export function getColoredDimensionName(dimensionId) {
switch (dimensionId) {
case 'minecraft:overworld':
case 'overworld':
return '§aOverworld';
case 'minecraft:nether':
case 'nether':
return '§cNether';
case 'minecraft:the_end':
case 'the_end':
return '§dEnd';
default:
return '§f' + dimensionId;
}
}
export function getColorByDimension(dimensionId) {
switch (dimensionId) {
case 'minecraft:overworld':
case 'overworld':
return '§a';
case 'minecraft:nether':
case 'nether':
return '§c';
case 'minecraft:the_end':
case 'the_end':
return '§d';
default:
return '§f';
}
}
export function getScriptEventSourceName(event) {
switch (event.sourceType) {
case 'Block':
if (event.sourceBlock.typeId.includes('command_block'))
return '!';
return event.sourceBlock.typeId;
case 'Entity':
if (event.sourceEntity.typeId === 'minecraft:player')
return event.sourceEntity.name;
return event.sourceEntity.typeId;
case 'Server':
return 'Server';
default:
return 'Unknown';
}
}
export function getScriptEventSourceObject(event) {
switch (event.sourceType) {
case 'Block':
return event.sourceBlock;
case 'Entity':
return event.sourceEntity;
case 'Server':
return 'Server';
default:
return 'Unknown';
}
}
export function recolor(text, term, colorCode = '§f') {
if (text === '' || term === '' || colorCode === '')
return text;
const lowerText = text.toLowerCase();
const lowerTerm = term.toLowerCase();
const index = lowerText.indexOf(lowerTerm);
if (index === -1)
return text;
const splitText = lowerText.split(lowerTerm);
let newText = '';
let lastColorCode = '§f';
let currentIndex = 0;
for (let i = 0; i < splitText.length; i++) {
const splice = splitText[i];
const originalSplice = text.slice(currentIndex, currentIndex + splice.length);
currentIndex += splice.length;
if (i === splitText.length - 1) {
newText += originalSplice;
continue;
}
const colorCodeIndex = originalSplice.lastIndexOf('§');
if (colorCodeIndex === -1) {
newText += originalSplice + colorCode + text.slice(currentIndex, currentIndex + term.length) + lastColorCode;
} else {
lastColorCode = originalSplice.slice(colorCodeIndex, colorCodeIndex + 2);
newText += originalSplice + colorCode + text.slice(currentIndex, currentIndex + term.length) + lastColorCode;
}
currentIndex += term.length;
}
return newText;
}
export function getEntitiesByType(type) {
let entities = [];
DimensionTypes.getAll().forEach(dimensionType => {
const dimensionEntities = world.getDimension(dimensionType.typeId).getEntities({ type });
if (dimensionEntities)
entities = entities.concat(dimensionEntities);
})
return entities;
}
export function getRaycastResults(player, distance) {
const blockRayResult = player.getBlockFromViewDirection({ includeLiquidBlocks: false, includePassableBlocks: true, maxDistance: distance });
const entityRayResult = player.getEntitiesFromViewDirection({ ignoreBlockCollision: false, includeLiquidBlocks: false, includePassableBlocks: false, maxDistance: distance });
return { blockRayResult, entityRayResult };
}
export function titleCase(str) {
return str
.replace(/([a-z])([A-Z])/g, '$1 $2')
.toLowerCase()
.replace(/_/g, ' ')
.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
}
export function formatColorStr(color) {
return `${getColorCode(color)}${color}§r`;
}
export async function forceShow(player, form, { timeout = Infinity, showBusyMessage = true } = {}) {
uiManager.closeAllForms(player);
const startTick = system.currentTick;
while ((system.currentTick - startTick) < timeout) {
const response = await form.show(player);
if (startTick + 1 === system.currentTick && response.cancelationReason === FormCancelationReason.UserBusy && showBusyMessage)
player.sendMessage({ translate: 'commands.canopy.menu.busy' });
if (response.cancelationReason !== FormCancelationReason.UserBusy)
return response;
}
throw new Error({ translate: 'commands.canopy.menu.timeout', with: [String(timeout)] });
};
export function getTranslatedEntityList(entities) {
const message = { rawtext: [] };
for (let i = 0; i < entities.length; i++) {
const entity = entities[i];
if (entity.nameTag)
message.rawtext.push({ translate: entity.nameTag });
else
message.rawtext.push({ translate: entities[i].localizationKey });
if (i !== entities.length - 1)
message.rawtext.push({ rawtext: [{ text: ', ' }] });
}
return message;
}
export function getNameFromEntityId(id) {
let entityName = id;
try {
const entity = world.getEntity(id);
entityName = entity?.name || entity?.nameTag || entityName;
} catch (error) {
if (!error.message.includes("is invalid") && error.name !== 'InvalidArgumentError')
throw error;
}
return entityName;
}
export function hexToRGB(hex) {
hex = hex.replace(/^#/, '');
const num = parseInt(hex, 16);
return {
red: ((num >> 16) & 0xFF) / 255,
green: ((num >> 8) & 0xFF) / 255,
blue: (num & 0xFF) / 255
};
}