summaryrefslogtreecommitdiff
path: root/engine/Dynamic/Descriptors/Objects.go
blob: 92a44d726c8c85e54eaa518d3746581538a8246a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package descriptors

import (
	"encoding/json"
	"fmt"

	components "github.com/DegustatorPonos/RuinesOfRafdolon/Components"
	coreobjects "github.com/DegustatorPonos/RuinesOfRafdolon/CoreObjects"
	rl "github.com/gen2brain/raylib-go/raylib"
)

const ObjectsDirName string = "Objects"

type ObjectDescriptor struct {
	Name string
	Textures []*ObjectTextureBlock
}

// Maps objects by their IDs
func MapObjectDescriptors(loaded []*ObjectDescriptor) map[string]*ObjectDescriptor {
	var outp = make(map[string]*ObjectDescriptor, 0)
	for _, v := range loaded {
		outp[v.Name] = v
	}
	return outp
}

func (base *ObjectDescriptor) IsValid() error {
	if base.Textures == nil {
		return fmt.Errorf("The textures are not specified")
	}
	for i, v := range base.Textures {
		// The texture was not specified
		if v.TextureId == nil && len(v.Name) == 0 {
			return fmt.Errorf("The texture #%d was not specified (neither texture name nor ID)", i)
		}
	}
	return nil
}

func (base *ObjectDescriptor) Parse() coreobjects.DynamicObject {
	var outp = coreobjects.DynamicObject{
		Textures: make([]*coreobjects.TextureBlock, len(base.Textures)),
	}
	for i, v := range base.Textures {
		var texture, err = v.GetTexture()
		if err != nil {
			rl.TraceLog(rl.LogWarning, "Failed to get the required by the object %s texture: %s", base.Name, err.Error())
			continue
		}
		outp.Textures[i] = &coreobjects.TextureBlock {
			Texture: texture,
			Offset: v.Offset,
		}
	}
	return outp
}

type ObjectTextureBlock struct {
	Name string
	TextureId *uint64
	Offset rl.Vector2
}

func (base *ObjectTextureBlock) GetTexture() (*rl.Texture2D, error) {
	if base.TextureId != nil {
		return components.Resources.Textures.GetTexture(*base.TextureId)
	}
	return components.Resources.Textures.GetTextureByName(base.Name)
}

func (base *ObjectDescriptor) String() string {
	var outp, jsonErr = json.Marshal(base)
	if jsonErr != nil {
		return fmt.Sprintf("Failed to parse settings: %s", jsonErr.Error())
	}
	return string(outp)
}