summaryrefslogtreecommitdiffstats
path: root/world/chunk/ChunkGen.gd
blob: 75d37365c4911178c4da2d1d97191b2300df9297 (plain) (blame)
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
79
extends Node

var chunk_half_size setget _set_chunk_size
var chunk_size

func _set_chunk_size(val):
    chunk_half_size = val
    chunk_size = val * 2.0

onready var noise = OpenSimplexNoise.new()
onready var rng = RandomNumberGenerator.new()
var _seed

func _ready():
    #randomize()
    #self._seed = randi()
    self._seed = 0
    self.noise.seed = self._seed
    self.noise.seed = 0
    self.noise.period = 16
    self.noise.persistence = 0
    self.rng.seed = self._seed

func rng_2dv(coords:Vector2):
    self.rng.seed = hash(coords)

func gen_chunk(chunk):
    var gen_tree = Spatial.new()
    gen_tree.name = "gen_tree"
    chunk.add_child(gen_tree)
    gen_rocks(chunk)

func v2_coords(coords:Vector3):
    return Vector2(coords.x,coords.z)

func v3_coords(coords:Vector2):
    return Vector3(coords.x,0.0,coords.y)

func iterate_chunk(chunk,step:Vector2,cb:FuncRef):
    var chunk_size_rounded = Vector2(chunk_half_size,chunk_half_size).snapped(step)
    for x in range(-chunk_size_rounded.x,chunk_size_rounded.x,step.x):
        for y in range(-chunk_size_rounded.y,chunk_size_rounded.y,step.y):
            cb.call_func(chunk,Vector2(x,y))

var rock_mesh = preload("res://world/obstacles/Rock_mesh.tres")
var rock_mat = preload("res://world/obstacles/Rock_mat.tres")
func make_rock(chunk,chunk_coords:Vector2):
    var coords = v3_coords(chunk_coords)
    var basis = Basis()
    var world_coords = chunk_coords + v2_coords(chunk.transform.origin)
    self.rng_2dv(world_coords)
    var rng_val = self.rng.randf_range(0.0,TAU)
    basis = Basis(Vector3.UP,rng_val) * basis
    var noise_val = self.noise.get_noise_2dv(world_coords * 0.125)
    if noise_val < 0.4:
        return
    noise_val = min(noise_val,0.6)
    noise_val -= 0.4
    noise_val /= 0.2
    noise_val = lerp(1.0,4.0,noise_val)
    basis = basis.scaled(Vector3.ONE*noise_val)
    coords.y += (noise_val*5.0)-5.0
    var gen_tree = chunk.get_node("gen_tree")
    var rocks = gen_tree.get_node("rocks").multimesh
    rocks.visible_instance_count += 1
    rocks.set_instance_transform(rocks.visible_instance_count-1, Transform(basis,coords))

func gen_rocks(chunk):
    var multi_inst = MultiMeshInstance.new()
    multi_inst.name = "rocks"
    var multi = MultiMesh.new()
    multi_inst.multimesh = multi
    chunk.get_node("gen_tree").add_child(multi_inst)
    multi.transform_format = MultiMesh.TRANSFORM_3D
    multi.instance_count = 1000
    multi.visible_instance_count = 0
    multi.mesh = rock_mesh
    rock_mesh.material = rock_mat
    iterate_chunk(chunk, Vector2(10.0,10.0), funcref(self,"make_rock"))