(state: ScriptState)
| 119 | } |
| 120 | |
| 121 | static execute(state: ScriptState) { |
| 122 | if (!state || !state.script || !state.script.info) { |
| 123 | return ScriptState.ABORTED; |
| 124 | } |
| 125 | |
| 126 | try { |
| 127 | if (state.execution !== ScriptState.RUNNING) { |
| 128 | state.executionHistory.push(state.execution); |
| 129 | } |
| 130 | state.execution = ScriptState.RUNNING; |
| 131 | |
| 132 | let start = 0; |
| 133 | if (Environment.node.debugProfile) { |
| 134 | start = performance.now() * 1000; |
| 135 | } |
| 136 | |
| 137 | while (state.execution === ScriptState.RUNNING) { |
| 138 | const opcodes = state.script.opcodes; |
| 139 | |
| 140 | if (state.pc >= opcodes.length || state.pc < -1) { |
| 141 | throw new Error('Invalid program counter: ' + state.pc + ', max expected: ' + opcodes.length); |
| 142 | } |
| 143 | |
| 144 | if (state.opcount > 500_000) { |
| 145 | throw new Error('Too many instructions'); |
| 146 | } |
| 147 | |
| 148 | state.opcount++; |
| 149 | |
| 150 | const opcode = opcodes[++state.pc]; |
| 151 | const handler = ScriptRunner.HANDLERS[opcode]; |
| 152 | if (!handler) { |
| 153 | throw new Error(`Unhandled command ${ScriptOpcodeNameMap.get(opcode) ?? opcode}`); |
| 154 | } |
| 155 | |
| 156 | handler(state); |
| 157 | } |
| 158 | |
| 159 | if (Environment.node.debugProfile) { |
| 160 | const time: number = (performance.now() * 1000 - start) | 0; |
| 161 | if (time > 1000) { |
| 162 | const message: string = `Warning [cpu time]: Script: ${state.script.name}, time: ${time}us, opcount: ${state.opcount}`; |
| 163 | if (state.self instanceof Player) { |
| 164 | state.self.wrappedMessageGame(message); |
| 165 | } else { |
| 166 | printWarning(message); |
| 167 | } |
| 168 | } |
| 169 | } |
| 170 | } catch (err: any) { |
| 171 | // print the last opcode executed |
| 172 | if (state.pc >= 0 && state.pc < state.script.opcodes.length) { |
| 173 | const opcode = state.script.opcodes[state.pc]; |
| 174 | |
| 175 | let secondary = state.intOperand; |
| 176 | if (opcode === ScriptOpcode.POP_VARP || opcode === ScriptOpcode.POP_VARN || opcode === ScriptOpcode.PUSH_VARP || opcode === ScriptOpcode.PUSH_VARN) { |
| 177 | secondary = (state.intOperand >> 16) & 0x1; |
| 178 | } else if (opcode <= ScriptOpcode.POP_ARRAY_INT) { |
no test coverage detected