TARGET      := main
SRC_DIR     := src
SHADER_DIR  := shaders
BUILD_DIR   := build

CXX         := g++
CXXFLAGS    := -g -std=c++23 -Wall -Wextra -Wpedantic -Wno-missing-field-initializers -Wno-unused-function # -fsanitize=address
LDFLAGS     := -lSDL3

GLSLC       := glslc

DEBUG       ?= 0
ifeq ($(DEBUG), 1)
    CXXFLAGS += -g -O0 -DDEBUG
else
    CXXFLAGS += -O2 -DNDEBUG
endif


SRCS        := $(wildcard $(SRC_DIR)/*.cpp)
OBJS        := $(patsubst $(SRC_DIR)/%.cpp, $(BUILD_DIR)/%.o, $(SRCS))
DEPS        := $(OBJS:.o=.d)

FRAG_SRCS   := $(wildcard $(SHADER_DIR)/*.frag)
VERT_SRCS   := $(wildcard $(SHADER_DIR)/*.vert)
SHADER_SRCS := $(FRAG_SRCS) $(VERT_SRCS)
SPIRV_OUTS  := $(addsuffix .spv, $(SHADER_SRCS))


.PHONY: all
all: $(TARGET) shaders


$(TARGET): $(OBJS)
	$(CXX) $(CXXFLAGS) $^ -o $@ $(LDFLAGS)
	@echo "Linked → $@"

$(BUILD_DIR)/%.o: $(SRC_DIR)/%.cpp | $(BUILD_DIR)
	$(CXX) $(CXXFLAGS) -MMD -MP -c $< -o $@
	@echo "Compiled → $@"

-include $(DEPS)

$(BUILD_DIR):
	mkdir -p $(BUILD_DIR)


.PHONY: shaders
shaders: $(SPIRV_OUTS)

%.spv: %
	$(GLSLC) $< -o $@
	@echo "Compiled shader → $@"

.PHONY: run
run: all
	./$(TARGET)


.PHONY: clean
clean:
	$(RM) -r $(BUILD_DIR) $(TARGET) $(SPIRV_OUTS)
	@echo "Cleaned."

.PHONY: clean-shaders
clean-shaders:
	$(RM) $(SPIRV_OUTS)
	@echo "Shader SPIR-V files removed."

.PHONY: rebuild
rebuild: clean all

.PHONY: info
info:
	@echo "Target:      $(TARGET)"
	@echo "Sources:     $(SRCS)"
	@echo "Objects:     $(OBJS)"
	@echo "Frag shaders:$(FRAG_SRCS)"
	@echo "Vert shaders:$(VERT_SRCS)"
	@echo "SPIR-V outs: $(SPIRV_OUTS)"
	@echo "Debug:       $(DEBUG)"
