ASMR/src/main/kotlin/net/shadowfacts/asmr/program/blocks/math/BinaryOperatorBlock.kt

59 lines
1.7 KiB
Kotlin

package net.shadowfacts.asmr.program.blocks.math
import net.minecraft.util.Identifier
import net.shadowfacts.asmr.ASMR
import net.shadowfacts.asmr.program.*
import net.shadowfacts.asmr.program.execution.SimpleExecutableBlock
import java.lang.RuntimeException
/**
* @author shadowfacts
*/
class BinaryOperatorBlock<Type: Any>(
val type: ProgramType<Type>,
val operation: Operation
): SimpleExecutableBlock(
Identifier(ASMR.modid, "binary_operator")
) {
init {
if (type != ProgramType.INT && type != ProgramType.FLOAT) {
throw RuntimeException("BinaryOperatorBlock type must be int or float")
}
}
val left = ProgramBlockInput(Identifier(ASMR.modid, "binary_operator.left_operand"), type, this)
val right = ProgramBlockInput(Identifier(ASMR.modid, "binary_operator.right_operand"), type, this)
val output = ProgramBlockOutput(Identifier(ASMR.modid, "binary_operator.result"), type, this)
override val inputs: Array<ProgramBlockInput<*>> = arrayOf(left, right)
override val outputs: Array<ProgramBlockOutput<*>> = arrayOf(output)
override fun execute() {
if (type == ProgramType.INT) {
val left = left.value as Int
val right = right.value as Int
output.value = when (operation) {
Operation.ADD -> left + right
Operation.SUBTRACT -> left - right
Operation.MULTIPLY -> left * right
Operation.DIVIDE -> left / right
} as Type
} else if (type == ProgramType.FLOAT) {
val left = left.value as Float
val right = right.value as Float
output.value = when (operation) {
Operation.ADD -> left + right
Operation.SUBTRACT -> left - right
Operation.MULTIPLY -> left * right
Operation.DIVIDE -> left / right
} as Type
}
}
enum class Operation {
ADD, SUBTRACT, MULTIPLY, DIVIDE
}
}