# Installation des packages si nécessaire
# install.packages(c("rayshader", "png", "raster"))

library(rayshader)
library(png)
library(raster)

cat("🎯 MODE PNG - PROPORTIONS 50x50x50\n")
cat("=====================================\n")

# 1. PARAMÈTRES
largeur_max_mm <- 50
hauteur_max_mm <- 50
fichier_entree <- "data/pic.png"  # Assurez-vous que le fichier est bien là
fichier_sortie <- "output/relief.obj"

# 2. CHARGEMENT DU PNG
if (!file.exists(fichier_entree)) {
  stop(paste("❌ Erreur : Le fichier", fichier_entree, "est introuvable !"))
}

img <- readPNG(fichier_entree)

# 3. CONVERSION EN NIVEAUX DE GRIS (si l'image est en couleur)
if (length(dim(img)) == 3) {
  # On utilise la formule de luminance standard : R*0.299 + G*0.587 + B*0.114
  elmat <- 0.299 * img[,,1] + 0.587 * img[,,2] + 0.114 * img[,,3]
} else {
  elmat <- img
}

# Rayshader lit les matrices de bas en haut, il faut souvent inverser les lignes
elmat <- elmat[nrow(elmat):1, ]

# 4. NORMALISATION POUR LA HAUTEUR EXACTE (Z)
# On force les valeurs entre 0 et hauteur_max_mm
elmat_norm <- (elmat - min(elmat)) / (max(elmat) - min(elmat))
elmat_final <- elmat_norm * hauteur_max_mm

# 5. CALCUL DU ZSCALE POUR LES PROPORTIONS X/Y (IMPORTANT)
# Pour que l'objet fasse 50mm de large dans le monde réel :
# zscale = (largeur_en_pixels / largeur_voulue_en_mm)
largeur_pixels <- ncol(elmat_final)
z_scale_calcule <- largeur_pixels / largeur_max_mm

cat("📊 Dimensions de l'image:", largeur_pixels, "x", nrow(elmat_final), "pixels\n")
cat("📏 Z-Scale calculé:", z_scale_calcule, "\n")

# 6. VISUALISATION 3D
cat("🎨 Génération de la vue 3D...\n")
plot_3d(sphere_shade(elmat_final, texture = "bw"), # "bw" au lieu de "gray"
        elmat_final, 
        zscale = z_scale_calcule, 
        windowsize = c(1000, 800),
        baseshape = "rectangle",
        solid = TRUE,
        soliddepth = -5, 
        fov = 0, 
        zoom = 0.6, 
        phi = 45, 
        theta = 0)

# 7. EXPORT OBJ
if (!dir.exists("output")) dir.create("output")
save_obj(fichier_sortie)

cat("\n✅ TERMINÉ !\n")
cat("📍 Fichier sauvegardé :", fichier_sortie, "\n")
cat("💡 Dans votre logiciel 3D, redimensionnez l'objet à 50x50x50mm si nécessaire.\n")
