57 lines
1.5 KiB
Kotlin
57 lines
1.5 KiB
Kotlin
package net.shadowfacts.asmr.program.blocks.math
|
|
|
|
import net.shadowfacts.asmr.program.ExecutableBlock
|
|
import net.shadowfacts.asmr.program.ProgramBlockInput
|
|
import net.shadowfacts.asmr.program.ProgramBlockOutput
|
|
import net.shadowfacts.asmr.program.ProgramType
|
|
import java.lang.RuntimeException
|
|
|
|
/**
|
|
* @author shadowfacts
|
|
*/
|
|
class BinaryOperatorBlock<Type: Any>(
|
|
val type: ProgramType<Type>,
|
|
val operation: Operation
|
|
): ExecutableBlock() {
|
|
|
|
init {
|
|
if (type != ProgramType.INT && type != ProgramType.FLOAT) {
|
|
throw RuntimeException("BinaryOperatorBlock type must be int or float")
|
|
}
|
|
}
|
|
|
|
val left = ProgramBlockInput(type)
|
|
val right = ProgramBlockInput(type)
|
|
|
|
val output = ProgramBlockOutput(type)
|
|
|
|
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
|
|
}
|
|
|
|
} |