Class: Amaterasu::GameBoy::Cpu::Instructions::Add16

Inherits:
Base
  • Object
show all
Defined in:
lib/amaterasu/game_boy/cpu/instructions/add16.rb,
sig/akane/game_boy/cpu/instructions/add16.rbs

Overview

Handles the logic related to all possible ADD 16-bit instructions.

  • ADD HL, BC
  • ADD HL, DE
  • ADD HL, HL
  • ADD HL, SP
  • ADD SP, sig8

Instance Attribute Summary

Attributes inherited from Base

#mnemonic

Instance Method Summary collapse

Methods inherited from Base

#execute, #format_operand

Constructor Details

#initialize(cpu:, source:, target:) ⇒ Add16

Returns a new instance of Add16.

Parameters:

  • cpu: (Cpu)
  • target: (Symbol)
  • source: (Symbol)


15
16
17
18
19
20
# File 'lib/amaterasu/game_boy/cpu/instructions/add16.rb', line 15

def initialize(cpu:, source:, target:)
  super(cpu:)

  @mnemonic = "ADD #{format_operand(source)}, #{format_operand(target)}"
  @logic    = build_logic(source, target)
end

Instance Method Details

#add16(reg16_value) ⇒ void

This method returns an undefined value.

M-cycle 1: Fetches the instruction opcode. M-cycle 2: 16-bit add operation + flag logic + set result.

Parameters:

  • value (Integer)


41
42
43
44
45
46
47
48
49
50
# File 'lib/amaterasu/game_boy/cpu/instructions/add16.rb', line 41

def add16(reg16_value)
  hl_value = @registers.hl
  result = @cpu.add16(@registers.hl, reg16_value)

  @registers.n_flag = false
  @registers.h_flag = (hl_value & 0x0FFF) + (reg16_value & 0x0FFF) > 0x0FFF
  @registers.c_flag = result > 0xFFFF

  @registers.hl = result
end

#add16_sig8void

This method returns an undefined value.

M-cycle 1: Fetches the instruction opcode. M-cycle 2: Fetches the next byte in the PC. M-cycle 3: Signs the value + internal processing. M-cycle 4: 16-bit Add operation + flag logic + set result.



56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/amaterasu/game_boy/cpu/instructions/add16.rb', line 56

def add16_sig8
  sp = @registers.sp
  unsigned_byte = @cpu.fetch_next_byte
  offset = @cpu.sign_value(unsigned_byte)
  @cpu.internal_processing
  result = @cpu.add16(@registers.sp, offset)

  @registers.clear_flags
  @registers.h_flag = (sp & 0x0F) + (unsigned_byte & 0x0F) > 0x0F
  @registers.c_flag = (sp & 0xFF) + (unsigned_byte & 0xFF) > 0xFF

  @registers.sp = result
end

#build_logic(source, target) ⇒ Proc

Builds the logic for each ADD 16-bit instruction.

Parameters:

  • source (Symbol)
  • target (Symbol)

Returns:

  • (Proc)

    A lambda object to be called by the CPU.



26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/amaterasu/game_boy/cpu/instructions/add16.rb', line 26

def build_logic(source, target)
  return -> { add16_sig8 } if target == :sp

  case source
  when :bc     then -> { add16(@registers.bc) }
  when :de     then -> { add16(@registers.de) }
  when :hl     then -> { add16(@registers.hl) }
  when :sp     then -> { add16(@registers.sp) }
  else
    raise ArgumentError, 'Unknown Add16 source'
  end
end