-
Notifications
You must be signed in to change notification settings - Fork 62
/
discrete_gradient_texture.gd
57 lines (43 loc) · 1.38 KB
/
discrete_gradient_texture.gd
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
tool
class_name DiscreteGradientTexture
extends ImageTexture
# author: Athrunen
# license: MIT
# description: Has the same functionality as the GradientTexture but does not interpolate colors.
# todos:
# - Write a more elegant way of updating the texture than changing the resolution.
# - Persuade Godot to repeat the texture vertically in the inspector.
export var resolution: int = 256 setget _update_resolution
export var gradient: Gradient = Gradient.new() setget _update_gradient
func _ready() -> void:
_update_texture()
func _update_texture() -> void:
var image := Image.new()
image.create(resolution, 1, false, Image.FORMAT_RGBA8)
if not gradient:
return
image.lock()
var last_offset := 0
var last_pixel := 0
var index := 0
for offset in gradient.offsets:
var amount := int(round((offset - last_offset) * resolution))
amount -= 1 if amount > 0 else 0
var color := gradient.colors[index]
for x in range(amount):
image.set_pixel(x + last_pixel, 0, color)
last_offset = offset
last_pixel = last_pixel + amount
index += 1
if last_pixel < resolution:
var color := gradient.colors[-1]
for x in resolution - last_pixel:
image.set_pixel(x + last_pixel, 0, color)
image.unlock()
self.create_from_image(image, 0)
func _update_gradient(g: Gradient) -> void:
gradient = g
_update_texture()
func _update_resolution(r: int) -> void:
resolution = r
_update_texture()