rj-action-library/Runtime/Procedural/Baking/Baker.cs

110 lines
2.2 KiB
C#
Raw Permalink Normal View History

2024-12-01 17:07:41 +00:00
using System.Collections;
using System.Collections.Generic;
using Godot;
using System;
namespace Rokojori
{
[Tool]
[GlobalClass]
public partial class Baker:Node
{
2025-04-08 09:07:02 +00:00
[ExportToolButton( "Update")]
public Callable BakeButton => Callable.From( () => Bake() );
2024-12-01 17:07:41 +00:00
[Export]
public bool updateAlways = false;
2025-04-08 09:07:02 +00:00
[ExportGroup( "View") ]
2024-12-01 17:07:41 +00:00
[Export]
2025-04-08 09:07:02 +00:00
public BakingViewSettings viewSettings = new BakingViewSettings();
2024-12-01 17:07:41 +00:00
[Export]
2025-04-08 09:07:02 +00:00
public Viewport viewport;
2024-12-01 17:07:41 +00:00
[Export]
2025-04-08 09:07:02 +00:00
public Camera3D camera;
2024-12-01 17:07:41 +00:00
2025-04-08 09:07:02 +00:00
[ExportGroup( "Target")]
2024-12-01 17:07:41 +00:00
[Export]
2025-04-08 09:07:02 +00:00
public Node3D target;
2024-12-01 17:07:41 +00:00
[Export]
2025-04-08 09:07:02 +00:00
public Vector3 targetPivot;
2024-12-01 17:07:41 +00:00
[Export]
2025-04-08 09:07:02 +00:00
public bool autoTargetPivot = true;
2024-12-01 17:07:41 +00:00
2025-04-08 09:07:02 +00:00
[ExportGroup( "Output")]
2024-12-01 17:07:41 +00:00
[Export]
public Node3D outputTexture;
[Export]
2025-04-08 09:07:02 +00:00
public float outputScale = 1;
2025-01-03 12:09:23 +00:00
2024-12-01 17:07:41 +00:00
[Export]
2025-04-08 09:07:02 +00:00
public float outputTextureSize = 1;
2024-12-01 17:07:41 +00:00
public static Baker Create( Node parent, Node3D target, Vector2I size, string name )
{
var bakingView = parent.CreateChild<SubViewport>( "Viewport " + name );
bakingView.TransparentBg = true;
bakingView.Size = size;
var bakingCamera = bakingView.CreateChild<Camera3D>( "Camera View " + name );
var baker = bakingView.CreateChild<Baker>( "Baker " + name );
baker.camera = bakingCamera;
baker.target = target;
baker.viewport = bakingView;
return baker;
}
2024-12-01 17:07:41 +00:00
public override void _Process( double delta )
{
2025-04-08 09:07:02 +00:00
if ( ! updateAlways )
2024-12-01 17:07:41 +00:00
{
return;
}
Bake();
}
2025-04-08 09:07:02 +00:00
public void Bake()
2024-12-01 17:07:41 +00:00
{
if ( viewport == null || target == null || camera == null )
{
return;
}
2025-04-08 09:07:02 +00:00
if ( autoTargetPivot )
2024-12-01 17:07:41 +00:00
{
2025-04-08 09:07:02 +00:00
Box3 box = target.GetWorldBounds();
targetPivot = new Vector3( 0, -box.center.Y, 0 );
2024-12-01 17:07:41 +00:00
}
2025-04-08 09:07:02 +00:00
viewSettings.ApplySettings( camera, target, targetPivot );
var outputScale = Cameras.ComputeCameraFittingScale( camera.Fov, viewSettings._XX_ComputedDistance );
2024-12-01 17:07:41 +00:00
if ( outputTexture != null )
{
outputTexture.Scale = Vector3.One * outputScale;
2025-04-08 09:07:02 +00:00
outputTexture.GlobalPosition = target.GlobalPosition - targetPivot;
2024-12-01 17:07:41 +00:00
}
}
}
}