github.com/df-mc/dragonfly@v0.9.13/server/internal/packbuilder/items.go (about)

     1  package packbuilder
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"github.com/df-mc/dragonfly/server/world"
     7  	"image"
     8  	"image/png"
     9  	"os"
    10  	"path/filepath"
    11  	"strings"
    12  	_ "unsafe" // Imported for compiler directives.
    13  )
    14  
    15  // buildItems builds all the item-related files for the resource pack. This includes textures, language
    16  // entries and item atlas.
    17  func buildItems(dir string) (count int, lang []string) {
    18  	if err := os.Mkdir(filepath.Join(dir, "items"), os.ModePerm); err != nil {
    19  		panic(err)
    20  	}
    21  	if err := os.MkdirAll(filepath.Join(dir, "textures/items"), os.ModePerm); err != nil {
    22  		panic(err)
    23  	}
    24  
    25  	textureData := make(map[string]any)
    26  	for _, item := range world.CustomItems() {
    27  		identifier, _ := item.EncodeItem()
    28  		lang = append(lang, fmt.Sprintf("item.%s.name=%s", identifier, item.Name()))
    29  
    30  		name := strings.Split(identifier, ":")[1]
    31  		textureData[name] = map[string]string{"textures": fmt.Sprintf("textures/items/%s.png", name)}
    32  
    33  		buildItemTexture(dir, name, item.Texture())
    34  
    35  		count++
    36  	}
    37  
    38  	buildItemAtlas(dir, map[string]any{
    39  		"resource_pack_name": "vanilla",
    40  		"texture_name":       "atlas.items",
    41  		"texture_data":       textureData,
    42  	})
    43  	return
    44  }
    45  
    46  // buildItemTexture creates a PNG file for the item from the provided image and name and writes it to the pack.
    47  func buildItemTexture(dir, name string, img image.Image) {
    48  	texture, err := os.Create(filepath.Join(dir, "textures/items", name+".png"))
    49  	if err != nil {
    50  		panic(err)
    51  	}
    52  	if err := png.Encode(texture, img); err != nil {
    53  		_ = texture.Close()
    54  		panic(err)
    55  	}
    56  	if err := texture.Close(); err != nil {
    57  		panic(err)
    58  	}
    59  }
    60  
    61  // buildItemAtlas creates the identifier to texture mapping and writes it to the pack.
    62  func buildItemAtlas(dir string, atlas map[string]any) {
    63  	b, err := json.Marshal(atlas)
    64  	if err != nil {
    65  		panic(err)
    66  	}
    67  	if err := os.WriteFile(filepath.Join(dir, "textures/item_texture.json"), b, 0666); err != nil {
    68  		panic(err)
    69  	}
    70  }