2021-11-25 12:48:30 +00:00
|
|
|
class_name ShaderImageEffect
|
|
|
|
extends Reference
|
2021-04-21 12:31:33 +00:00
|
|
|
# Helper class to generate image effects using shaders
|
|
|
|
signal done
|
|
|
|
|
2021-11-25 12:48:30 +00:00
|
|
|
|
2021-12-01 01:04:40 +00:00
|
|
|
func generate_image(img: Image, shader: Shader, params: Dictionary, size: Vector2) -> void:
|
|
|
|
img.unlock()
|
2022-01-06 23:49:22 +00:00
|
|
|
# duplicate shader before modifying code to avoid affecting original resource
|
|
|
|
shader = shader.duplicate()
|
2021-12-30 16:05:28 +00:00
|
|
|
shader.code = shader.code.replace("unshaded", "unshaded, blend_premul_alpha")
|
2021-12-26 22:08:06 +00:00
|
|
|
var vp := VisualServer.viewport_create()
|
|
|
|
var canvas := VisualServer.canvas_create()
|
2021-04-21 12:31:33 +00:00
|
|
|
VisualServer.viewport_attach_canvas(vp, canvas)
|
|
|
|
VisualServer.viewport_set_size(vp, size.x, size.y)
|
|
|
|
VisualServer.viewport_set_disable_3d(vp, true)
|
|
|
|
VisualServer.viewport_set_usage(vp, VisualServer.VIEWPORT_USAGE_2D)
|
|
|
|
VisualServer.viewport_set_active(vp, true)
|
|
|
|
VisualServer.viewport_set_transparent_background(vp, true)
|
|
|
|
|
2021-12-26 22:08:06 +00:00
|
|
|
var ci_rid := VisualServer.canvas_item_create()
|
2021-04-21 12:31:33 +00:00
|
|
|
VisualServer.viewport_set_canvas_transform(vp, canvas, Transform())
|
|
|
|
VisualServer.canvas_item_set_parent(ci_rid, canvas)
|
2021-12-26 22:08:06 +00:00
|
|
|
var texture := VisualServer.texture_create_from_image(img, 0)
|
|
|
|
VisualServer.canvas_item_add_texture_rect(ci_rid, Rect2(Vector2.ZERO, size), texture)
|
2021-04-21 12:31:33 +00:00
|
|
|
|
2021-12-26 22:08:06 +00:00
|
|
|
var mat_rid := VisualServer.material_create()
|
2021-04-21 12:31:33 +00:00
|
|
|
VisualServer.material_set_shader(mat_rid, shader.get_rid())
|
|
|
|
VisualServer.canvas_item_set_material(ci_rid, mat_rid)
|
2021-12-01 01:04:40 +00:00
|
|
|
for key in params:
|
|
|
|
VisualServer.material_set_param(mat_rid, key, params[key])
|
2021-04-21 12:31:33 +00:00
|
|
|
|
|
|
|
VisualServer.viewport_set_update_mode(vp, VisualServer.VIEWPORT_UPDATE_ONCE)
|
|
|
|
VisualServer.viewport_set_vflip(vp, true)
|
|
|
|
VisualServer.force_draw(false)
|
2021-12-26 22:08:06 +00:00
|
|
|
var viewport_texture := Image.new()
|
2021-04-21 12:31:33 +00:00
|
|
|
viewport_texture = VisualServer.texture_get_data(VisualServer.viewport_get_texture(vp))
|
|
|
|
VisualServer.free_rid(vp)
|
|
|
|
VisualServer.free_rid(canvas)
|
|
|
|
VisualServer.free_rid(ci_rid)
|
|
|
|
VisualServer.free_rid(mat_rid)
|
2021-12-26 22:08:06 +00:00
|
|
|
VisualServer.free_rid(texture)
|
2021-04-21 12:31:33 +00:00
|
|
|
viewport_texture.convert(Image.FORMAT_RGBA8)
|
2021-12-01 01:04:40 +00:00
|
|
|
img.copy_from(viewport_texture)
|
2021-04-21 12:31:33 +00:00
|
|
|
emit_signal("done")
|