diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..37f05f2 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.import diff --git a/.import/.gdignore b/.import/.gdignore new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/.import/.gdignore @@ -0,0 +1 @@ + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e02a34e --- /dev/null +++ b/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2022 Mario Liebisch + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..93bebb3 --- /dev/null +++ b/README.md @@ -0,0 +1,7 @@ +# BackgroundWorker Node for Godot 3.x + +This is an example project for my `BackgroundWorker` node, which can be found in the `addons` sub directory. + +The latest version of the addon can be found in [my repository](https://github.com/MarioLiebisch/GD-BackgroundWorker). + +For more details sett the [actual readme file of the addon itself](./addons/BackgroundWorker/README.md). diff --git a/TestScene.gd b/TestScene.gd new file mode 100644 index 0000000..b435a20 --- /dev/null +++ b/TestScene.gd @@ -0,0 +1,23 @@ +extends Node2D + +func _process(delta: float) -> void: + $Icon.rotation_degrees += 180 * delta + + +func _on_BackgroundWorker_busy() -> void: + $Loading.visible = true + + +func _on_BackgroundWorker_free() -> void: + $Loading.visible = false + + +func _on_BackgroundWorker_progress(completed, total) -> void: + $Loading/ProgressBar.max_value = total + $Loading/ProgressBar.value = completed + +func _on_Button_pressed() -> void: + $BackgroundWorker.queue_job(self, "random_job", []) + +func random_job() -> void: + OS.delay_msec(rand_range(1000, 5000)) diff --git a/TestScene.tscn b/TestScene.tscn new file mode 100644 index 0000000..156350c --- /dev/null +++ b/TestScene.tscn @@ -0,0 +1,50 @@ +[gd_scene load_steps=4 format=2] + +[ext_resource path="res://icon.png" type="Texture" id=1] +[ext_resource path="res://TestScene.gd" type="Script" id=2] +[ext_resource path="res://addons/BackgroundWorker/BackgroundWorker.gd" type="Script" id=3] + +[node name="TestScene" type="Node2D"] +script = ExtResource( 2 ) + +[node name="Icon" type="Sprite" parent="."] +position = Vector2( 65, 66 ) +texture = ExtResource( 1 ) + +[node name="Loading" type="VBoxContainer" parent="."] +visible = false +margin_left = 156.0 +margin_top = 22.0 +margin_right = 379.0 +margin_bottom = 62.0 +__meta__ = { +"_edit_use_anchors_": false +} + +[node name="Label" type="Label" parent="Loading"] +margin_right = 223.0 +margin_bottom = 14.0 +text = "Loading..." + +[node name="ProgressBar" type="ProgressBar" parent="Loading"] +margin_top = 18.0 +margin_right = 223.0 +margin_bottom = 32.0 + +[node name="BackgroundWorker" type="Node" parent="."] +script = ExtResource( 3 ) + +[node name="Button" type="Button" parent="."] +margin_left = 34.0 +margin_top = 136.0 +margin_right = 214.0 +margin_bottom = 218.0 +text = "Do some WORK!" +__meta__ = { +"_edit_use_anchors_": false +} + +[connection signal="busy" from="BackgroundWorker" to="." method="_on_BackgroundWorker_busy"] +[connection signal="free" from="BackgroundWorker" to="." method="_on_BackgroundWorker_free"] +[connection signal="progress" from="BackgroundWorker" to="." method="_on_BackgroundWorker_progress"] +[connection signal="pressed" from="Button" to="." method="_on_Button_pressed"] diff --git a/addons/BackgroundWorker/BackgroundWorker.gd b/addons/BackgroundWorker/BackgroundWorker.gd new file mode 100644 index 0000000..1ecd028 --- /dev/null +++ b/addons/BackgroundWorker/BackgroundWorker.gd @@ -0,0 +1,110 @@ +extends Node + +## The minimum time in seconds the workers have to be busy for visibility to kick in +export var show_timeout = 0.250 + +## The mimium time in seconds the workers have to be idle for visibility to cease +export var hide_timeout = 0.500 + +## The number of worker threads to be used +export var worker_count = 2 + + +var visible = false +var jobs: Array +var start_time: float +var last_time: float +var running = 0 +var threads: Array +var active = false +var completed = 0 +var total = 0 + +## Triggered once work starts +signal started() +## Triggered once work is finished +signal finished(total) +## Triggered once UI hints should be shown +signal busy() +## Triggered once UI hints should be hidden +signal free() +## Triggered whenever progress updates +signal progress(completed, total) + +class BackgroundWorkerJob: + var target: Object + var method: String + var binds: Array + + ## Creates a new Background Worker Job + func _init(target: Object, method: String, binds: Array = []) -> void: + self.target = target + self.method = method + self.binds = binds + + ## Executes the job and returns true, if processing of the job is complete + func execute(_dummy: BackgroundWorkerJob = null) -> void: + target.callv(method, binds) + +## Queue up a member function call as a new job +func queue_job(target: Object, method: String, binds: Array = []) -> void: + jobs.append(BackgroundWorkerJob.new(target, method, binds)) + total += 1 + +## Queue up a resource load as a job +func queue_load(file: String, type_hint: String = '') -> void: + jobs.append(BackgroundWorkerJob.new(ResourceLoader, 'load', [file, type_hint])) + total += 1 + +## Clear all still unprocessed jobs +func clear_queue() -> void: + total -= len(jobs) + jobs.clear() + +## Return the number of queued jobs +func queue_length() -> int: + return len(jobs) + +func _process(_delta: float) -> void: + if active and not visible: + if OS.get_ticks_msec() / 1000.0 > start_time + show_timeout: + emit_signal('progress', completed, total) + emit_signal('busy') + visible = true + if len(jobs) > 0: + while len(threads) < worker_count: + threads.append(Thread.new()) + + if not active: + start_time = OS.get_ticks_msec() / 1000.0 + active = true + emit_signal('started') + var c = 0 + for i in worker_count: + c += 1 + if not threads[i].is_active(): + var job = jobs.front() + threads[i].start(job, 'execute', job) + jobs.pop_front() + running += 1 + break + last_time = OS.get_ticks_msec() / 1000.0 + emit_signal('progress', completed, total) + if running > 0: + var c = 0 + for thread in threads: + c += 1 + if thread.is_active() and not thread.is_alive(): + thread.wait_to_finish() + running -= 1 + completed += 1 + emit_signal('progress', completed, total) + if running == 0: + active = false + emit_signal('finished', total) + completed = 0 + total = 0 + last_time = OS.get_ticks_msec() / 1000.0 + elif not active and visible and OS.get_ticks_msec() / 1000.0 > last_time + hide_timeout: + emit_signal('free') + visible = false diff --git a/addons/BackgroundWorker/README.md b/addons/BackgroundWorker/README.md new file mode 100644 index 0000000..6199ec5 --- /dev/null +++ b/addons/BackgroundWorker/README.md @@ -0,0 +1,73 @@ +# BackgroundWorker Node for Godot 3.x + +This plugin provides a new node `BackgroundWorker` to make it easy to queue up and track background tasks. +This can be used to preload scenes, save games, synchronize or upload files, etc. + +All queued up jobs are processed by an adjustable amount of worker threads. +For strict linear processing "one after the other" you can reduce the number of active worker threads to one. + +Progress is reported back through signals, although hooked up functions can still trigger their own signals from their own thread in case you need it. + +## Installation + +The latest version of the addon can be found in [my repository](https://github.com/MarioLiebisch/GD-BackgroundWorker). + +As with any other Godot addon, put the contents of `addons/BackgroundWorker` in your own project's `addons` directory and make sure to enable it in Project Setting's "Plugins" tab. + +## Usage + +To queue up new jobs, call the member methods `queue_job(target, method, [binds])` or `queue_load(file, [type_hint]`). Processing starts automatically on the next frame. + +### Properties + +#### show_timeout [= 0.250] + +The minimum time in seconds the workers have to be busy for visibility to kick in. + +#### hide_timeout [= 0.500] + +The mimium time in seconds the workers have to be idle for visibility to cease + +#### worker_count [= 2] + +The number of worker threads to be used. + +### Methods + +#### queue_job(target: Object, method: String, binds: Array = []) -> void + +Queues a new job to call `method()` on `target` passing `binds` (if set). + +#### queue_load(file: String, type_hint: String = '') -> void + +Queues loading a file using Godot's `load()`, passing the optional `type_hint` (if set). + +#### clear_queue() -> void + +Remove/cancel any queued job not yet started. + +#### queue_length() -> int + +Return the number of queued jobs not yet started. + +### Signals + +#### started() + +Triggered as soon as the first job starts processing. + +#### finished(total: int) + +Triggered once all queued up jobs have finished processing. + +#### busy() + +Triggered once busy longer than defined in `show_timeout` to show a visible indicator. + +#### free() + +Triggered once all queued up jobs have finished and the timeout defined in `hide_timeout` has passed to hide indicators. + +#### progress(completed: int, total: int) + +Triggered whenever progress is made. This can be used to show relative progress to the user. diff --git a/addons/BackgroundWorker/icon.png b/addons/BackgroundWorker/icon.png new file mode 100644 index 0000000..efd12ce Binary files /dev/null and b/addons/BackgroundWorker/icon.png differ diff --git a/addons/BackgroundWorker/icon.png.import b/addons/BackgroundWorker/icon.png.import new file mode 100644 index 0000000..946ca15 --- /dev/null +++ b/addons/BackgroundWorker/icon.png.import @@ -0,0 +1,35 @@ +[remap] + +importer="texture" +type="StreamTexture" +path="res://.import/icon.png-186ed922af3136db90886735a2a3fca0.stex" +metadata={ +"vram_texture": false +} + +[deps] + +source_file="res://addons/BackgroundWorker/icon.png" +dest_files=[ "res://.import/icon.png-186ed922af3136db90886735a2a3fca0.stex" ] + +[params] + +compress/mode=0 +compress/lossy_quality=0.7 +compress/hdr_mode=0 +compress/bptc_ldr=0 +compress/normal_map=0 +flags/repeat=0 +flags/filter=true +flags/mipmaps=false +flags/anisotropic=false +flags/srgb=2 +process/fix_alpha_border=true +process/premult_alpha=false +process/HDR_as_SRGB=false +process/invert_color=false +process/normal_map_invert_y=false +stream=false +size_limit=0 +detect_3d=true +svg/scale=1.0 diff --git a/addons/BackgroundWorker/plugin.cfg b/addons/BackgroundWorker/plugin.cfg new file mode 100644 index 0000000..72e3335 --- /dev/null +++ b/addons/BackgroundWorker/plugin.cfg @@ -0,0 +1,7 @@ +[plugin] + +name="Background Worker" +description="A simple node utilizing a pool of worker threads to perform tasks in background, reporting progress, and allowing you to hook up UI markers or progress bars to keep the user up to date.." +author="Mario Liebisch" +version="0.5" +script="plugin.gd" diff --git a/addons/BackgroundWorker/plugin.gd b/addons/BackgroundWorker/plugin.gd new file mode 100644 index 0000000..478c8f7 --- /dev/null +++ b/addons/BackgroundWorker/plugin.gd @@ -0,0 +1,8 @@ +tool +extends EditorPlugin + +func _enter_tree() -> void: + add_custom_type("BackgroundWorker", "Node", preload("BackgroundWorker.gd"), preload("icon.png")) + +func _exit_tree() -> void: + remove_custom_type("BackgroundWorker") diff --git a/default_env.tres b/default_env.tres new file mode 100644 index 0000000..20207a4 --- /dev/null +++ b/default_env.tres @@ -0,0 +1,7 @@ +[gd_resource type="Environment" load_steps=2 format=2] + +[sub_resource type="ProceduralSky" id=1] + +[resource] +background_mode = 2 +background_sky = SubResource( 1 ) diff --git a/icon.png b/icon.png new file mode 100644 index 0000000..c98fbb6 Binary files /dev/null and b/icon.png differ diff --git a/icon.png.import b/icon.png.import new file mode 100644 index 0000000..a4c02e6 --- /dev/null +++ b/icon.png.import @@ -0,0 +1,35 @@ +[remap] + +importer="texture" +type="StreamTexture" +path="res://.import/icon.png-487276ed1e3a0c39cad0279d744ee560.stex" +metadata={ +"vram_texture": false +} + +[deps] + +source_file="res://icon.png" +dest_files=[ "res://.import/icon.png-487276ed1e3a0c39cad0279d744ee560.stex" ] + +[params] + +compress/mode=0 +compress/lossy_quality=0.7 +compress/hdr_mode=0 +compress/bptc_ldr=0 +compress/normal_map=0 +flags/repeat=0 +flags/filter=true +flags/mipmaps=false +flags/anisotropic=false +flags/srgb=2 +process/fix_alpha_border=true +process/premult_alpha=false +process/HDR_as_SRGB=false +process/invert_color=false +process/normal_map_invert_y=false +stream=false +size_limit=0 +detect_3d=true +svg/scale=1.0 diff --git a/project.godot b/project.godot new file mode 100644 index 0000000..bb80657 --- /dev/null +++ b/project.godot @@ -0,0 +1,27 @@ +; Engine configuration file. +; It's best edited using the editor UI and not directly, +; since the parameters that go here are not all obvious. +; +; Format: +; [section] ; section goes between [] +; param=value ; assign values to parameters + +config_version=4 + +[application] + +config/name="GD-BackgroundWorker" +run/main_scene="res://TestScene.tscn" +config/icon="res://icon.png" + +[editor_plugins] + +enabled=PoolStringArray( "res://addons/BackgroundWorker/plugin.cfg" ) + +[physics] + +common/enable_pause_aware_picking=true + +[rendering] + +environment/default_environment="res://default_env.tres"