Skip to content

Commit

Permalink
Add new things.
Browse files Browse the repository at this point in the history
  • Loading branch information
ZXMushroom63 committed Dec 9, 2024
1 parent 7b38487 commit 3bea644
Show file tree
Hide file tree
Showing 8 changed files with 239 additions and 30 deletions.
15 changes: 15 additions & 0 deletions block_libmap.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const BLOCK_LIBMAP = {};
var oldDefineBlocks = Blockly.common.defineBlocks;
Blockly.common.defineBlocks = function (blockMap) {
var types = Object.keys(blockMap);
types.forEach(type => {
BLOCK_LIBMAP[type] = (blockMap[type].libs || []);
});
return oldDefineBlocks.apply(this, [blockMap]);
}
function getBlockLibs(block) {
return BLOCK_LIBMAP[block.type] || [];
}
function getBlockLibsByType(blockType) {
return BLOCK_LIBMAP[blockType] || [];
}
56 changes: 55 additions & 1 deletion blocks/Blocks.js
Original file line number Diff line number Diff line change
Expand Up @@ -105,5 +105,59 @@ javascript.javascriptGenerator.forBlock['handle_BlockBreak'] = function () {
const variable_world = javascript.javascriptGenerator.getVariableName(this.getFieldValue('WORLD'));
const variable_blockpos = javascript.javascriptGenerator.getVariableName(this.getFieldValue('BLOCKPOS'));
const statement = javascript.javascriptGenerator.statementToCode(this, 'CODE');
return { code: statement, args: [variable_world, variable_blockpos, "$blockstate"] };
return { code: statement, args: [variable_world, variable_blockpos, "$$blockstate"] };
}



const handle_BlockAdded = {
init: function () {
this.appendDummyInput('ID')
.appendField('Handler ID:')
.appendField(new Blockly.FieldTextInput('block added 1'), 'ID');
this.appendDummyInput('')
.appendField('Block Placed Handler with:')
.appendField(new Blockly.FieldVariable('world'), 'WORLD')
.appendField(new Blockly.FieldVariable('position'), 'BLOCKPOS');
this.appendStatementInput('CODE');
this.setInputsInline(false)
this.setTooltip('');
this.setHelpUrl('');
this.setColour(0);
}
};
Blockly.common.defineBlocks({ handle_BlockAdded: handle_BlockAdded });

javascript.javascriptGenerator.forBlock['handle_BlockAdded'] = function () {
const variable_world = javascript.javascriptGenerator.getVariableName(this.getFieldValue('WORLD'));
const variable_blockpos = javascript.javascriptGenerator.getVariableName(this.getFieldValue('BLOCKPOS'));
const statement = javascript.javascriptGenerator.statementToCode(this, 'CODE');
return { code: statement, args: [variable_world, variable_blockpos, "$$blockstate"] };
}



const handle_BlockNeighbourChange = {
init: function () {
this.appendDummyInput('ID')
.appendField('Handler ID:')
.appendField(new Blockly.FieldTextInput('block neighbour update 1'), 'ID');
this.appendDummyInput('')
.appendField('Block Neighbour Changed Handler with:')
.appendField(new Blockly.FieldVariable('world'), 'WORLD')
.appendField(new Blockly.FieldVariable('position'), 'BLOCKPOS');
this.appendStatementInput('CODE');
this.setInputsInline(false)
this.setTooltip('');
this.setHelpUrl('');
this.setColour(0);
}
};
Blockly.common.defineBlocks({ handle_BlockNeighbourChange: handle_BlockNeighbourChange });

javascript.javascriptGenerator.forBlock['handle_BlockNeighbourChange'] = function () {
const variable_world = javascript.javascriptGenerator.getVariableName(this.getFieldValue('WORLD'));
const variable_blockpos = javascript.javascriptGenerator.getVariableName(this.getFieldValue('BLOCKPOS'));
const statement = javascript.javascriptGenerator.statementToCode(this, 'CODE');
return { code: statement, args: [variable_world, variable_blockpos, "$$blockstate"] };
}
62 changes: 62 additions & 0 deletions blocks/World.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
const world_explosion = {
init: function () {
this.appendValueInput('WORLD')
.appendField('Spawn explosion in world:');
this.appendValueInput('POS')
.appendField('Position:');
this.appendValueInput('STRENGTH')
.setCheck('Number')
.appendField('Strength:');
this.appendValueInput('FIRE')
.setCheck('Boolean')
.appendField('Fire:');
this.appendValueInput('SMOKE')
.setCheck('Boolean')
.appendField('Particles:');
this.setInputsInline(false)
this.setPreviousStatement(true, null);
this.setNextStatement(true, null);
this.setTooltip('');
this.setHelpUrl('');
this.setColour(195);
}
};
Blockly.common.defineBlocks({ world_explosion: world_explosion });
javascript.javascriptGenerator.forBlock['world_explosion'] = function () {
const value_world = javascript.javascriptGenerator.valueToCode(this, 'WORLD', javascript.Order.ATOMIC);
const value_pos = javascript.javascriptGenerator.valueToCode(this, 'POS', javascript.Order.ATOMIC);
const value_strength = javascript.javascriptGenerator.valueToCode(this, 'STRENGTH', javascript.Order.ATOMIC);
const value_fire = javascript.javascriptGenerator.valueToCode(this, 'FIRE', javascript.Order.ATOMIC);
const value_smoke = javascript.javascriptGenerator.valueToCode(this, 'SMOKE', javascript.Order.ATOMIC);
const code = `${value_world}.$newExplosion(null, ${value_pos}.$x, ${value_pos}.$y, ${value_pos}.$z, ${value_strength}, (${value_fire} ? 1 : 0), (${value_smoke} ? 1 : 0));`;
return code;
}



const world_command = {
init: function () {
this.appendValueInput('WORLD')
.appendField('Execute command in world');
this.appendValueInput('POS')
.appendField('Position:');
this.appendValueInput('CMD')
.setCheck('String')
.appendField('Command:');
this.setInputsInline(false)
this.setPreviousStatement(true, null);
this.setNextStatement(true, null);
this.setTooltip('');
this.setHelpUrl('');
this.setColour(195);
},
libs: ["execute_command"]
};
Blockly.common.defineBlocks({ world_command: world_command });
javascript.javascriptGenerator.forBlock['world_command'] = function () {
const value_world = javascript.javascriptGenerator.valueToCode(this, 'WORLD', javascript.Order.ATOMIC);
const value_pos = javascript.javascriptGenerator.valueToCode(this, 'POS', javascript.Order.ATOMIC);
const value_cmd = javascript.javascriptGenerator.valueToCode(this, 'CMD', javascript.Order.ATOMIC);
const code = `efb2__executeCommand(${value_world}, ${value_pos}, ${value_cmd});`;
return code;
}
3 changes: 3 additions & 0 deletions compiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ function getCompiledCode() {
functionPrereqs = functionPrereqs.concat(PRIMITIVES[node.type].uses);
datablock_contents += PRIMITIVES[node.type].asJavaScript.apply(node, []);
});
workspace.getAllBlocks().forEach(block => {
functionPrereqs = functionPrereqs.concat(getBlockLibs(block));
});
functionPrereqs = [...new Set(functionPrereqs)]; //dedupe the list
functionPrereqs.forEach(fn => {
prereq_contents += getFunctionCode(FUNCTIONS[fn]);
Expand Down
28 changes: 28 additions & 0 deletions functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,34 @@ FUNCTIONS["fixup_block_ids"] = {
EFB2__defineFixupGlobal();
},
};

FUNCTIONS["execute_command"] = {
identifier: "execute_command",
//Very important that there is no name and a whitespace before and after the parantheses
code: function () {
function EFB2__defineExecCmdGlobal() {
globalThis.efb2__executeCommand = function efb2__executeCommand($world, $blockpos, commandStr) {
var fakeEntity = (new new ModAPI.reflect.getClassByName("Entity").class);
fakeEntity.$setPosition($blockpos.$x, $blockpos.$y, $blockpos.$z);
var vector = ModAPI.reflect.getClassByName("Vec3").constructors[0]($blockpos.$x, $blockpos.$y, $blockpos.$z);
var cmd = Object.assign((new new ModAPI.reflect.getClassByName("CommandBlockLogic").class), {
$func_145751_f: ()=>{return 1},
$updateCommand: ()=>{},
$func_145757_a: ()=>{},
$getPosition: ()=>{return $blockpos},
$getPositionVector: ()=>{return vector},
$getEntityWorld: ()=>{return $world},
$getCommandSenderEntity: ()=>{return fakeEntity}
});
cmd.$setCommand(ModAPI.util.str(commandStr));
cmd.$trigger($world);
}
}
ModAPI.dedicatedServer.appendCode(EFB2__defineExecCmdGlobal);
EFB2__defineExecCmdGlobal();
},
};

function getFunctionCode(fn) {
return fn.code.toString().match(codeGrabberRegex)?.[0]
|| (()=>{console.error("Malformed function: ", fn); return "";})();
Expand Down
10 changes: 10 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,12 @@
</block>
<block type="blocks_blockswitch"> </block>
<block type="handle_BlockBreak"> </block>
<block type="handle_BlockAdded"> </block>
<block type="handle_BlockNeighbourChange"> </block>
</category>
<category name="World" colour="#22aabb">
<block type="world_explosion"> </block>
<block type="world_command"> </block>
</category>
</xml>
</head>
Expand Down Expand Up @@ -429,7 +435,11 @@ <h4>Dirt Block</h4>
</td>
</tr>
</table>
<!-- Blockly block libmap builder -->
<script src="block_libmap.js"></script>

<!-- Additional blocks -->
<script src="blocks/World.js"></script>
<script src="blocks/Blocks.js"></script>
<script src="blocks/Events.js"></script>
<script src="blocks/ReturnBlock.js"></script>
Expand Down
19 changes: 16 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,16 @@ var workspace = globalThis.workspace = Blockly.inject('blockly', {
theme: "dark",
trashcan: true,
readOnly: false,
toolbox: document.querySelector("#toolbox")
toolbox: document.querySelector("#toolbox"),
zoom: {
controls: true,
wheel: true,
startScale: 1.0,
maxScale: 3,
minScale: 0.3,
scaleSpeed: 1.2,
pinch: true
},
});
var handlers = {};
var handlerMapDict = {};
Expand All @@ -19,16 +28,20 @@ function getHandlers(type) {
function getHandler(type, name) {
return handlerMapDict["handle_" + type]?.[name] || null;
}
function getHandlerCode(type, tag) {
function getHandlerCode(type, tag, defaultArgs) {
var handler = getHandler(type, tag);
if (!handler) { return { code: "", args: defaultArgs } };
var usedVariableSet = new Set();
handler.getDescendants(true).forEach(block => {
block.getVars().forEach(varId => {
usedVariableSet.add(varId);
});
});
var variableCode = "var " + [...usedVariableSet].map(varId => { return javascript.javascriptGenerator.getVariableName(varId) }).join(",") + ";"
var generatedCode = javascript.javascriptGenerator.forBlock[handler.type].apply(handler, []);

var variableCode = [...usedVariableSet].map(varId => { return javascript.javascriptGenerator.getVariableName(varId) }).join(",");
variableCode = variableCode ? ("var " + variableCode + ";") : "";

generatedCode.code = variableCode + generatedCode.code;
return generatedCode;
}
Expand Down
76 changes: 50 additions & 26 deletions primitives/AdvancedBlock.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//TODO: tickRate/getTickRate, quantityDropped, onBlockDestroyedByExplosion, onEntityCollidedWithBlock, onBlockActivated, onEntityCollidedWithBlock
PRIMITIVES["block_advanced"] = {
name: "Advanced Block",
uses: ["fixup_block_ids"],
Expand All @@ -8,59 +9,82 @@ PRIMITIVES["block_advanced"] = {
texture: VALUE_ENUMS.IMG,
material: ['air', 'grass', 'ground', 'wood', 'rock', 'iron', 'anvil', 'water', 'lava', 'leaves', 'plants', 'vine', 'sponge', 'cloth', 'fire', 'sand', 'circuits', 'carpet', 'glass', 'redstoneLight', 'tnt', 'coral', 'ice', 'packedIce', 'snow', 'craftedSnow', 'cactus', 'clay', 'gourd', 'dragonEgg', 'portal', 'cake', 'web', 'piston', 'barrier'],
Constructor: VALUE_ENUMS.ABSTRACT_HANDLER + "BlockConstructor",
Break: VALUE_ENUMS.ABSTRACT_HANDLER + "BlockBreak",
Added: VALUE_ENUMS.ABSTRACT_HANDLER + "BlockAdded",
NeighborChange: VALUE_ENUMS.ABSTRACT_HANDLER + "NeighborChange",
},
asJavaScript: function () {
console.log(this);
var constructorHandler = getHandlerCode("BlockConstructor", this.tags.Constructor);
var constructorHandler = getHandlerCode("BlockConstructor", this.tags.Constructor, []);
var breakHandler = getHandlerCode("BlockBreak", this.tags.Break, ["$$world", "$$blockpos", "$$blockstate"]);
var addedHandler = getHandlerCode("BlockAdded", this.tags.Added, ["$$world", "$$blockpos", "$$blockstate"]);
var neighborHandler = getHandlerCode("NeighborChange", this.tags.NeighborChange, ["$$world", "$$blockpos", "$$blockstate"]);
return `(function AdvancedBlockDatablock() {
const blockTexture = "${this.tags.texture}";
const $$blockTexture = "${this.tags.texture}";
function ServersideBlocks() {
var itemClass = ModAPI.reflect.getClassById("net.minecraft.item.Item");
var blockClass = ModAPI.reflect.getClassById("net.minecraft.block.Block");
var iproperty = ModAPI.reflect.getClassById("net.minecraft.block.properties.IProperty").class;
var makeBlockState = ModAPI.reflect.getClassById("net.minecraft.block.state.BlockState").constructors.find(x => x.length === 2);
var blockSuper = ModAPI.reflect.getSuper(blockClass, (x) => x.length === 2);
var nmb_AdvancedBlock = function nmb_AdvancedBlock() {
blockSuper(this, ModAPI.materials.${this.tags.material}.getRef());
var $$itemClass = ModAPI.reflect.getClassById("net.minecraft.item.Item");
var $$blockClass = ModAPI.reflect.getClassById("net.minecraft.block.Block");
var $$iproperty = ModAPI.reflect.getClassById("net.minecraft.block.properties.IProperty").class;
var $$makeBlockState = ModAPI.reflect.getClassById("net.minecraft.block.state.BlockState").constructors.find(x => x.length === 2);
var $$blockSuper = ModAPI.reflect.getSuper($$blockClass, (x) => x.length === 2);
var $$breakBlockMethod = $$blockClass.methods.breakBlock.method;
var $$onBlockAddedMethod = $$blockClass.methods.onBlockAdded.method;
var $$onNeighborBlockChangeMethod = $$blockClass.methods.onNeighborBlockChange.method;
var $$nmb_AdvancedBlock = function $$nmb_AdvancedBlock() {
$$blockSuper(this, ModAPI.materials.${this.tags.material}.getRef());
this.$defaultBlockState = this.$blockState.$getBaseState();
${constructorHandler.code}
${constructorHandler.code};
}
ModAPI.reflect.prototypeStack(blockClass, nmb_AdvancedBlock);
nmb_AdvancedBlock.prototype.$isOpaqueCube = function () {
ModAPI.reflect.prototypeStack($$blockClass, $$nmb_AdvancedBlock);
$$nmb_AdvancedBlock.prototype.$isOpaqueCube = function () {
return 1;
}
nmb_AdvancedBlock.prototype.$createBlockState = function () {
return makeBlockState(this, ModAPI.array.object(iproperty, 0));
$$nmb_AdvancedBlock.prototype.$createBlockState = function () {
return $$makeBlockState(this, ModAPI.array.object($$iproperty, 0));
}
$$nmb_AdvancedBlock.prototype.$breakBlock = function (${breakHandler.args.join(", ")}) {
${breakHandler.code};
return $$breakBlockMethod(this, ${breakHandler.args.join(", ")});
}
$$nmb_AdvancedBlock.prototype.$onBlockAdded = function (${addedHandler.args.join(", ")}) {
${addedHandler.code};
return $$onBlockAddedMethod(this, ${addedHandler.args.join(", ")});
}
$$nmb_AdvancedBlock.prototype.$onNeighborBlockChange = function (${neighborHandler.args.join(", ")}) {
${neighborHandler.code};
return $$onNeighborBlockChangeMethod(this, ${neighborHandler.args.join(", ")});
}
function internal_reg() {
var cblock = (new nmb_AdvancedBlock()).$setUnlocalizedName(
function $$internal_reg() {
var $$cblock = (new $$nmb_AdvancedBlock()).$setUnlocalizedName(
ModAPI.util.str("${this.tags.id}")
);
blockClass.staticMethods.registerBlock0.method(
$$blockClass.staticMethods.registerBlock0.method(
ModAPI.keygen.block("${this.tags.id}"),
ModAPI.util.str("${this.tags.id}"),
cblock
$$cblock
);
itemClass.staticMethods.registerItemBlock0.method(cblock);
$$itemClass.staticMethods.registerItemBlock0.method($$cblock);
efb2__fixupBlockIds();
ModAPI.blocks["${this.tags.id}"] = cblock;
ModAPI.blocks["${this.tags.id}"] = $$cblock;
return cblock;
return $$cblock;
}
if (ModAPI.materials) {
return internal_reg();
return $$internal_reg();
} else {
ModAPI.addEventListener("bootstrap", internal_reg);
ModAPI.addEventListener("bootstrap", $$internal_reg);
}
}
ModAPI.dedicatedServer.appendCode(ServersideBlocks);
var cblock = ServersideBlocks();
var $$cblock = ServersideBlocks();
ModAPI.addEventListener("lib:asyncsink", async () => {
ModAPI.addEventListener("custom:asyncsink_reloaded", ()=>{
ModAPI.mc.renderItem.registerBlock(cblock, ModAPI.util.str("${this.tags.id}"));
ModAPI.mc.renderItem.registerBlock($$cblock, ModAPI.util.str("${this.tags.id}"));
});
AsyncSink.L10N.set("tile.${this.tags.id}.name", "${this.tags.name}");
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/models/block/${this.tags.id}.json", JSON.stringify(
Expand Down Expand Up @@ -93,7 +117,7 @@ PRIMITIVES["block_advanced"] = {
}
));
AsyncSink.setFile("resourcepacks/AsyncSinkLib/assets/minecraft/textures/blocks/${this.tags.id}.png", await (await fetch(
blockTexture
$$blockTexture
)).arrayBuffer());
});
})();`;
Expand Down

0 comments on commit 3bea644

Please sign in to comment.