SIM_TARGET = build/top
BIN_TARGET = build/top.bin
PCF = constraints/iceFUN.pcf
TIMING = constraints/timing.py
YOSYS = yosys
PNR = nextpnr-ice40
IPACK = icepack
BURN = iceFUNprog
SBY = sby

VERILATOR=verilator
VERILATOR_ROOT ?= $(shell bash -c 'verilator -V|grep VERILATOR_ROOT | head -1 | sed -e "s/^.*=\s*//"')
VINC := $(VERILATOR_ROOT)/include

RTL_SRC := $(wildcard rtl/*.v)
SIM_SRC := $(wildcard sim/*.cc)
FV_SRC := sim/top.sby

BUILD_DIR := ./build

define colorecho
      @tput setaf 6
      @echo $1
      @tput sgr0
endef

.PHONY: all burn fv clean sim
all: $(SIM_TARGET)  $(BIN_TARGET)

$(BUILD_DIR)/Vtop.cc: $(RTL_SRC)
	$(call colorecho, "Running verilator")
	mkdir -p $(BUILD_DIR)
	$(VERILATOR) --trace -Wall -cc $^ --top-module top -GWIDTH=10\
		--Mdir $(BUILD_DIR) --timescale-override 10ns/1ns

$(BUILD_DIR)/Vtop__ALL.a: $(BUILD_DIR)/Vtop.cc
	make --no-print-directory -C $(BUILD_DIR) -f Vtop.mk

# std=c++11 flag is needed as of verilator v4.100
$(SIM_TARGET): $(SIM_SRC) $(BUILD_DIR)/Vtop__ALL.a
	$(call colorecho, "Compiling simulation executable")
	g++ -I$(VINC) -I$(BUILD_DIR) -std=c++14 $(VINC)/verilated.cpp\
		$(VINC)/verilated_vcd_c.cpp $^ -o $@
	echo "Run simulation with ./$(SIM_TARGET)"

$(BUILD_DIR)/top.json: $(RTL_SRC)
	$(call colorecho, "Synthesizing ...")
	mkdir -p $(BUILD_DIR)
	$(YOSYS) -p "synth_ice40 -top top -json build/top.json" -q $^

$(BIN_TARGET): $(BUILD_DIR)/top.json $(PCF) $(TIMING)
	$(call colorecho, "Routing and building binary stream ...") 
	$(PNR) -r --hx8k --json $< --package cb132 \
		--asc $(BUILD_DIR)/top.asc --opt-timing --pcf $(PCF) \
		--pre-pack $(TIMING) -l $(BUILD_DIR)/pnr_report.txt -q 
	$(IPACK) $(BUILD_DIR)/top.asc $@
	$(call colorecho, "Done!")

sim: $(SIM_TARGET)
	$(call colorecho, "Running simulation")
	$(SIM_TARGET) && open $(BUILD_DIR)/waveform.vcd

burn: $(BIN_TARGET)
	$(BURN) $<

fv:
	$(SBY) -f $(FV_SRC) -d $(BUILD_DIR)/fv

clean:
	rm -rf $(BUILD_DIR)

$V.SILENT:
