Added display of editor camera position #368

Merged
srishamharan merged 6 commits from SP3-4-Editor into main 2023-02-27 11:59:58 +08:00
95 changed files with 2913 additions and 999 deletions
Showing only changes of commit fbd0035ade - Show all commits

View File

@ -1,4 +1,4 @@
Start in Fullscreen: false Start in Fullscreen: false
Starting Scene ID: 97086054 Starting Scene ID: 86098106
Window Size: {x: 1920, y: 1080} Window Size: {x: 1920, y: 1080}
Window Title: SHADE Engine Window Title: SHADE Engine

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -1,10 +1,10 @@
0 1 0000000000000000 0 StaticObject 1110000000000000
1 2 0000000000000000 1 Player 1100000000000000
2 3 0000000000000000 2 Food 1000000000000000
3 4 0000000000000000 3 Breakable 1100000000000000
4 5 0000000000000000 4 ScoringWallCollider 0110000000000000
5 6 0000000000000000 5 Homeowner 1100000000000000
6 7 0000000000000000 6 Camera 0010000000000000
7 8 0000000000000000 7 8 0000000000000000
8 9 0000000000000000 8 9 0000000000000000
9 10 0000000000000000 9 10 0000000000000000

View File

@ -1,4 +1,4 @@
Start Maximized: true Start Maximized: true
Working Scene ID: 91685359 Working Scene ID: 97158628
Window Size: {x: 1920, y: 1013} Window Size: {x: 1920, y: 1013}
Style: 0 Style: 0

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -6,6 +6,7 @@
Canvas Component: Canvas Component:
Canvas Width: 1920 Canvas Width: 1920
Canvas Height: 1080 Canvas Height: 1080
Scale by canvas width: false
IsActive: true IsActive: true
Scripts: ~ Scripts: ~
- EID: 1 - EID: 1
@ -24,6 +25,8 @@
IsActive: true IsActive: true
UI Component: UI Component:
Canvas ID: 0 Canvas ID: 0
Hovered: false
Clicked: false
IsActive: true IsActive: true
Scripts: ~ Scripts: ~
- EID: 5 - EID: 5
@ -47,6 +50,8 @@
IsActive: true IsActive: true
UI Component: UI Component:
Canvas ID: 0 Canvas ID: 0
Hovered: false
Clicked: false
IsActive: true IsActive: true
Scripts: Scripts:
- Type: ChangeSceneButton - Type: ChangeSceneButton
@ -73,6 +78,8 @@
IsActive: true IsActive: true
UI Component: UI Component:
Canvas ID: 0 Canvas ID: 0
Hovered: false
Clicked: false
IsActive: true IsActive: true
Scripts: Scripts:
- Type: QuitButton - Type: QuitButton
@ -106,11 +113,12 @@
Pitch: 0 Pitch: 0
Yaw: 0 Yaw: 0
Roll: 0 Roll: 0
Width: 1920 Width: 1319
Height: 1080 Height: 622
Near: 0.00999999978 Near: 0.00999999978
Far: 10000 Far: 10000
Perspective: true Perspective: true
FOV: 90
IsActive: true IsActive: true
Scripts: ~ Scripts: ~
- EID: 4 - EID: 4

View File

@ -1,18 +1,18 @@
- EID: 0 - EID: 0
Name: Default Name: Player
IsActive: true IsActive: true
NumberOfChildren: 0 NumberOfChildren: 0
Components: Components:
Transform Component: Transform Component:
Translate: {x: 0, y: 7, z: 0} Translate: {x: 0, y: 7, z: 0}
Rotate: {x: 0, y: 0, z: 0} Rotate: {x: 1.48352981, y: 0, z: 0}
Scale: {x: 0.999999344, y: 0.999999821, z: 0.999999523} Scale: {x: 0.999999344, y: 0.999999821, z: 0.999999523}
IsActive: true IsActive: true
RigidBody Component: RigidBody Component:
Type: Dynamic Type: Dynamic
Drag: 0.00999999978 Drag: 0.00999999978
Angular Drag: 0.100000001 Angular Drag: 0.100000001
Use Gravity: false Use Gravity: true
Interpolate: false Interpolate: false
Sleeping Enabled: true Sleeping Enabled: true
Freeze Position X: false Freeze Position X: false
@ -25,7 +25,7 @@
Collider Component: Collider Component:
Colliders: Colliders:
- Is Trigger: false - Is Trigger: false
Collision Tag: 2 Collision Tag: 0
Type: Box Type: Box
Half Extents: {x: 1, y: 1, z: 1} Half Extents: {x: 1, y: 1, z: 1}
Friction: 0.400000006 Friction: 0.400000006
@ -39,6 +39,8 @@
Enabled: true Enabled: true
forceAmount: 50 forceAmount: 50
torqueAmount: 500 torqueAmount: 500
- Type: CollisionTest
Enabled: true
- EID: 1 - EID: 1
Name: Default Name: Default
IsActive: true IsActive: true
@ -52,7 +54,7 @@
Collider Component: Collider Component:
Colliders: Colliders:
- Is Trigger: false - Is Trigger: false
Collision Tag: 5 Collision Tag: 0
Type: Box Type: Box
Half Extents: {x: 1, y: 1, z: 1} Half Extents: {x: 1, y: 1, z: 1}
Friction: 0.400000006 Friction: 0.400000006
@ -161,7 +163,7 @@
Collider Component: Collider Component:
Colliders: Colliders:
- Is Trigger: false - Is Trigger: false
Collision Tag: 7 Collision Tag: 2
Type: Box Type: Box
Half Extents: {x: 1, y: 1, z: 1} Half Extents: {x: 1, y: 1, z: 1}
Friction: 0.400000006 Friction: 0.400000006
@ -208,3 +210,26 @@
Rotation Offset: {x: 0, y: 0, z: 0} Rotation Offset: {x: 0, y: 0, z: 0}
IsActive: true IsActive: true
Scripts: ~ Scripts: ~
- EID: 8
Name: Target
IsActive: true
NumberOfChildren: 0
Components:
Transform Component:
Translate: {x: 8, y: 7, z: 0}
Rotate: {x: -0, y: 0, z: -0}
Scale: {x: 1, y: 1, z: 1}
IsActive: true
Collider Component:
Colliders:
- Is Trigger: false
Collision Tag: 0
Type: Box
Half Extents: {x: 1, y: 1, z: 1}
Friction: 0.400000006
Bounciness: 0
Density: 1
Position Offset: {x: 0, y: 0, z: 0}
Rotation Offset: {x: 0, y: 0, z: 0}
IsActive: true
Scripts: ~

View File

@ -36,6 +36,9 @@
Mesh: 141771688 Mesh: 141771688
Material: 129138332 Material: 129138332
IsActive: true IsActive: true
UI Component:
Canvas ID: 1
IsActive: true
Scripts: ~ Scripts: ~
- EID: 5 - EID: 5
Name: Main Menu Button Name: Main Menu Button
@ -56,6 +59,9 @@
Hovered Texture: 55999018 Hovered Texture: 55999018
Clicked Texture: 66382894 Clicked Texture: 66382894
IsActive: true IsActive: true
UI Component:
Canvas ID: 1
IsActive: true
Scripts: Scripts:
- Type: ChangeSceneButton - Type: ChangeSceneButton
Enabled: true Enabled: true
@ -79,6 +85,9 @@
Hovered Texture: 65045286 Hovered Texture: 65045286
Clicked Texture: 58607560 Clicked Texture: 58607560
IsActive: true IsActive: true
UI Component:
Canvas ID: 1
IsActive: true
Scripts: Scripts:
- Type: QuitButton - Type: QuitButton
Enabled: true Enabled: true

View File

@ -0,0 +1,31 @@
using SHADE;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SHADE_Scripting.Audio
{
public static class AudioHandler
{
public static Dictionary<string, AudioClipHandler> audioClipHandlers = new Dictionary<string, AudioClipHandler>();
//Functions here, maybe
public static void stopAllSounds(bool fadeOut)
{
foreach (KeyValuePair<string, AudioClipHandler> h in audioClipHandlers)
{
h.Value.Stop(fadeOut);
}
}
public static void pauseAllSounds(bool pause)
{
foreach (KeyValuePair<string, AudioClipHandler> h in audioClipHandlers)
{
h.Value.SetPause(pause);
}
}
}
}

View File

@ -0,0 +1,3 @@
Name: AudioHandler
ID: 159235425
Type: 9

View File

@ -14,6 +14,7 @@
using SHADE; using SHADE;
using SHADE_Scripting.AIBehaviour.BehaviourTree; using SHADE_Scripting.AIBehaviour.BehaviourTree;
using SHADE_Scripting.Audio;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -99,6 +100,17 @@ public partial class Homeowner1 : BehaviourTree
SetData("turningSpeed", turningSpeed); SetData("turningSpeed", turningSpeed);
SetData("distanceToCapture", distanceToCapture); SetData("distanceToCapture", distanceToCapture);
SetData("baseCaptureTime", captureTime);*/ SetData("baseCaptureTime", captureTime);*/
//These should be somewhere else
//Debug.Log("TESTING");
AudioHandler.audioClipHandlers["BGMUnalert"] = Audio.CreateAudioClip("event:/Music/player_undetected");
AudioHandler.audioClipHandlers["BGMAlert"] = Audio.CreateAudioClip("event:/Music/player_detected");
AudioHandler.audioClipHandlers["BGMAdaptive"] = Audio.CreateAudioClip("event:/Music/bgm_adaptive");
AudioHandler.audioClipHandlers["SFXFootstep"] = Audio.CreateAudioClip("event:/Homeowner/homeowner_footsteps");
AudioHandler.audioClipHandlers["SFXDetectAh"] = Audio.CreateAudioClip("event:/Homeowner/homeowner_detect_raccoon");
AudioHandler.audioClipHandlers["SFXDetectSting"] = Audio.CreateAudioClip("event:/Music/stingers/player_detected");
} }
//Called every tick //Called every tick
@ -132,7 +144,6 @@ public partial class Homeowner1 : BehaviourTree
if (GetData("baseCaptureTime") == null || (float)GetData("baseCaptureTime") != captureTime) if (GetData("baseCaptureTime") == null || (float)GetData("baseCaptureTime") != captureTime)
SetData("baseCaptureTime", captureTime); SetData("baseCaptureTime", captureTime);
events.Tick(); events.Tick();
//Footsteps SFX, move them somewhere else soon //Footsteps SFX, move them somewhere else soon
@ -141,7 +152,8 @@ public partial class Homeowner1 : BehaviourTree
footstepTimeRemaining -= velocity * Time.DeltaTimeF; footstepTimeRemaining -= velocity * Time.DeltaTimeF;
if (footstepTimeRemaining < 0.0f) if (footstepTimeRemaining < 0.0f)
{ {
Audio.PlaySFXOnce2D("event:/Homeowner/homeowner_footsteps"); //Audio.PlaySFXOnce2D("event:/Homeowner/homeowner_footsteps");
//AudioHandler.audioClipHandlers["SFXFootstep"].Play();
footstepTimeRemaining = footstepSFXIntervalMultiplier; footstepTimeRemaining = footstepSFXIntervalMultiplier;
} }
//Debug.Log("Ticked"); //Debug.Log("Ticked");

View File

@ -11,6 +11,7 @@
using SHADE; using SHADE;
using SHADE_Scripting.AIBehaviour.BehaviourTree; using SHADE_Scripting.AIBehaviour.BehaviourTree;
using SHADE_Scripting.Audio;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -111,7 +112,9 @@ public partial class LeafChase : BehaviourTreeNode
if (GetNodeData("isAlert") != null && (bool)GetNodeData("isAlert") == true) if (GetNodeData("isAlert") != null && (bool)GetNodeData("isAlert") == true)
{ {
Audio.PlaySFXOnce2D("event:/Homeowner/humming"); //AudioHandler.audioClipHandlers["BGMAdpative"].SetParameter("Detected", 0.0f);
Audio.SetParameter("Detected", 0.0f);
AudioHandler.audioClipHandlers["SFXHumming"].Play();
} }
SetNodeData("isAlert", false); SetNodeData("isAlert", false);

View File

@ -11,6 +11,7 @@
using SHADE; using SHADE;
using SHADE_Scripting.AIBehaviour.BehaviourTree; using SHADE_Scripting.AIBehaviour.BehaviourTree;
using SHADE_Scripting.Audio;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -239,9 +240,12 @@ public partial class LeafPatrol : BehaviourTreeNode
if (GetNodeData("isAlert") != null && (bool)GetNodeData("isAlert")) if (GetNodeData("isAlert") != null && (bool)GetNodeData("isAlert"))
{ {
//Debug.Log("Unalert"); //Debug.Log("Unalert");
Audio.PlaySFXOnce2D("event:/Homeowner/humming"); //AudioHandler.audioClipHandlers["BGMAlert"].Stop(true);
Audio.StopAllSounds(); //Audio.PlaySFXOnce2D("event:/Homeowner/humming");
Audio.PlayBGMOnce2D("event:/Music/player_undetected"); AudioHandler.audioClipHandlers["SFXHumming"].Play();
//AudioHandler.audioClipHandlers["BGMUnalert"].Play();
//AudioHandler.audioClipHandlers["BGMAdaptive"].SetParameter("Detected", 0.0f);
Audio.SetParameter("Detected", 0.0f);
} }
SetNodeData("isAlert", false); SetNodeData("isAlert", false);
} }

View File

@ -11,6 +11,7 @@
using SHADE; using SHADE;
using SHADE_Scripting.AIBehaviour.BehaviourTree; using SHADE_Scripting.AIBehaviour.BehaviourTree;
using SHADE_Scripting.Audio;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -65,7 +66,9 @@ public partial class LeafSearch : BehaviourTreeNode
{ {
if (GetNodeData("isAlert") != null && (bool)GetNodeData("isAlert") == true) if (GetNodeData("isAlert") != null && (bool)GetNodeData("isAlert") == true)
{ {
Audio.PlaySFXOnce2D("event:/Homeowner/humming"); //AudioHandler.audioClipHandlers["BGMAdaptive"].SetParameter("Detected", 0.0f);
Audio.SetParameter("Detected", 0.0f);
AudioHandler.audioClipHandlers["SFXHumming"].Play();
reevaluateWaypoint(); reevaluateWaypoint();
} }
SetNodeData("isAlert", false); SetNodeData("isAlert", false);
@ -185,19 +188,27 @@ public partial class LeafSearch : BehaviourTreeNode
if (GetNodeData("isAlert") == null) if (GetNodeData("isAlert") == null)
{ {
SetNodeData("isAlert", true); SetNodeData("isAlert", true);
Audio.PlaySFXOnce2D("event:/Homeowner/homeowner_detect_raccoon"); //Audio.StopAllSounds();
Audio.PlaySFXOnce2D("event:/Music/stingers/player_detected"); AudioHandler.audioClipHandlers["SFXDetectAh"].Play();
Audio.StopAllSounds(); AudioHandler.audioClipHandlers["SFXDetectSting"].Play();
Audio.PlayBGMOnce2D("event:/Music/player_detected"); //AudioHandler.audioClipHandlers["BGMAlert"].Play();
AudioHandler.audioClipHandlers["SFXHumming"].Stop(false);
//AudioHandler.audioClipHandlers["BGMUnalert"].Stop(true);
//AudioHandler.audioClipHandlers["BGMAdaptive"].SetParameter("Detected", 1.0f);
Audio.SetParameter("Detected", 1.0f);
} }
else else
{ {
if (GetNodeData("isAlert") != null && (bool)GetNodeData("isAlert") == false) if (GetNodeData("isAlert") != null && (bool)GetNodeData("isAlert") == false)
{ {
Audio.PlaySFXOnce2D("event:/Homeowner/homeowner_detect_raccoon"); //Audio.StopAllSounds();
Audio.PlaySFXOnce2D("event:/Music/stingers/player_detected"); AudioHandler.audioClipHandlers["SFXDetectAh"].Play();
Audio.StopAllSounds(); AudioHandler.audioClipHandlers["SFXDetectSting"].Play();
Audio.PlayBGMOnce2D("event:/Music/player_detected"); //AudioHandler.audioClipHandlers["BGMAlert"].Play();
AudioHandler.audioClipHandlers["SFXHumming"].Stop(false);
//AudioHandler.audioClipHandlers["BGMUnalert"].Stop(true);
//AudioHandler.audioClipHandlers["BGMAdaptive"].SetParameter("Detected", 1.0f);
Audio.SetParameter("Detected", 1.0f);
} }
SetNodeData("isAlert", true); SetNodeData("isAlert", true);
} }

View File

@ -1,4 +1,5 @@
using SHADE; using SHADE;
using SHADE_Scripting.Audio;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
@ -30,6 +31,8 @@ public class Breakable : Script
} }
isBreak = false; isBreak = false;
AudioHandler.audioClipHandlers["SFXBreak"] = Audio.CreateAudioClip("event:/Props/impact_break");
} }
protected override void update() protected override void update()
@ -43,6 +46,7 @@ public class Breakable : Script
if (ignoreRaccoon && info.GameObject.GetScript<PlayerController>()) if (ignoreRaccoon && info.GameObject.GetScript<PlayerController>())
return; return;
if (rb.LinearVelocity.GetSqrMagnitude() > threshHold && !info.GameObject.GetScript<PlayerController>()) if (rb.LinearVelocity.GetSqrMagnitude() > threshHold && !info.GameObject.GetScript<PlayerController>())
{ {
isBreak = true; isBreak = true;
@ -68,7 +72,7 @@ public class Breakable : Script
} }
isBreak = false; isBreak = false;
Audio.PlaySFXOnce2D("event:/Props/impact_break"); AudioHandler.audioClipHandlers["SFXBreak"].Play();
GameObject.SetActive(false); GameObject.SetActive(false);
} }
} }

View File

@ -1,4 +1,5 @@
using SHADE; using SHADE;
using SHADE_Scripting.Audio;
using System; using System;
public class Item : Script public class Item : Script
{ {
@ -14,6 +15,7 @@ public class Item : Script
public ItemCategory currCategory; public ItemCategory currCategory;
public bool returnBack { get; set; } public bool returnBack { get; set; }
private Transform transform; private Transform transform;
private RigidBody rb;
private bool playSound = false; private bool playSound = false;
private bool caputurePos = false; private bool caputurePos = false;
private Vector3 firstPostion; private Vector3 firstPostion;
@ -21,14 +23,19 @@ public class Item : Script
public float density = 1.0f; public float density = 1.0f;
public bool dontReturn = false; public bool dontReturn = false;
protected override void awake() protected override void awake()
{ {
transform = GetComponent<Transform>(); transform = GetComponent<Transform>();
rb = GetComponent<RigidBody>();
collider = GetComponent<Collider>(); collider = GetComponent<Collider>();
if(collider) if(collider)
collider.GetCollisionShape(0).Density = density; collider.GetCollisionShape(0).Density = density;
returnBack = false; returnBack = false;
AudioHandler.audioClipHandlers["SFXImpactElastic"] = Audio.CreateAudioClip("event:/Props/impact_elastic");
AudioHandler.audioClipHandlers["SFXImpactHard"] = Audio.CreateAudioClip("event:/Props/impact_hard");
} }
protected override void start() protected override void start()
@ -40,7 +47,12 @@ public class Item : Script
{ {
if (returnBack && !dontReturn) if (returnBack && !dontReturn)
{ {
if(transform)
transform.LocalPosition = firstPostion; transform.LocalPosition = firstPostion;
if (rb)
rb.LinearVelocity = Vector3.Zero;
returnBack = false; returnBack = false;
} }
} }
@ -55,14 +67,14 @@ public class Item : Script
if (playSound) if (playSound)
{ {
if(currCategory == ItemCategory.LIGHT) if (currCategory == ItemCategory.LIGHT)
Audio.PlaySFXOnce2D("event:/Props/impact_elastic"); AudioHandler.audioClipHandlers["SFXImpactElastic"].Play();
else if (currCategory == ItemCategory.MEDIUM || currCategory == ItemCategory.HEAVY) else if (currCategory == ItemCategory.MEDIUM || currCategory == ItemCategory.HEAVY)
Audio.PlaySFXOnce2D("event:/Props/impact_hard"); AudioHandler.audioClipHandlers["SFXImpactHard"].Play();
playSound = false; playSound = false;
} }
if (info.GameObject.GetScript<Homeowner1>()) if (info.GameObject.GetScript<Homeowner1>() && !returnBack)
{ {
returnBack = true; returnBack = true;
} }

View File

@ -1,5 +1,6 @@
using SHADE; using SHADE;
using SHADE_Scripting; using SHADE_Scripting;
using SHADE_Scripting.Audio;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using static PlayerController; using static PlayerController;
@ -7,7 +8,7 @@ using static Item;
public class PickAndThrow : Script public class PickAndThrow : Script
{ {
public Vector3 throwForce = new Vector3(100.0f, 200.0f, 100.0f); public Vector3 throwForce = new Vector3(10.0f, 8.0f, 10.0f);
public Vector3 cameraArmOffSet = new Vector3(0.0f, 0.25f, 0.0f); public Vector3 cameraArmOffSet = new Vector3(0.0f, 0.25f, 0.0f);
public GameObject item { get; set; } public GameObject item { get; set; }
public float delayTimer = 1.0f; public float delayTimer = 1.0f;
@ -29,6 +30,12 @@ public class PickAndThrow : Script
[Tooltip("Lenght of ray")] [Tooltip("Lenght of ray")]
public float rayDistance = 1; public float rayDistance = 1;
[Tooltip("Height of ray")]
public float rayHeight = 0.1f;
public float aimingFOV = 50;
public float defaultFOV = 45;
protected override void awake() protected override void awake()
{ {
pc = GetScript<PlayerController>(); pc = GetScript<PlayerController>();
@ -43,6 +50,8 @@ public class PickAndThrow : Script
if(!tpc) if(!tpc)
Debug.LogError("TPC EMPTY"); Debug.LogError("TPC EMPTY");
AudioHandler.audioClipHandlers["SFXThrow"] = Audio.CreateAudioClip("event:/Raccoon/raccoon_throw");
timer = delayTimer; timer = delayTimer;
} }
protected override void update() protected override void update()
@ -68,15 +77,17 @@ public class PickAndThrow : Script
pc.isAiming = true; pc.isAiming = true;
pc.camArm.ArmLength = aimingLength; pc.camArm.ArmLength = aimingLength;
pc.camArm.TargetOffset = cameraArmOffSet; pc.camArm.TargetOffset = cameraArmOffSet;
pc.cam.FOV = aimingFOV;
} }
if (Input.GetMouseButtonUp(Input.MouseCode.LeftButton) && pc.isAiming) if (Input.GetMouseButtonUp(Input.MouseCode.LeftButton) && pc.isAiming)
{ {
Audio.PlaySFXOnce2D("event:/Raccoon/raccoon_throw"); AudioHandler.audioClipHandlers["SFXThrow"].Play();
itemRidigBody.IsGravityEnabled = true; itemRidigBody.IsGravityEnabled = true;
itemCollider.GetCollisionShape(0).IsTrigger = false; itemCollider.GetCollisionShape(0).IsTrigger = false;
pc.isAiming = false; pc.isAiming = false;
pc.camArm.TargetOffset = Vector3.Zero; pc.camArm.TargetOffset = Vector3.Zero;
pc.cam.FOV = defaultFOV;
if (tpc) if (tpc)
pc.camArm.ArmLength = tpc.armLength; pc.camArm.ArmLength = tpc.armLength;
pc.holdItem = false; pc.holdItem = false;
@ -97,6 +108,7 @@ public class PickAndThrow : Script
if (Input.GetMouseButtonDown(Input.MouseCode.RightButton) && pc.isAiming) if (Input.GetMouseButtonDown(Input.MouseCode.RightButton) && pc.isAiming)
{ {
pc.isAiming = false; pc.isAiming = false;
pc.cam.FOV = defaultFOV;
pc.camArm.TargetOffset = Vector3.Zero; pc.camArm.TargetOffset = Vector3.Zero;
if (tpc) if (tpc)
pc.camArm.ArmLength = tpc.armLength; pc.camArm.ArmLength = tpc.armLength;
@ -126,7 +138,7 @@ public class PickAndThrow : Script
{ {
if (itemScript) if (itemScript)
{ {
Vector3 vec = new Vector3(throwForce.x * lastXDir, throwForce.y, throwForce.z * lastZDir); Vector3 vec = new Vector3(throwForce.x * lastXDir, throwForce.y + (throwForce.y * GetPitchRatioRange()), throwForce.z * lastZDir);
if (itemScript.currCategory == ItemCategory.LIGHT) if (itemScript.currCategory == ItemCategory.LIGHT)
itemRidigBody.AddForce(vec * 0.2f); itemRidigBody.AddForce(vec * 0.2f);
if (itemScript.currCategory == ItemCategory.MEDIUM) if (itemScript.currCategory == ItemCategory.MEDIUM)
@ -202,7 +214,7 @@ public class PickAndThrow : Script
{ {
Vector3 dirNor = pc.tranform.Forward; Vector3 dirNor = pc.tranform.Forward;
Vector3 playerRayPos = pc.tranform.GlobalPosition; Vector3 playerRayPos = pc.tranform.GlobalPosition;
playerRayPos.y += 0.05f; playerRayPos.y += rayHeight;
dirNor.Normalise(); dirNor.Normalise();
List<RaycastHit> rayList1 = Physics.Raycast(new Ray(playerRayPos, Vector3.RotateY(dirNor, SHADE.Math.DegreesToRadians(22.5f))), rayDistance, false, (ushort)65535); List<RaycastHit> rayList1 = Physics.Raycast(new Ray(playerRayPos, Vector3.RotateY(dirNor, SHADE.Math.DegreesToRadians(22.5f))), rayDistance, false, (ushort)65535);
List<RaycastHit> rayList2 = Physics.Raycast(new Ray(playerRayPos, Vector3.RotateY(dirNor, SHADE.Math.DegreesToRadians(-22.5f))), rayDistance, false, (ushort)65535); List<RaycastHit> rayList2 = Physics.Raycast(new Ray(playerRayPos, Vector3.RotateY(dirNor, SHADE.Math.DegreesToRadians(-22.5f))), rayDistance, false, (ushort)65535);
@ -248,5 +260,10 @@ public class PickAndThrow : Script
return false; return false;
} }
private float GetPitchRatioRange()
{
return (pc.camArm.Pitch - tpc.pitchUpperClamp) / (tpc.pitchLowerClamp - tpc.pitchUpperClamp);
}
} }

View File

@ -65,7 +65,7 @@ public class PlayerController : Script
//Jumping vars================================================================== //Jumping vars==================================================================
[Tooltip("max height of the jump")] [Tooltip("max height of the jump")]
public float maxJumpHeight = 1.0f; public float maxJumpHeight = 1.0f;
[Tooltip("max amt of time it will take for the jump")] [Tooltip("max amount of time it will take for the jump")]
public float maxJumpTime = 0.5f; public float maxJumpTime = 0.5f;
[Tooltip("increase gravity when falling")] [Tooltip("increase gravity when falling")]
public float fallMultipler = 3.0f; public float fallMultipler = 3.0f;
@ -73,6 +73,9 @@ public class PlayerController : Script
private bool isGrounded = true; private bool isGrounded = true;
private float gravity = -9.8f; private float gravity = -9.8f;
private float groundGravity = -0.5f; private float groundGravity = -0.5f;
public bool landedOnJumpPad { get; set; }
[Tooltip("multiply height on Jump Pad ")]
public float jumpPadMultiplayer = 2.0f;
//ItemMultipler================================================================== //ItemMultipler==================================================================
[Tooltip("How light item will affect player jump")] [Tooltip("How light item will affect player jump")]
@ -88,6 +91,7 @@ public class PlayerController : Script
isMoveKeyPress = false; isMoveKeyPress = false;
holdItem = false; holdItem = false;
isAiming = false; isAiming = false;
landedOnJumpPad = false;
//Jump setup //Jump setup
float timeToApex = maxJumpTime / 2; float timeToApex = maxJumpTime / 2;
@ -150,7 +154,13 @@ public class PlayerController : Script
if(!camArm) if(!camArm)
camArm = GetComponentInChildren<CameraArm>(); camArm = GetComponentInChildren<CameraArm>();
//tempFix
if (tranform)
tranform.LocalEulerAngles = new Vector3(0.0f, tranform.LocalEulerAngles.y, 0.0f);
Rotation(); Rotation();
MoveKey();
Sprint();
Jump(); Jump();
GotCaught(); GotCaught();
//Debug.Log($"{currentState}"); //Debug.Log($"{currentState}");
@ -161,10 +171,7 @@ public class PlayerController : Script
protected override void fixedUpdate() protected override void fixedUpdate()
{ {
MoveKey();
Move(); Move();
Sprint();
Gravity(); Gravity();
//Debug.Log($"X: {rb.LinearVelocity.x}" + $" Z: {rb.LinearVelocity.z}"); //Debug.Log($"X: {rb.LinearVelocity.x}" + $" Z: {rb.LinearVelocity.z}");
} }
@ -284,7 +291,7 @@ public class PlayerController : Script
{ {
if (currentState == RaccoonStates.WALKING || currentState == RaccoonStates.RUNNING || currentState == RaccoonStates.IDLE) if (currentState == RaccoonStates.WALKING || currentState == RaccoonStates.RUNNING || currentState == RaccoonStates.IDLE)
{ {
if (Input.GetKeyDown(Input.KeyCode.Space) && isGrounded && rb != null) if ( (Input.GetKeyDown(Input.KeyCode.Space) || landedOnJumpPad ) && isGrounded && rb != null)
{ {
currentState = RaccoonStates.JUMP; currentState = RaccoonStates.JUMP;
Vector3 v = rb.LinearVelocity; Vector3 v = rb.LinearVelocity;
@ -299,6 +306,12 @@ public class PlayerController : Script
if (item != null && item.currCategory == ItemCategory.HEAVY) if (item != null && item.currCategory == ItemCategory.HEAVY)
v.y *= heavyMultiper; v.y *= heavyMultiper;
} }
if (landedOnJumpPad)
{
v.y *= jumpPadMultiplayer;
landedOnJumpPad = false;
}
rb.LinearVelocity = v; rb.LinearVelocity = v;
} }
} }

View File

@ -14,9 +14,10 @@ namespace SHADE_Scripting
public float armLength = 2.0f; public float armLength = 2.0f;
public float turnSpeedPitch = 0.3f; public float turnSpeedPitch = 0.3f;
public float turnSpeedYaw = 0.5f; public float turnSpeedYaw = 0.5f;
public float pitchClamp = 45.0f;
public bool inverseXControls = false; public bool inverseXControls = false;
public bool inverseYControls = false; public bool inverseYControls = false;
public float pitchUpperClamp = 45.0f;
public float pitchLowerClamp = 5.0f;
protected override void awake() protected override void awake()
{ {
@ -50,17 +51,17 @@ namespace SHADE_Scripting
arm.Pitch += vel.y * turnSpeedPitch * Time.DeltaTimeF; arm.Pitch += vel.y * turnSpeedPitch * Time.DeltaTimeF;
if (inverseXControls) if (inverseXControls)
arm.Yaw -= vel.x * turnSpeedYaw * Time.DeltaTimeF;
else
arm.Yaw += vel.x * turnSpeedYaw * Time.DeltaTimeF; arm.Yaw += vel.x * turnSpeedYaw * Time.DeltaTimeF;
else
arm.Yaw -= vel.x * turnSpeedYaw * Time.DeltaTimeF;
if (arm.Pitch > pitchClamp) if (arm.Pitch > pitchUpperClamp)
{ {
arm.Pitch = pitchClamp; arm.Pitch = pitchUpperClamp;
} }
else if (arm.Pitch < 0) else if (arm.Pitch < pitchLowerClamp)
{ {
arm.Pitch = 0; arm.Pitch = pitchLowerClamp;
} }
} }
} }

View File

@ -1,4 +1,5 @@
using SHADE; using SHADE;
using SHADE_Scripting.Audio;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -37,6 +38,26 @@ public class GameManager : Script
private Vector3 fontScalar; private Vector3 fontScalar;
public static GameManager Instance { get; private set; } public static GameManager Instance { get; private set; }
//public static int highScore { get; private set; } maybe need
public bool GamePause { get; set; }
protected override void start()
{
base.start();
AudioHandler.audioClipHandlers["BGMAdaptive"] = Audio.CreateAudioClip("event:/Music/bgm_adaptive");
AudioHandler.audioClipHandlers["BGMAdaptive"].Play();
Audio.SetParameter("Detected", 0.0f);
AudioHandler.audioClipHandlers["KitchenAmbience"] = Audio.CreateAudioClip("event:/Ambience/roomtone_kitchen");
AudioHandler.audioClipHandlers["KitchenAmbience"].Play();
AudioHandler.audioClipHandlers["SFXHumming"] = Audio.CreateAudioClip("event:/Homeowner/homeowner_humming");
AudioHandler.audioClipHandlers["SFXHumming"].SetVolume(0.15f);
AudioHandler.audioClipHandlers["SFXHumming"].Play();
}
protected override void awake() protected override void awake()
{ {
@ -45,8 +66,12 @@ public class GameManager : Script
else else
Instance = this; Instance = this;
Audio.PlayBGMOnce2D("event:/Music/player_undetected");
Audio.PlayBGMOnce2D("event:/Ambience/roomtone_kitchen"); //AudioHandler.audioClipHandlers["BGMAdaptive"].SetParameter("Detected", 0.0f);
//Audio.PlayBGMOnce2D("event:/Music/player_undetected");
//Audio.PlayBGMOnce2D("event:/Ambience/roomtone_kitchen");
totalItemCount = 0; totalItemCount = 0;
Score = 0; Score = 0;
currGameState = GameState.START; currGameState = GameState.START;
@ -54,11 +79,18 @@ public class GameManager : Script
currMultiplierCombo = 1; currMultiplierCombo = 1;
currMultiplierDuration = 0; currMultiplierDuration = 0;
fontScalar = new Vector3(multiplierFont / maxMultiplierDuration, multiplierFont / maxMultiplierDuration , multiplierFont / maxMultiplierDuration); fontScalar = new Vector3(multiplierFont / maxMultiplierDuration, multiplierFont / maxMultiplierDuration , multiplierFont / maxMultiplierDuration);
AudioHandler.audioClipHandlers["BGMWin"] = Audio.CreateAudioClip("event:/Music/stingers/game_win");
AudioHandler.audioClipHandlers["BGMLose"] = Audio.CreateAudioClip("event:/Music/stingers/game_lose");
} }
protected override void update() protected override void update()
{ {
Cheats(); if (GamePause)
{
return;
}
if (currGameState == GameState.START) if (currGameState == GameState.START)
{ {
timer -= Time.DeltaTimeF; timer -= Time.DeltaTimeF;
@ -86,19 +118,25 @@ public class GameManager : Script
multiplierText.GetComponent<Transform>().LocalScale = Vector3.Zero; multiplierText.GetComponent<Transform>().LocalScale = Vector3.Zero;
} }
if ((timer > 0 && totalItemCount < 0) || Input.GetKeyDown(Input.KeyCode.F1)) if ((timer > 0 && totalItemCount <= 0) || Input.GetKeyDown(Input.KeyCode.F1))
{ {
currGameState = GameState.WIN; currGameState = GameState.WIN;
Audio.StopAllSounds(); //Audio.StopAllSounds(); //Calling this outright breaks audio clip handlers
AudioHandler.stopAllSounds(false);
AudioHandler.audioClipHandlers["BGMWin"].Play();
SceneManager.ChangeScene(winScene); SceneManager.ChangeScene(winScene);
Audio.PlaySFXOnce2D("event:/Music/stingers/game_win"); //Audio.PlaySFXOnce2D("event:/Music/stingers/game_win");
} }
else if(timer < 0 || Input.GetKeyDown(Input.KeyCode.F2)) else if(timer < 0 || Input.GetKeyDown(Input.KeyCode.F2))
{ {
currGameState = GameState.LOSE; currGameState = GameState.LOSE;
Audio.StopAllSounds(); //Audio.StopAllSounds();
AudioHandler.stopAllSounds(false);
AudioHandler.audioClipHandlers["BGMLose"].Play();
SceneManager.ChangeScene(loseScene); SceneManager.ChangeScene(loseScene);
Audio.PlaySFXOnce2D("event:/Music/stingers/game_lose"); //Audio.PlaySFXOnce2D("event:/Music/stingers/game_lose");
} }
} }
} }
@ -109,15 +147,6 @@ public class GameManager : Script
Instance = null; Instance = null;
} }
private void Cheats()
{
if (Input.GetKeyDown(Input.KeyCode.Escape))
{
Audio.StopAllSounds();
SceneManager.ChangeScene(97158628);
}
}
public void ItemScored() public void ItemScored()
{ {
totalItemCount -= 1; totalItemCount -= 1;

View File

@ -1,19 +1,21 @@
using SHADE; using SHADE;
using SHADE_Scripting.Audio;
using System; using System;
public class ScoringZone : Script public class ScoringZone : Script
{ {
protected override void awake() protected override void awake()
{ {
AudioHandler.audioClipHandlers["SFXItemScore"] = Audio.CreateAudioClip("event:/Music/stingers/item_scored");
} }
protected override void onTriggerEnter(CollisionInfo info) protected override void onTriggerEnter(CollisionInfo info)
{ {
if (GameManager.Instance && info.GameObject.GetScript<Item>()) if (GameManager.Instance && info.GameObject.GetScript<Item>() && info.GameObject.IsActiveSelf && !info.GameObject.GetComponent<Collider>().GetCollisionShape(0).IsTrigger )
{ {
Audio.PlaySFXOnce2D("event:/Music/stingers/item_scored"); AudioHandler.audioClipHandlers["SFXItemScore"].Play();
GameManager.Instance.ItemScored();
GameManager.Instance.Score += info.GameObject.GetScript<Item>().Score * GameManager.Instance.currMultiplierCombo; GameManager.Instance.Score += info.GameObject.GetScript<Item>().Score * GameManager.Instance.currMultiplierCombo;
GameManager.Instance.ItemScored();
info.GameObject.SetActive(false); info.GameObject.SetActive(false);
} }
} }

View File

@ -0,0 +1,22 @@
using SHADE;
using System;
public class JumpPad : Script
{
protected override void awake()
{
}
protected override void update()
{
}
protected override void onCollisionEnter(CollisionInfo info)
{
if (info.GameObject.GetScript<PlayerController>() && info.GameObject.GetScript<PlayerController>().currentState == PlayerController.RaccoonStates.FALLING)
{
info.GameObject.GetScript<PlayerController>().landedOnJumpPad = true;
}
}
}

View File

@ -0,0 +1,3 @@
Name: SC_JumpPad
ID: 167326885
Type: 9

View File

@ -0,0 +1,37 @@
using SHADE;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SHADE_Scripting
{
public class StaticTest
{
public static int x;
static StaticTest()
{
x = 5;
Debug.Log("Static Constructor!");
}
}
public class ImplicitStaticTest : Script
{
public static int x = 5;
static ImplicitStaticTest()
{
Debug.Log("Static Constructor!");
}
protected override void awake()
{
Debug.LogWarning($"Before Add: x = {x}");
++x;
Debug.LogWarning($"After Add: x = {x}");
}
}
}

View File

@ -0,0 +1,3 @@
Name: StaticTest
ID: 159057282
Type: 9

View File

@ -0,0 +1,45 @@
using SHADE;
using System;
using System.Collections.Generic;
using static Item;
public class CollisionTest : Script
{
public Collider collider { get; set; }
private bool printStay = false;
protected override void awake()
{
collider = GetComponent<Collider>();
}
protected override void onCollisionEnter(CollisionInfo info)
{
base.onCollisionEnter(info);
Debug.Log("Collision Enter");
printStay = false;
}
protected override void onCollisionStay(CollisionInfo info)
{
base.onCollisionStay(info);
if (!printStay)
{
Debug.Log("Collision Stay");
printStay= true;
}
}
protected override void onCollisionExit(CollisionInfo info)
{
base.onCollisionExit(info);
Debug.Log("Collision Exit");
printStay = false;
}
};

View File

@ -0,0 +1,3 @@
Name: CollisionTest
ID: 163810535
Type: 9

View File

@ -6,6 +6,7 @@ using static Item;
public class PhysicsTestObj : Script public class PhysicsTestObj : Script
{ {
public Transform tf { get; set; }
public RigidBody body { get; set; } public RigidBody body { get; set; }
public Collider collider { get; set; } public Collider collider { get; set; }
@ -68,6 +69,7 @@ public class PhysicsTestObj : Script
protected override void awake() protected override void awake()
{ {
tf = GetComponent<Transform>();
body = GetComponent<RigidBody>(); body = GetComponent<RigidBody>();
collider = GetComponent<Collider>(); collider = GetComponent<Collider>();
@ -80,9 +82,12 @@ public class PhysicsTestObj : Script
protected override void update() protected override void update()
{ {
Ray colliderRay = new Ray(); GameObject? target = GameObject.Find("Target");
colliderRay.Direction = Vector3.Right; if (target.HasValue)
Physics.ColliderRaycast(collider.Owner, colliderRay, false, (ushort)64); {
Physics.ColliderLineCast(collider.Owner, Vector3.Zero, target.Value.GetComponent<Transform>().GlobalPosition, false, (ushort)64);
}
for (int i = 0; i < 6; ++i) for (int i = 0; i < 6; ++i)
{ {

View File

@ -0,0 +1,33 @@
using SHADE;
using System;
using System.Collections.Generic;
using static Item;
public class TriggerTest : Script
{
public Collider collider { get; set; }
protected override void awake()
{
collider = GetComponent<Collider>();
}
protected override void onTriggerEnter(CollisionInfo info)
{
base.onTriggerEnter(info);
Debug.Log("Trigger Enter");
}
protected override void onTriggerStay(CollisionInfo info)
{
base.onTriggerStay(info);
Debug.Log("Trigger Stay");
}
protected override void onTriggerExit(CollisionInfo info)
{
base.onTriggerExit(info);
Debug.Log("Trigger Exit");
}
};

View File

@ -0,0 +1,3 @@
Name: TriggerTest
ID: 159344038
Type: 9

View File

@ -1,5 +1,6 @@
using System; using System;
using SHADE; using SHADE;
using SHADE_Scripting.Audio;
public class EndScene : Script public class EndScene : Script
{ {
@ -8,28 +9,36 @@ public class EndScene : Script
protected override void awake() protected override void awake()
{ {
AudioHandler.audioClipHandlers["SFXMouseDownElement"] = Audio.CreateAudioClip("event:/UI/mouse_down_element");
AudioHandler.audioClipHandlers["SFXUISuccess"] = Audio.CreateAudioClip("event:/UI/success");
} }
protected override void update() protected override void update()
{ {
if (Input.GetKeyDown(Input.KeyCode.R)) if (Input.GetKeyDown(Input.KeyCode.R))
{ {
Audio.PlaySFXOnce2D("event:/UI/mouse_down_element"); //Audio.PlaySFXOnce2D("event:/UI/mouse_down_element");
AudioHandler.audioClipHandlers["SFXMouseDownElement"].Play();
} }
if (Input.GetKeyUp(Input.KeyCode.R)) if (Input.GetKeyUp(Input.KeyCode.R))
{ {
Audio.PlaySFXOnce2D("event:/UI/success"); //Audio.PlaySFXOnce2D("event:/UI/success");
Audio.StopAllSounds(); //Audio.StopAllSounds();
AudioHandler.stopAllSounds(false);
AudioHandler.audioClipHandlers["SFXUISuccess"].Play();
SceneManager.ChangeScene(mainGameScene); SceneManager.ChangeScene(mainGameScene);
} }
if (Input.GetKeyDown(Input.KeyCode.M)) if (Input.GetKeyDown(Input.KeyCode.M))
{ {
Audio.PlaySFXOnce2D("event:/UI/mouse_down_element"); //Audio.PlaySFXOnce2D("event:/UI/mouse_down_element");
AudioHandler.audioClipHandlers["SFXMouseDownElement"].Play();
} }
if (Input.GetKeyUp(Input.KeyCode.M)) if (Input.GetKeyUp(Input.KeyCode.M))
{ {
Audio.PlaySFXOnce2D("event:/UI/success"); //Audio.PlaySFXOnce2D("event:/UI/success");
Audio.StopAllSounds(); //Audio.StopAllSounds();
AudioHandler.stopAllSounds(false);
AudioHandler.audioClipHandlers["SFXUISuccess"].Play();
SceneManager.ChangeScene(mainMainScene); SceneManager.ChangeScene(mainMainScene);
} }

View File

@ -1,23 +1,30 @@
using System; using System;
using SHADE; using SHADE;
using SHADE_Scripting.Audio;
public class MainMenu : Script public class MainMenu : Script
{ {
public uint sceneID; public uint sceneID;
protected override void awake() protected override void awake()
{ {
Audio.PlayBGMOnce2D("event:/Music/main_menu"); AudioHandler.audioClipHandlers["BGMMainMenu"] = Audio.CreateAudioClip("event:/Music/main_menu");
AudioHandler.audioClipHandlers["SFXMouseDownElement"] = Audio.CreateAudioClip("event:/UI/mouse_down_element");
AudioHandler.audioClipHandlers["SFXUISuccess"] = Audio.CreateAudioClip("event:/UI/success");
//Audio.PlayBGMOnce2D("event:/Music/main_menu");
AudioHandler.audioClipHandlers["BGMMainMenu"].Play();
} }
protected override void update() protected override void update()
{ {
if (Input.GetKeyDown(Input.KeyCode.Space)) if (Input.GetKeyDown(Input.KeyCode.Space))
{ {
Audio.PlaySFXOnce2D("event:/UI/mouse_down_element"); //Audio.PlaySFXOnce2D("event:/UI/mouse_down_element");
AudioHandler.audioClipHandlers["SFXMouseDownElement"].Play();
} }
if (Input.GetKeyUp(Input.KeyCode.Space)) if (Input.GetKeyUp(Input.KeyCode.Space))
{ {
Audio.PlaySFXOnce2D("event:/UI/success"); //Audio.PlaySFXOnce2D("event:/UI/success");
AudioHandler.audioClipHandlers["SFXUISuccess"].Play();
SceneManager.ChangeScene(sceneID); SceneManager.ChangeScene(sceneID);
Audio.StopAllSounds(); Audio.StopAllSounds();
} }

View File

@ -0,0 +1,106 @@
using System;
using SHADE;
using SHADE_Scripting.Audio;
public class PauseMenu : Script
{
public GameObject resumeBtn;
public GameObject retryBtn;
public GameObject quitBtn;
public GameObject gamePauseText;
public GameObject canvas;
protected override void awake()
{
GameManager.Instance.GamePause = false;
if (gamePauseText)
gamePauseText.GetComponent<TextRenderable>().Enabled = false;
if (canvas)
canvas.SetActive(false);
if (!resumeBtn)
Debug.LogError("Resume Btn missing");
if (!retryBtn)
Debug.LogError("Retry Btn missing");
if (!quitBtn)
Debug.LogError("Quit Btn missing");
}
protected override void start()
{
//resume
UIElement resume = resumeBtn.GetComponent<UIElement>();
if (resume != null)
{
resume.OnClick.RegisterAction(() =>
{
if (GameManager.Instance.GamePause)
{
GameManager.Instance.GamePause = false;
AudioHandler.pauseAllSounds(false);
if (gamePauseText)
gamePauseText.GetComponent<TextRenderable>().Enabled = false;
if (canvas)
canvas.SetActive(false);
}
});
}
else
{
Debug.LogError("Failed to register resume button.");
}
//retry
UIElement retry = retryBtn.GetComponent<UIElement>();
if (retry != null)
{
retry.OnClick.RegisterAction(() =>
{
Audio.StopAllSounds();
//get curr scene
//SceneManager.ChangeScene();
});
}
else
{
Debug.LogError("Failed to register retry button.");
}
UIElement quit = quitBtn.GetComponent<UIElement>();
if (quit != null)
{
quit.OnClick.RegisterAction(() =>
{
Audio.StopAllSounds();
//go to main menu
SceneManager.ChangeScene(97158628);
});
}
else
{
Debug.LogError("Failed to register quit button.");
}
}
protected override void update()
{
if (GameManager.Instance.GamePause)
{
return;
}
if (Input.GetKeyDown(Input.KeyCode.Escape) && !GameManager.Instance.GamePause)
{
GameManager.Instance.GamePause = true;
AudioHandler.pauseAllSounds(true);
if (gamePauseText)
gamePauseText.GetComponent<TextRenderable>().Enabled = true;
if (canvas)
canvas.SetActive(true);
}
}
}

View File

@ -0,0 +1,3 @@
Name: SC_PauseMenu
ID: 151952680
Type: 9

View File

@ -48,19 +48,34 @@ layout(std430, set = 1, binding = 4) buffer AmbientLightData
AmbientLightStruct aLightData[]; AmbientLightStruct aLightData[];
} AmbLightData; } AmbLightData;
float LinStep (float val, float low, float high)
{
return clamp ((val - low)/(high - low), 0.0f, 1.0f);
}
float CalcShadowValue (sampler2D shadowMap, vec4 worldSpaceFragPos, mat4 lightPV) float CalcShadowValue (sampler2D shadowMap, vec4 worldSpaceFragPos, mat4 lightPV)
{ {
// clip space for fragment from light view space
vec4 fragPosLightPOV = lightPV * worldSpaceFragPos; vec4 fragPosLightPOV = lightPV * worldSpaceFragPos;
// Perform perspective division and convert to 0 to 1 range
vec3 converted = (fragPosLightPOV.xyz / fragPosLightPOV.w) * vec3(0.5f) + vec3(0.5f); vec3 converted = (fragPosLightPOV.xyz / fragPosLightPOV.w) * vec3(0.5f) + vec3(0.5f);
float sampledDepth = texture(shadowMap, converted.xy).r; // float sampledDepth = texture(shadowMap, converted.xy).r;
// float sampledDepth = texture(shadowMap, converted.xy).z;
vec2 moments = texture(shadowMap, converted.xy).xy;
if (converted.x < 0.0f || converted.x > 1.0f || converted.y < 0.0f || converted.y > 1.0f) if (converted.x < 0.0f || converted.x > 1.0f || converted.y < 0.0f || converted.y > 1.0f)
return 1.0f; return 1.0f;
if (fragPosLightPOV.z > sampledDepth && fragPosLightPOV.w > 0.0f) if (fragPosLightPOV.z > moments.x && fragPosLightPOV.w > 0.0f)
{ {
return 0.7f; float p = step (fragPosLightPOV.z, moments.x);
float variance = max (moments.y - (moments.x * moments.x), 0.00002f);
float d = fragPosLightPOV.z - moments.x;
float pMax = LinStep (variance / (variance + (d * d)), 0.9f, 1.0f);
return min (max (p, pMax), 1.0f);
} }
else else
return 1.0f; return 1.0f;

View File

@ -3,8 +3,10 @@
#extension GL_ARB_shading_language_420pack : enable #extension GL_ARB_shading_language_420pack : enable
#extension GL_EXT_nonuniform_qualifier : require #extension GL_EXT_nonuniform_qualifier : require
layout(location = 0) out vec4 shadowMap;
void main() void main()
{ {
// shadowMap = vec4 (0.0f, 0.0f, gl_FragCoord.z, 1.0f);
shadowMap = vec4 (gl_FragCoord.z, gl_FragCoord.z * gl_FragCoord.z, 0.0f, 1.0f);
} }

View File

@ -0,0 +1,22 @@
#version 450
#extension GL_ARB_separate_shader_objects : enable
#extension GL_ARB_shading_language_420pack : enable
#extension GL_EXT_nonuniform_qualifier : require
layout(location = 0) in struct
{
vec4 vertPos; // location 0
vec2 uv; // location = 1
vec4 color; // location = 2
} In;
layout(location = 0) out vec4 fragColor;
void main()
{
// default red first
fragColor = In.color;
}

Binary file not shown.

View File

@ -0,0 +1,3 @@
Name: Trajectory_FS
ID: 45635685
Type: 2

View File

@ -0,0 +1,36 @@
#version 450
#extension GL_KHR_vulkan_glsl : enable
// vertex inputs
layout(location = 0) in vec3 aPos;
layout(location = 1) in vec2 aUV;
layout(location = 2) in vec4 aColor;
layout(location = 3) in mat4 aTransform;
// between shader stages
layout(location = 0) out struct
{
vec4 vertPos; // location 0
vec2 uv; // location = 1
vec4 color; // location = 2
} Out;
// Camera data
layout(set = 1, binding = 0) uniform CameraData
{
vec4 position;
mat4 vpMat;
mat4 viewMat;
mat4 projMat;
} cameraData;
void main()
{
Out.uv = aUV;
Out.color = aColor;
gl_Position = cameraData.projMat * aTransform * vec4(aPos, 1.0f);
}

Binary file not shown.

View File

@ -0,0 +1,3 @@
Name: Trajectory_VS
ID: 41042628
Type: 2

View File

@ -171,6 +171,7 @@ namespace Sandbox
SHSceneManager::InitSceneManager<SBMainScene>(editorConfig.workingSceneID); SHSceneManager::InitSceneManager<SBMainScene>(editorConfig.workingSceneID);
#else #else
SHSceneManager::InitSceneManager<SBMainScene>(appConfig.startingSceneID); SHSceneManager::InitSceneManager<SBMainScene>(appConfig.startingSceneID);
window.SetMouseVisible(false);
#endif #endif
SHFrameRateController::UpdateFRC(); SHFrameRateController::UpdateFRC();
@ -199,7 +200,8 @@ namespace Sandbox
#ifdef SHEDITOR #ifdef SHEDITOR
if(editor->editorState == SHEditor::State::PLAY) if(editor->editorState == SHEditor::State::PLAY)
#else
window.ClipMouseCursor();
#endif #endif
SHSceneManager::SceneUpdate(0.016f); SHSceneManager::SceneUpdate(0.016f);
#ifdef SHEDITOR #ifdef SHEDITOR

View File

@ -31,7 +31,7 @@ INT WINAPI wWinMain
try try
{ {
#ifndef SHEDITOR #ifndef SHEDITOR
//ShowWindow(::GetConsoleWindow(), SW_HIDE); ShowWindow(::GetConsoleWindow(), SW_HIDE);
#endif #endif
SHLOG_REGISTER(logger) SHLOG_REGISTER(logger)

View File

@ -23,6 +23,7 @@ of DigiPen Institute of Technology is prohibited.
#include "Graphics/SHVkUtil.h" #include "Graphics/SHVkUtil.h"
#include "Graphics/MiddleEnd/Interface/SHGraphicsSystem.h" #include "Graphics/MiddleEnd/Interface/SHGraphicsSystem.h"
#include "ECS_Base/Managers/SHSystemManager.h" #include "ECS_Base/Managers/SHSystemManager.h"
#include "Graphics/MiddleEnd/Interface/SHMaterialInstance.h"
#include "Tools/SHDebugDraw.h" #include "Tools/SHDebugDraw.h"
namespace SHADE namespace SHADE
@ -98,7 +99,7 @@ namespace SHADE
} }
} }
if (rig && currClip) if (rig && rig->GetRootNode() && currClip)
{ {
updatePoseWithClip(0.0f); updatePoseWithClip(0.0f);
} }
@ -109,8 +110,11 @@ namespace SHADE
/*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/
void SHAnimatorComponent::Update(float dt) void SHAnimatorComponent::Update(float dt)
{ {
//Reset matrices
std::fill(boneMatrices.begin(), boneMatrices.end(), SHMatrix::Identity);
// Nothing to animate // Nothing to animate
if (!currClip || !isPlaying || !rig) if (!currClip || !isPlaying || !rig || !rig->GetRootNode())
return; return;
// Update time on the playback // Update time on the playback
@ -120,12 +124,6 @@ namespace SHADE
currPlaybackTime = currPlaybackTime - currClip->GetTotalTime(); currPlaybackTime = currPlaybackTime - currClip->GetTotalTime();
} }
// Reset all matrices
for (auto& mat : boneMatrices)
{
mat = SHMatrix::Identity;
}
// Play the clip // Play the clip
updatePoseWithClip(currPlaybackTime); updatePoseWithClip(currPlaybackTime);
} }

View File

@ -254,7 +254,8 @@ RTTR_REGISTRATION
.property("Height", &SHCameraComponent::GetHeight, &SHCameraComponent::SetHeight) .property("Height", &SHCameraComponent::GetHeight, &SHCameraComponent::SetHeight)
.property("Near", &SHCameraComponent::GetNear, &SHCameraComponent::SetNear) .property("Near", &SHCameraComponent::GetNear, &SHCameraComponent::SetNear)
.property("Far", &SHCameraComponent::GetFar, &SHCameraComponent::SetFar) .property("Far", &SHCameraComponent::GetFar, &SHCameraComponent::SetFar)
.property("Perspective", &SHCameraComponent::GetIsPerspective, &SHCameraComponent::SetIsPerspective); .property("Perspective", &SHCameraComponent::GetIsPerspective, &SHCameraComponent::SetIsPerspective)
.property("FOV",&SHCameraComponent::GetFOV, &SHCameraComponent::SetFOV);
} }

View File

@ -12,6 +12,7 @@
#include "Editor/SHEditor.h" #include "Editor/SHEditor.h"
#include "Math/SHRay.h" #include "Math/SHRay.h"
#include "Physics/System/SHPhysicsSystem.h" #include "Physics/System/SHPhysicsSystem.h"
#include "Graphics/Events/SHGraphicsEvents.h"
namespace SHADE namespace SHADE
@ -123,6 +124,13 @@ namespace SHADE
SHComponentManager::CreateComponentSparseSet<SHCameraComponent>(); SHComponentManager::CreateComponentSparseSet<SHCameraComponent>();
SHComponentManager::CreateComponentSparseSet<SHCameraArmComponent>(); SHComponentManager::CreateComponentSparseSet<SHCameraArmComponent>();
std::shared_ptr<SHEventReceiverSpec<SHCameraSystem>> thisReceiver
{
std::make_shared<SHEventReceiverSpec<SHCameraSystem>>(this, &SHCameraSystem::ReceiveWindowResizeEvent)
};
ReceiverPtr receiver = std::dynamic_pointer_cast<SHEventReceiver>(thisReceiver);
SHEventManager::SubscribeTo(SH_WINDOW_RESIZE_EVENT, receiver);
} }
void SHCameraSystem::Exit(void) void SHCameraSystem::Exit(void)
@ -130,6 +138,29 @@ namespace SHADE
} }
SHEventHandle SHCameraSystem::ReceiveWindowResizeEvent(SHEventPtr eventPtr) noexcept
{
auto const& EVENT_DATA = reinterpret_cast<const SHEventSpec<SHWindowResizeEvent>*>(eventPtr.get())->data;
//std::cout << EVENT_DATA->resizeWidth << std::endl;
//std::cout << EVENT_DATA->resizeHeight << std::endl;
for (auto director : directorHandleList)
{
auto camera = SHComponentManager::GetComponent_s<SHCameraComponent>(director->mainCameraEID);
if (camera)
{
camera->SetWidth(EVENT_DATA->resizeWidth);
camera->SetHeight(EVENT_DATA->resizeHeight);
}
}
return eventPtr->handle;
}
SHCameraComponent* SHCameraSystem::GetEditorCamera(void) noexcept SHCameraComponent* SHCameraSystem::GetEditorCamera(void) noexcept
{ {
return &editorCamera; return &editorCamera;
@ -142,10 +173,10 @@ namespace SHADE
SHVec3 offset{ 0.0f,0.0f, pivot.GetArmLength() }; SHVec3 offset{ 0.0f,0.0f, 1.0f };
offset = SHVec3::RotateX(offset, -(SHMath::DegreesToRadians(pivot.GetPitch()))); offset = SHVec3::RotateX(offset, -(SHMath::DegreesToRadians(pivot.GetPitch())));
offset = SHVec3::RotateY(offset, (SHMath::DegreesToRadians(pivot.GetYaw()))); offset = SHVec3::RotateY(offset, (SHMath::DegreesToRadians(pivot.GetYaw())));
offset = SHVec3::Normalise(offset) * pivot.armLength;
//pivot.rtMatrix = SHMatrix::RotateX(SHMath::DegreesToRadians(pivot.GetPitch())) //pivot.rtMatrix = SHMatrix::RotateX(SHMath::DegreesToRadians(pivot.GetPitch()))
// * SHMatrix::RotateY(SHMath::DegreesToRadians(pivot.GetYaw())) // * SHMatrix::RotateY(SHMath::DegreesToRadians(pivot.GetYaw()))
@ -165,7 +196,7 @@ namespace SHADE
return; return;
/*if (SHComponentManager::HasComponent<SHTransformComponent>(camera->GetEID()) == true && camera != &editorCamera) if (SHComponentManager::HasComponent<SHTransformComponent>(camera->GetEID()) == true && camera != &editorCamera)
{ {
auto transform = SHComponentManager::GetComponent<SHTransformComponent>(camera->GetEID()); auto transform = SHComponentManager::GetComponent<SHTransformComponent>(camera->GetEID());
SHVec3 rotation = transform->GetWorldRotation(); SHVec3 rotation = transform->GetWorldRotation();
@ -174,14 +205,47 @@ namespace SHADE
camera->roll = SHMath::RadiansToDegrees(rotation.z); camera->roll = SHMath::RadiansToDegrees(rotation.z);
camera->position = transform->GetWorldPosition(); camera->position = transform->GetWorldPosition();
camera->dirtyView = true; camera->dirtyView = true;
}*/ }
pivot.ray.position = camera->GetPosition() + pivot.targetOffset;
pivot.ray.direction = SHVec3::Normalise((camera->position + offset)- pivot.ray.position); SHVec3 cameraPos = camera->position + pivot.offset;
SHVec3 cameraTarget = camera->position;
//SHLOG_INFO("Ray position: {},{},{} direction:{},{},{}",pivot.ray.position.x, pivot.ray.position.y, pivot.ray.position.z,pivot.ray.direction.x, pivot.ray.direction.y, pivot.ray.direction.z) //SHLOG_INFO("Ray position: {},{},{} direction:{},{},{}",pivot.ray.position.x, pivot.ray.position.y, pivot.ray.position.z,pivot.ray.direction.x, pivot.ray.direction.y, pivot.ray.direction.z)
SHRaycaster::RaycastInfo info;
//info.layers = (SHCollisionTagMatrix::GetTag("7")->GetMask());
info.layers = (uint16_t)(SHCollisionTagMatrix::GetTag("Camera")->GetMask());
info.distance = pivot.armLength;
info.continuous = false;
info.ray.position = cameraTarget;
info.SetColliderID(2);
info.ray.direction = SHVec3::Normalise(cameraPos - cameraTarget);
auto result = physicsSystem->Raycast(info);
for (auto hitResult : result)
{
if (hitResult.distance < pivot.armLength)
{
//auto result = physicsSystem->Raycast(pivot.ray); SHVec3 newOffset{ 0.0f,0.0f, 1.0f };
newOffset = SHVec3::RotateX(newOffset, -(SHMath::DegreesToRadians(pivot.GetPitch())));
newOffset = SHVec3::RotateY(newOffset, (SHMath::DegreesToRadians(pivot.GetYaw())));
newOffset = SHVec3::Normalise(newOffset) * (hitResult.distance * 0.95f);
pivot.offset = newOffset;
//cameraPos = camera->position + pivot.offset;
//SHLOG_INFO("CAMERA COLLISION HIT, {} armlength: {}, true armlength: {}", hitResult.distance, hitResult.distance, (cameraPos - camera->position).Length());
//SHLOG_INFO("Racoon Position {}, {}, {}, Camera Position: {}, {}, {}, Distance {}", cameraTarget.x, cameraTarget.y, cameraTarget.z, cameraPos.x, cameraPos.y, cameraPos.z, SHVec3::Distance(cameraTarget, cameraPos));
//SHLOG_INFO("Camera Position: {}, {}, {}", cameraPos.x, cameraPos.y, cameraPos.z);
//auto otherTransform = SHComponentManager::GetComponent_s<SHTransformComponent>(hitResult.entityHit);
//SHVec3 otherPos = hitResult.position;
//SHLOG_INFO("hit distance{} other pos: {},{},{}, distance between: {}", hitResult.distance, otherPos.x, otherPos.y, otherPos.z, SHVec3::Distance(cameraTarget,otherPos));
break;
}
}
////auto result = physicsSystem->Raycast(pivot.ray);
//if (result && result.distance < pivot.GetArmLength()) //if (result && result.distance < pivot.GetArmLength())
//{ //{
// //
@ -196,8 +260,6 @@ namespace SHADE
// //SHLOG_INFO("CAMERA COLLISION CANT HIT CAMERA"); // //SHLOG_INFO("CAMERA COLLISION CANT HIT CAMERA");
//} //}
//
//
// pivot.rtMatrix = SHMatrix::Inverse(pivot.rtMatrix); // pivot.rtMatrix = SHMatrix::Inverse(pivot.rtMatrix);
@ -235,6 +297,7 @@ namespace SHADE
camera.offset = arm->GetOffset(); camera.offset = arm->GetOffset();
if (arm->lookAtCameraOrigin) if (arm->lookAtCameraOrigin)
CameraLookAt(camera, camera.position + arm->GetTargetOffset()); CameraLookAt(camera, camera.position + arm->GetTargetOffset());
} }
} }
@ -418,7 +481,7 @@ namespace SHADE
} }
} }
void SHCameraSystem::DecomposeViewMatrix(SHMatrix const& viewMatrix, float& pitch, float& yaw, float& roll, SHVec3& pos) noexcept void SHCameraSystem::DecomposeViewMatrix(SHMatrix const& viewMatrix, float& pitch, float& yaw, float& roll, SHVec3& pos, bool takePos) noexcept
{ {
float initPitch = pitch; float initPitch = pitch;
@ -441,15 +504,18 @@ namespace SHADE
mtx = SHMatrix::Inverse(mtx); mtx = SHMatrix::Inverse(mtx);
SHVec4 translate = mtx* dotPos; SHVec4 translate = mtx* dotPos;
if (takePos)
{
pos.x = translate.x; pos.x = translate.x;
pos.y = translate.y; pos.y = translate.y;
pos.z = translate.z; pos.z = translate.z;
}
} }
void SHCameraSystem::SetCameraViewMatrix(SHCameraComponent& camera, SHMatrix const& viewMatrix) noexcept void SHCameraSystem::SetCameraViewMatrix(SHCameraComponent& camera, SHMatrix const& viewMatrix, bool takePos) noexcept
{ {
SHVec3 pos; SHVec3 pos;
DecomposeViewMatrix(viewMatrix, camera.pitch, camera.yaw, camera.roll, camera.position); DecomposeViewMatrix(viewMatrix, camera.pitch, camera.yaw, camera.roll, camera.position, takePos);
camera.dirtyView = true; camera.dirtyView = true;
} }
@ -457,7 +523,7 @@ namespace SHADE
void SHCameraSystem::CameraLookAt(SHCameraComponent& camera, SHVec3 target) noexcept void SHCameraSystem::CameraLookAt(SHCameraComponent& camera, SHVec3 target) noexcept
{ {
if (camera.position == target) if (camera.position + camera.offset == target)
{ {
//lets off set it abit so the view is nt fked //lets off set it abit so the view is nt fked
target.z -= 0.0001f; target.z -= 0.0001f;
@ -499,7 +565,7 @@ namespace SHADE
viewMtx(2, 3) = -forward.Dot(camera.position + camera.offset); viewMtx(2, 3) = -forward.Dot(camera.position + camera.offset);
SetCameraViewMatrix(camera, viewMtx); SetCameraViewMatrix(camera, viewMtx,false);
} }
SHVec2 SHCameraSystem::GetCameraWidthHeight(size_t index) noexcept SHVec2 SHCameraSystem::GetCameraWidthHeight(size_t index) noexcept

View File

@ -46,6 +46,11 @@ namespace SHADE
}; };
friend class CameraSystemUpdate; friend class CameraSystemUpdate;
/*-----------------------------------------------------------------------*/
/* Light functions */
/*-----------------------------------------------------------------------*/
SHEventHandle ReceiveWindowResizeEvent(SHEventPtr eventPtr) noexcept;
SHCameraComponent* GetEditorCamera (void) noexcept; SHCameraComponent* GetEditorCamera (void) noexcept;
void GetCameraAxis(SHCameraComponent const& camera, SHVec3& forward, SHVec3& right, SHVec3& up) const noexcept; void GetCameraAxis(SHCameraComponent const& camera, SHVec3& forward, SHVec3& right, SHVec3& up) const noexcept;
@ -54,8 +59,8 @@ namespace SHADE
void ClampCameraRotation(SHCameraComponent& camera) noexcept; void ClampCameraRotation(SHCameraComponent& camera) noexcept;
void UpdateEditorCamera(double dt) noexcept; void UpdateEditorCamera(double dt) noexcept;
void SetMainCamera(EntityID eid, size_t directorIndex) noexcept; void SetMainCamera(EntityID eid, size_t directorIndex) noexcept;
void DecomposeViewMatrix(SHMatrix const& matrix, float& pitch, float& yaw, float& roll, SHVec3& pos) noexcept; void DecomposeViewMatrix(SHMatrix const& matrix, float& pitch, float& yaw, float& roll, SHVec3& pos, bool takePos) noexcept;
void SetCameraViewMatrix(SHCameraComponent& camera, SHMatrix const& viewMatrix) noexcept; void SetCameraViewMatrix(SHCameraComponent& camera, SHMatrix const& viewMatrix, bool takePos) noexcept;
void CameraLookAt(SHCameraComponent& camera, SHVec3 target) noexcept; void CameraLookAt(SHCameraComponent& camera, SHVec3 target) noexcept;
void UpdateEditorArm(double dt,bool active ,SHVec3 const& targetPos) noexcept; void UpdateEditorArm(double dt,bool active ,SHVec3 const& targetPos) noexcept;

View File

@ -25,4 +25,8 @@ constexpr SHEventIdentifier SH_SCENE_EXIT_POST { 16 };
constexpr SHEventIdentifier SH_GRAPHICS_LIGHT_ENABLE_SHADOW_EVENT { 17 }; constexpr SHEventIdentifier SH_GRAPHICS_LIGHT_ENABLE_SHADOW_EVENT { 17 };
constexpr SHEventIdentifier SH_BUTTON_CLICK_EVENT { 18 }; constexpr SHEventIdentifier SH_BUTTON_CLICK_EVENT { 18 };
constexpr SHEventIdentifier SH_PHYSICS_COLLIDER_DRAW_EVENT { 19 }; constexpr SHEventIdentifier SH_PHYSICS_COLLIDER_DRAW_EVENT { 19 };
constexpr SHEventIdentifier SH_WINDOW_RESIZE_EVENT { 20 };
constexpr SHEventIdentifier SH_BUTTON_RELEASE_EVENT { 21 };
constexpr SHEventIdentifier SH_BUTTON_HOVER_ENTER_EVENT { 22 };
constexpr SHEventIdentifier SH_BUTTON_HOVER_EXIT_EVENT { 23 };

View File

@ -14,4 +14,13 @@ namespace SHADE
//! Generate a renderer for the light component //! Generate a renderer for the light component
bool generateRenderer; bool generateRenderer;
}; };
struct SHWindowResizeEvent
{
// New width when window resizes
uint32_t resizeWidth;
// New height when window resizes
uint32_t resizeHeight;
};
} }

View File

@ -52,6 +52,12 @@ namespace SHADE
{SHPredefinedDescriptorTypes::RENDER_GRAPH_RESOURCE, 3}, {SHPredefinedDescriptorTypes::RENDER_GRAPH_RESOURCE, 3},
{SHPredefinedDescriptorTypes::RENDER_GRAPH_NODE_COMPUTE_RESOURCE, 4}, {SHPredefinedDescriptorTypes::RENDER_GRAPH_NODE_COMPUTE_RESOURCE, 4},
}); });
perSystemData[SHUtilities::ConvertEnum(SystemType::TRAJECTORY_RENDERING)].descMappings.AddMappings
({
{SHPredefinedDescriptorTypes::STATIC_DATA, 0},
{SHPredefinedDescriptorTypes::CAMERA, 1},
});
} }
void SHGraphicsPredefinedData::InitDummyPipelineLayouts(Handle<SHVkLogicalDevice> logicalDevice) noexcept void SHGraphicsPredefinedData::InitDummyPipelineLayouts(Handle<SHVkLogicalDevice> logicalDevice) noexcept
@ -222,6 +228,12 @@ namespace SHADE
SHGraphicsPredefinedData::PredefinedDescSetLayoutTypes::CAMERA | SHGraphicsPredefinedData::PredefinedDescSetLayoutTypes::CAMERA |
SHGraphicsPredefinedData::PredefinedDescSetLayoutTypes::LIGHTS SHGraphicsPredefinedData::PredefinedDescSetLayoutTypes::LIGHTS
); );
perSystemData[SHUtilities::ConvertEnum(SystemType::TRAJECTORY_RENDERING)].descSetLayouts = GetPredefinedDescSetLayouts
(
SHGraphicsPredefinedData::PredefinedDescSetLayoutTypes::STATIC_DATA |
SHGraphicsPredefinedData::PredefinedDescSetLayoutTypes::CAMERA
);
} }
void SHGraphicsPredefinedData::InitPredefinedVertexInputState(void) noexcept void SHGraphicsPredefinedData::InitPredefinedVertexInputState(void) noexcept

View File

@ -38,6 +38,7 @@ namespace SHADE
BATCHING_ANIM, BATCHING_ANIM,
TEXT_RENDERING, TEXT_RENDERING,
RENDER_GRAPH_NODE_COMPUTE, RENDER_GRAPH_NODE_COMPUTE,
TRAJECTORY_RENDERING,
NUM_TYPES NUM_TYPES
}; };
static constexpr int SYSTEM_TYPE_COUNT = static_cast<int>(SystemType::NUM_TYPES); static constexpr int SYSTEM_TYPE_COUNT = static_cast<int>(SystemType::NUM_TYPES);

View File

@ -64,6 +64,17 @@ namespace SHADE
/***************************************************************************/ /***************************************************************************/
static constexpr std::string_view DEFERRED_COMPOSITE_PASS = "Deferred Comp Pass"; static constexpr std::string_view DEFERRED_COMPOSITE_PASS = "Deferred Comp Pass";
/***************************************************************************/
/*!
\brief
Name of vfx render graph node.
*/
/***************************************************************************/
static constexpr std::string_view VFX_PASS = "Vfx Pass";
/***************************************************************************/ /***************************************************************************/
/*! /*!
@ -117,6 +128,7 @@ namespace SHADE
static constexpr std::string_view GBUFFER_WRITE_SUBPASS = "G-Buffer Write"; static constexpr std::string_view GBUFFER_WRITE_SUBPASS = "G-Buffer Write";
static constexpr std::string_view UI_SUBPASS = "UI"; static constexpr std::string_view UI_SUBPASS = "UI";
static constexpr std::string_view VFX_SUBPASS = "VFX";
static constexpr std::array USABLE_SUBPASSES = static constexpr std::array USABLE_SUBPASSES =
{ {
@ -282,6 +294,13 @@ namespace SHADE
*/ */
/***************************************************************************/ /***************************************************************************/
static constexpr uint32_t BONE_MATRIX_FIRST_INDEX = 8; static constexpr uint32_t BONE_MATRIX_FIRST_INDEX = 8;
/***************************************************************************/
/*!
\brief
Vertex buffer bindings for color
*/
/***************************************************************************/
static constexpr uint32_t TRAJECTORY_COLOR = 2;
static constexpr uint32_t CALCULATED_GLYPH_POSITION = 0; static constexpr uint32_t CALCULATED_GLYPH_POSITION = 0;
static constexpr uint32_t GLYPH_INDEX = 1; static constexpr uint32_t GLYPH_INDEX = 1;

View File

@ -129,6 +129,7 @@ namespace SHADE
//SHAssetManager::CompileAsset("../../Assets/Shaders/DeferredComposite_CS.glsl", false); //SHAssetManager::CompileAsset("../../Assets/Shaders/DeferredComposite_CS.glsl", false);
//SHAssetManager::CompileAsset("../../Assets/Shaders/ShadowMap_FS.glsl", false); //SHAssetManager::CompileAsset("../../Assets/Shaders/ShadowMap_FS.glsl", false);
//SHAssetManager::CompileAsset("../../Assets/Shaders/ShadowMap_FS.glsl", false);
//SHAssetManager::CompileAsset("../../Assets/Shaders/SSAO_CS.glsl", false); //SHAssetManager::CompileAsset("../../Assets/Shaders/SSAO_CS.glsl", false);
//SHAssetManager::CompileAsset("../../Assets/Shaders/SSAOBlur_CS.glsl", false); //SHAssetManager::CompileAsset("../../Assets/Shaders/SSAOBlur_CS.glsl", false);
//SHAssetManager::CompileAsset("../../Assets/Shaders/PureCopy_CS.glsl", false); //SHAssetManager::CompileAsset("../../Assets/Shaders/PureCopy_CS.glsl", false);
@ -137,7 +138,8 @@ namespace SHADE
//SHAssetManager::CompileAsset("../../Assets/Shaders/UI_VS.glsl", false); //SHAssetManager::CompileAsset("../../Assets/Shaders/UI_VS.glsl", false);
//SHAssetManager::CompileAsset("../../Assets/Shaders/UI_FS.glsl", false); //SHAssetManager::CompileAsset("../../Assets/Shaders/UI_FS.glsl", false);
//SHAssetManager::CompileAsset("../../Assets/Shaders/Text_VS.glsl", false); //SHAssetManager::CompileAsset("../../Assets/Shaders/Text_VS.glsl", false);
//SHAssetManager::CompileAsset("../../Assets/Shaders/Trajectory_VS.glsl", false);
//SHAssetManager::CompileAsset("../../Assets/Shaders/Trajectory_FS.glsl", false);
// Load Built In Shaders // Load Built In Shaders
static constexpr AssetID VS_DEFAULT = 39210065; defaultVertShader = SHResourceManager::LoadOrGet<SHVkShaderModule>(VS_DEFAULT); static constexpr AssetID VS_DEFAULT = 39210065; defaultVertShader = SHResourceManager::LoadOrGet<SHVkShaderModule>(VS_DEFAULT);
@ -155,6 +157,8 @@ namespace SHADE
static constexpr AssetID RENDER_SC_FS = 36869006; renderToSwapchainFS = SHResourceManager::LoadOrGet<SHVkShaderModule>(RENDER_SC_FS); static constexpr AssetID RENDER_SC_FS = 36869006; renderToSwapchainFS = SHResourceManager::LoadOrGet<SHVkShaderModule>(RENDER_SC_FS);
static constexpr AssetID SHADOW_MAP_VS = 44646107; shadowMapVS = SHResourceManager::LoadOrGet<SHVkShaderModule>(SHADOW_MAP_VS); static constexpr AssetID SHADOW_MAP_VS = 44646107; shadowMapVS = SHResourceManager::LoadOrGet<SHVkShaderModule>(SHADOW_MAP_VS);
static constexpr AssetID SHADOW_MAP_FS = 45925790; shadowMapFS = SHResourceManager::LoadOrGet<SHVkShaderModule>(SHADOW_MAP_FS); static constexpr AssetID SHADOW_MAP_FS = 45925790; shadowMapFS = SHResourceManager::LoadOrGet<SHVkShaderModule>(SHADOW_MAP_FS);
static constexpr AssetID TRAJECTORY_VS = 41042628; trajectoryVS = SHResourceManager::LoadOrGet<SHVkShaderModule>(TRAJECTORY_VS);
static constexpr AssetID TRAJECTORY_FS = 45635685; trajectoryFS = SHResourceManager::LoadOrGet<SHVkShaderModule>(TRAJECTORY_FS);
} }
@ -307,13 +311,24 @@ namespace SHADE
lightingSubSystem->PrepareShadowMapsForRead(cmdBuffer); lightingSubSystem->PrepareShadowMapsForRead(cmdBuffer);
}); });
/*-----------------------------------------------------------------------*/
/* VFX PASS */
/*-----------------------------------------------------------------------*/
auto vfxPass = renderGraph->AddNode(SHGraphicsConstants::RenderGraphEntityNames::VFX_PASS.data(), { "Scene", "Depth Buffer" }, { SHGraphicsConstants::RenderGraphEntityNames::GBUFFER_PASS.data(), SHGraphicsConstants::RenderGraphEntityNames::DEFERRED_COMPOSITE_PASS.data() });
auto vfxSubpass = vfxPass->AddSubpass("Vfx Subpass", worldViewport, worldRenderer);
vfxSubpass->AddColorOutput("Scene");
vfxSubpass->AddDepthOutput("Depth Buffer");
vfxSubpass->AddExteriorDrawCalls([=](Handle<SHVkCommandBuffer> cmdBuffer, Handle<SHRenderer> renderer, uint32_t frameIndex)
{
trajectoryRenderingSubSystem->Render(cmdBuffer, renderer, frameIndex);
});
/*-----------------------------------------------------------------------*/ /*-----------------------------------------------------------------------*/
/* DEBUG DRAW PASS INIT */ /* DEBUG DRAW PASS INIT */
/*-----------------------------------------------------------------------*/ /*-----------------------------------------------------------------------*/
// Set up Debug Draw Passes // Set up Debug Draw Passes
// - Depth Tested // - Depth Tested
auto debugDrawNodeDepth = renderGraph->AddNode(SHGraphicsConstants::RenderGraphEntityNames::DEBUG_DRAW_DEPTH_PASS.data(), {"Scene", "Depth Buffer"}, {SHGraphicsConstants::RenderGraphEntityNames::GBUFFER_PASS.data(), SHGraphicsConstants::RenderGraphEntityNames::DEFERRED_COMPOSITE_PASS.data()}); auto debugDrawNodeDepth = renderGraph->AddNode(SHGraphicsConstants::RenderGraphEntityNames::DEBUG_DRAW_DEPTH_PASS.data(), {"Scene", "Depth Buffer"}, { SHGraphicsConstants::RenderGraphEntityNames::VFX_PASS.data()/*, SHGraphicsConstants::RenderGraphEntityNames::DEFERRED_COMPOSITE_PASS.data()*/});
auto debugDrawDepthSubpass = debugDrawNodeDepth->AddSubpass("Debug Draw with Depth", worldViewport, worldRenderer); auto debugDrawDepthSubpass = debugDrawNodeDepth->AddSubpass("Debug Draw with Depth", worldViewport, worldRenderer);
debugDrawDepthSubpass->AddColorOutput("Scene"); debugDrawDepthSubpass->AddColorOutput("Scene");
debugDrawDepthSubpass->AddDepthOutput("Depth Buffer"); debugDrawDepthSubpass->AddDepthOutput("Depth Buffer");
@ -432,6 +447,11 @@ namespace SHADE
auto uiNode = renderGraph->GetNode(SHGraphicsConstants::RenderGraphEntityNames::SCREEN_SPACE_PASS.data()); auto uiNode = renderGraph->GetNode(SHGraphicsConstants::RenderGraphEntityNames::SCREEN_SPACE_PASS.data());
textRenderingSubSystem->Init(device, uiNode->GetRenderpass(), uiNode->GetSubpass(SHGraphicsConstants::RenderGraphEntityNames::UI_SUBPASS), descPool, textVS, textFS); textRenderingSubSystem->Init(device, uiNode->GetRenderpass(), uiNode->GetSubpass(SHGraphicsConstants::RenderGraphEntityNames::UI_SUBPASS), descPool, textVS, textFS);
trajectoryRenderingSubSystem = resourceManager.Create<SHTrajectoryRenderingSubSystem>();
auto vfxNode = renderGraph->GetNode(SHGraphicsConstants::RenderGraphEntityNames::SCREEN_SPACE_PASS.data());
trajectoryRenderingSubSystem->Init(device, vfxNode->GetRenderpass(), vfxNode->GetSubpass(SHGraphicsConstants::RenderGraphEntityNames::UI_SUBPASS), trajectoryVS, trajectoryFS);
SHGlobalDescriptorSets::SetLightingSubSystem(lightingSubSystem); SHGlobalDescriptorSets::SetLightingSubSystem(lightingSubSystem);
} }
@ -566,6 +586,7 @@ namespace SHADE
} }
textRenderingSubSystem->Run(frameIndex); textRenderingSubSystem->Run(frameIndex);
trajectoryRenderingSubSystem->Run(frameIndex);
for (auto renderer : renderers) for (auto renderer : renderers)
@ -588,19 +609,19 @@ namespace SHADE
static bool shadowAdded = false; static bool shadowAdded = false;
if (shadowAdded == false/* && SHInputManager::GetKey(SHInputManager::SH_KEYCODE::B)*/) //if (shadowAdded == false && SHInputManager::GetKey(SHInputManager::SH_KEYCODE::B))
{
shadowAdded = true;
auto& lightComps = SHComponentManager::GetDense<SHLightComponent>();
if (lightComps.size() > 2)
{
lightComps[2].SetEnableShadow(true);
}
//for (auto& comp : lightComps)
//{ //{
// shadowAdded = true;
// auto& lightComps = SHComponentManager::GetDense<SHLightComponent>();
// //if (lightComps.size() > 2)
// //{
// // lightComps[2].SetEnableShadow(true);
// //}
// for (auto& comp : lightComps)
// {
// comp.SetEnableShadow(true); // comp.SetEnableShadow(true);
// }
//} //}
}
renderGraph->Begin(frameIndex); renderGraph->Begin(frameIndex);
auto cmdBuffer = renderGraph->GetCommandBuffer(frameIndex); auto cmdBuffer = renderGraph->GetCommandBuffer(frameIndex);
@ -781,7 +802,8 @@ namespace SHADE
auto const& EVENT_DATA = reinterpret_cast<const SHEventSpec<SHLightEnableShadowEvent>*>(eventPtr.get())->data; auto const& EVENT_DATA = reinterpret_cast<const SHEventSpec<SHLightEnableShadowEvent>*>(eventPtr.get())->data;
auto* lightComp = SHComponentManager::GetComponent<SHLightComponent>(EVENT_DATA->lightEntity); auto* lightComp = SHComponentManager::GetComponent<SHLightComponent>(EVENT_DATA->lightEntity);
std::string resourceName = "ShadowMap " + std::to_string(EVENT_DATA->lightEntity); std::string depthResourceName = "ShadowMap_Depth " + std::to_string(EVENT_DATA->lightEntity);
std::string shadowMapResourceName = "ShadowMap " + std::to_string(EVENT_DATA->lightEntity);
Handle<SHSubpass> companionSubpass = renderGraph->GetNode(SHGraphicsConstants::RenderGraphEntityNames::GBUFFER_PASS.data())->GetSubpass(SHGraphicsConstants::RenderGraphEntityNames::GBUFFER_WRITE_SUBPASS); Handle<SHSubpass> companionSubpass = renderGraph->GetNode(SHGraphicsConstants::RenderGraphEntityNames::GBUFFER_PASS.data())->GetSubpass(SHGraphicsConstants::RenderGraphEntityNames::GBUFFER_WRITE_SUBPASS);
if (EVENT_DATA->generateRenderer) if (EVENT_DATA->generateRenderer)
@ -795,14 +817,16 @@ namespace SHADE
} }
// Add the shadow map resource to the graph // Add the shadow map resource to the graph
renderGraph->AddResource(resourceName, {SH_RENDER_GRAPH_RESOURCE_FLAGS::DEPTH, SH_RENDER_GRAPH_RESOURCE_FLAGS::INPUT}, false, SHLightingSubSystem::SHADOW_MAP_WIDTH, SHLightingSubSystem::SHADOW_MAP_HEIGHT, vk::Format::eD32Sfloat); renderGraph->AddResource(depthResourceName, {SH_RENDER_GRAPH_RESOURCE_FLAGS::DEPTH}, false, SHLightingSubSystem::SHADOW_MAP_WIDTH, SHLightingSubSystem::SHADOW_MAP_HEIGHT, vk::Format::eD32Sfloat);
renderGraph->AddResource(shadowMapResourceName, { SH_RENDER_GRAPH_RESOURCE_FLAGS::COLOR, SH_RENDER_GRAPH_RESOURCE_FLAGS::INPUT }, false, SHLightingSubSystem::SHADOW_MAP_WIDTH, SHLightingSubSystem::SHADOW_MAP_HEIGHT, vk::Format::eR32G32B32A32Sfloat);
// link resource to node. This means linking the resource and regenerating the node's renderpass and framebuffer. // link resource to node. This means linking the resource and regenerating the node's renderpass and framebuffer.
auto shadowMapNode = renderGraph->AddNodeAfter(SHGraphicsConstants::RenderGraphEntityNames::SHADOW_MAP_PASS.data() + resourceName, {resourceName.c_str()}, SHGraphicsConstants::RenderGraphEntityNames::GBUFFER_PASS.data()); auto shadowMapNode = renderGraph->AddNodeAfter(SHGraphicsConstants::RenderGraphEntityNames::SHADOW_MAP_PASS.data() + shadowMapResourceName, {depthResourceName.c_str(), shadowMapResourceName.c_str()}, SHGraphicsConstants::RenderGraphEntityNames::GBUFFER_PASS.data());
// Add a subpass to render to that shadow map // Add a subpass to render to that shadow map
auto newSubpass = shadowMapNode->RuntimeAddSubpass(resourceName + " Subpass", shadowMapViewport, lightComp->GetRenderer()); auto newSubpass = shadowMapNode->RuntimeAddSubpass(shadowMapResourceName + " Subpass", shadowMapViewport, lightComp->GetRenderer());
newSubpass->AddDepthOutput(resourceName, SH_RENDER_GRAPH_RESOURCE_FLAGS::DEPTH); newSubpass->AddColorOutput(shadowMapResourceName);
newSubpass->AddDepthOutput(depthResourceName, SH_RENDER_GRAPH_RESOURCE_FLAGS::DEPTH);
// regenerate the node // regenerate the node
shadowMapNode->RuntimeStandaloneRegenerate(); shadowMapNode->RuntimeStandaloneRegenerate();
@ -828,7 +852,7 @@ namespace SHADE
newSubpass->SetCompanionSubpass(companionSubpass, shadowMapPipeline); // set companion subpass and pipeline newSubpass->SetCompanionSubpass(companionSubpass, shadowMapPipeline); // set companion subpass and pipeline
// add the shadow map to the lighting system // add the shadow map to the lighting system
uint32_t const NEW_SHADOW_MAP_INDEX = lightingSubSystem->AddShadowMap(renderGraph->GetRenderGraphResource(resourceName), EVENT_DATA->lightEntity); uint32_t const NEW_SHADOW_MAP_INDEX = lightingSubSystem->AddShadowMap(renderGraph->GetRenderGraphResource(shadowMapResourceName), EVENT_DATA->lightEntity);
auto nodeCompute = renderGraph->GetNode(SHGraphicsConstants::RenderGraphEntityNames::DEFERRED_COMPOSITE_PASS.data())->GetNodeCompute(SHGraphicsConstants::RenderGraphEntityNames::DEFERRED_COMPOSITE_COMPUTE.data()); auto nodeCompute = renderGraph->GetNode(SHGraphicsConstants::RenderGraphEntityNames::DEFERRED_COMPOSITE_PASS.data())->GetNodeCompute(SHGraphicsConstants::RenderGraphEntityNames::DEFERRED_COMPOSITE_COMPUTE.data());
nodeCompute->ModifyWriteDescImageComputeResource(SHGraphicsConstants::DescriptorSetBindings::SHADOW_MAP_IMAGE_SAMPLER_DATA, lightingSubSystem->GetViewSamplerLayout(NEW_SHADOW_MAP_INDEX), NEW_SHADOW_MAP_INDEX); nodeCompute->ModifyWriteDescImageComputeResource(SHGraphicsConstants::DescriptorSetBindings::SHADOW_MAP_IMAGE_SAMPLER_DATA, lightingSubSystem->GetViewSamplerLayout(NEW_SHADOW_MAP_INDEX), NEW_SHADOW_MAP_INDEX);
@ -1154,6 +1178,14 @@ namespace SHADE
#ifdef SHEDITOR #ifdef SHEDITOR
cameraSystem->GetEditorCamera()->SetWidth(static_cast<float>(resizeWidth)); cameraSystem->GetEditorCamera()->SetWidth(static_cast<float>(resizeWidth));
cameraSystem->GetEditorCamera()->SetHeight(static_cast<float>(resizeHeight)); cameraSystem->GetEditorCamera()->SetHeight(static_cast<float>(resizeHeight));
// Create new event and broadcast it
SHWindowResizeEvent newEvent;
newEvent.resizeWidth = resizeWidth;
newEvent.resizeHeight = resizeHeight;
SHEventManager::BroadcastEvent<SHWindowResizeEvent>(newEvent, SH_WINDOW_RESIZE_EVENT);
#else #else
#endif #endif

View File

@ -36,6 +36,7 @@ of DigiPen Institute of Technology is prohibited.
#include "Graphics/MiddleEnd/TextRendering/SHFontLibrary.h" #include "Graphics/MiddleEnd/TextRendering/SHFontLibrary.h"
#include "Graphics/MiddleEnd/Interface/SHRenderer.h" #include "Graphics/MiddleEnd/Interface/SHRenderer.h"
#include "Graphics/Events/SHGraphicsEvents.h" #include "Graphics/Events/SHGraphicsEvents.h"
#include "Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderingSubSystem.h"
namespace SHADE namespace SHADE
{ {
@ -470,6 +471,8 @@ namespace SHADE
Handle<SHVkShaderModule> renderToSwapchainFS; Handle<SHVkShaderModule> renderToSwapchainFS;
Handle<SHVkShaderModule> shadowMapVS; Handle<SHVkShaderModule> shadowMapVS;
Handle<SHVkShaderModule> shadowMapFS; Handle<SHVkShaderModule> shadowMapFS;
Handle<SHVkShaderModule> trajectoryVS;
Handle<SHVkShaderModule> trajectoryFS;
// Fonts // Fonts
Handle<SHFont> testFont; Handle<SHFont> testFont;
@ -505,6 +508,7 @@ namespace SHADE
Handle<SHPostOffscreenRenderSystem> postOffscreenRenderSubSystem; Handle<SHPostOffscreenRenderSystem> postOffscreenRenderSubSystem;
Handle<SHLightingSubSystem> lightingSubSystem; Handle<SHLightingSubSystem> lightingSubSystem;
Handle<SHTextRenderingSubSystem> textRenderingSubSystem; Handle<SHTextRenderingSubSystem> textRenderingSubSystem;
Handle<SHTrajectoryRenderingSubSystem> trajectoryRenderingSubSystem;
Handle<SHSSAO> ssaoStorage; Handle<SHSSAO> ssaoStorage;
uint32_t resizeWidth = 1; uint32_t resizeWidth = 1;

View File

@ -395,7 +395,11 @@ namespace SHADE
switch (lightComp->GetLightData().type) switch (lightComp->GetLightData().type)
{ {
case SH_LIGHT_TYPE::DIRECTIONAL: case SH_LIGHT_TYPE::DIRECTIONAL:
return SHMatrix::Transpose(SHMatrix::LookAtLH(lightComp->GetLightData().position, SHVec3::Normalise (lightComp->GetLightData().direction), SHVec3(0.0f, -1.0f, 0.0f))); {
SHTransformComponent* transform = SHComponentManager::GetComponent<SHTransformComponent>(lightComp->GetEID());
return SHMatrix::Transpose(SHMatrix::LookAtLH(transform->GetWorldPosition(), SHVec3::Normalise(lightComp->GetLightData().direction), SHVec3(0.0f, -1.0f, 0.0f)));
}
//return SHMatrix::Transpose(SHMatrix::LookAtLH(/*lightComp->GetLightData().position*/SHVec3(1.27862f, 4.78952f, 4.12811f), SHVec3(-0.280564f, -0.66262f, -0.69422f), SHVec3(0.0f, -1.0f, 0.0f))); //return SHMatrix::Transpose(SHMatrix::LookAtLH(/*lightComp->GetLightData().position*/SHVec3(1.27862f, 4.78952f, 4.12811f), SHVec3(-0.280564f, -0.66262f, -0.69422f), SHVec3(0.0f, -1.0f, 0.0f)));
case SH_LIGHT_TYPE::POINT: case SH_LIGHT_TYPE::POINT:
return {}; return {};
@ -518,7 +522,7 @@ namespace SHADE
if (auto renderer = light.GetRenderer()) if (auto renderer = light.GetRenderer())
{ {
//SHMatrix orthoMatrix = SHMatrix::OrthographicRH() //SHMatrix orthoMatrix = SHMatrix::OrthographicRH()
renderer->UpdateDataManual(frameIndex, GetViewMatrix(&light), SHMatrix::OrthographicLH(10.0f, 10.0f, 1.0f, 50.0f)); renderer->UpdateDataManual(frameIndex, GetViewMatrix(&light), SHMatrix::OrthographicLH(12.0f, 12.0f, 1.0f, 80.0f));
} }
auto enumValue = SHUtilities::ConvertEnum(light.GetLightData().type); auto enumValue = SHUtilities::ConvertEnum(light.GetLightData().type);
@ -627,16 +631,16 @@ namespace SHADE
// add to barriers // add to barriers
shadowMapMemoryBarriers.push_back (vk::ImageMemoryBarrier shadowMapMemoryBarriers.push_back (vk::ImageMemoryBarrier
{ {
.srcAccessMask = vk::AccessFlagBits::eDepthStencilAttachmentWrite, .srcAccessMask = vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eColorAttachmentRead,
.dstAccessMask = vk::AccessFlagBits::eShaderRead, .dstAccessMask = vk::AccessFlagBits::eShaderRead,
.oldLayout = vk::ImageLayout::eDepthAttachmentOptimal, .oldLayout = vk::ImageLayout::eColorAttachmentOptimal,
.newLayout = vk::ImageLayout::eShaderReadOnlyOptimal, .newLayout = vk::ImageLayout::eShaderReadOnlyOptimal,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = newShadowMap->GetImage()->GetVkImage(), .image = newShadowMap->GetImage()->GetVkImage(),
.subresourceRange = vk::ImageSubresourceRange .subresourceRange = vk::ImageSubresourceRange
{ {
.aspectMask = vk::ImageAspectFlagBits::eDepth, .aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0, .baseMipLevel = 0,
.levelCount = 1, .levelCount = 1,
.baseArrayLayer = 0, .baseArrayLayer = 0,
@ -651,7 +655,7 @@ namespace SHADE
void SHLightingSubSystem::PrepareShadowMapsForRead(Handle<SHVkCommandBuffer> cmdBuffer) noexcept void SHLightingSubSystem::PrepareShadowMapsForRead(Handle<SHVkCommandBuffer> cmdBuffer) noexcept
{ {
// Issue barrier to transition shadow maps for reading in compute shader // Issue barrier to transition shadow maps for reading in compute shader
cmdBuffer->PipelineBarrier(vk::PipelineStageFlagBits::eEarlyFragmentTests | vk::PipelineStageFlagBits::eLateFragmentTests, vk::PipelineStageFlagBits::eComputeShader, {}, {}, {}, shadowMapMemoryBarriers); cmdBuffer->PipelineBarrier(vk::PipelineStageFlagBits::eColorAttachmentOutput, vk::PipelineStageFlagBits::eComputeShader, {}, {}, {}, shadowMapMemoryBarriers);
} }
//void SHLightingSubSystem::HandleResize(Handle<SHRenderGraphNodeCompute> compute) noexcept //void SHLightingSubSystem::HandleResize(Handle<SHRenderGraphNodeCompute> compute) noexcept

View File

@ -0,0 +1,41 @@
#pragma once
#include "Resource/SHHandle.h"
#include "Graphics/Pipeline/SHPipelineState.h"
#include "Math/SHMatrix.h"
namespace SHADE
{
class SHVkLogicalDevice;
class SHVkDescriptorPool;
class SHVkDescriptorSetGroup;
class SHVkDescriptorSetLayout;
class SHVkBuffer;
class SHLightComponent;
class SHVkCommandBuffer;
class SHVkPipeline;
class SHVkPipelineLayout;
class SHVkRenderpass;
class SHSubpass;
class SHVkShaderModule;
class SHRenderer;
class SHParticleSubSystem
{
private:
Handle<SHVkLogicalDevice> logicalDevice;
public:
void Init(Handle<SHVkLogicalDevice> device, Handle<SHVkRenderpass> compatibleRenderpass, Handle<SHSubpass> subpass) noexcept;
void Run(uint32_t frameIndex) noexcept;
void Render(Handle<SHVkCommandBuffer> cmdBuffer, Handle<SHRenderer> renderer, uint32_t frameIndex) noexcept;
void Exit(void) noexcept;
};
}

View File

@ -0,0 +1,7 @@
#include "SHpch.h"
#include "SHParticleSubSustem.h"
namespace SHADE
{
}

View File

@ -13,6 +13,7 @@
#include "Math/Transform/SHTransformComponent.h" #include "Math/Transform/SHTransformComponent.h"
#include "Graphics/MiddleEnd/GlobalData/SHGlobalDescriptorSets.h" #include "Graphics/MiddleEnd/GlobalData/SHGlobalDescriptorSets.h"
#include "Graphics/MiddleEnd/Interface/SHRenderer.h" #include "Graphics/MiddleEnd/Interface/SHRenderer.h"
#include "Scene/SHSceneManager.h"
namespace SHADE namespace SHADE
{ {
@ -184,6 +185,9 @@ namespace SHADE
for (auto& comp : textRendererComps) for (auto& comp : textRendererComps)
{ {
if (!SHSceneManager::CheckNodeAndComponentsActive<SHTextRenderableComponent>(comp.GetEID()))
continue;
auto* transform = SHComponentManager::GetComponent<SHTransformComponent>(comp.GetEID()); auto* transform = SHComponentManager::GetComponent<SHTransformComponent>(comp.GetEID());
Handle<SHFont> fontHandle = comp.fontHandle; Handle<SHFont> fontHandle = comp.fontHandle;

View File

@ -0,0 +1,96 @@
#include "SHpch.h"
#include "SHTrajectoryRenderableComponent.h"
namespace SHADE
{
/***************************************************************************/
/*!
\brief
On create the text has nothing.
*/
/***************************************************************************/
void SHTrajectoryRenderableComponent::OnCreate(void)
{
}
void SHTrajectoryRenderableComponent::OnDestroy(void)
{
}
void SHTrajectoryRenderableComponent::ClearPositions(void) noexcept
{
positions.clear();
}
bool SHTrajectoryRenderableComponent::HasPositions(void) const noexcept
{
return !positions.empty();
}
std::vector<SHVec3> SHTrajectoryRenderableComponent::GetPositions(void) const noexcept
{
return positions;
}
Handle<SHMesh> SHTrajectoryRenderableComponent::GetMesh(void) const noexcept
{
return mesh;
}
SHVec4 const& SHTrajectoryRenderableComponent::GetStartColor(void) const noexcept
{
return startColor;
}
SHVec4 const& SHTrajectoryRenderableComponent::GetEndColor(void) const noexcept
{
return endColor;
}
float SHTrajectoryRenderableComponent::GetColorEvolveRate(void) const noexcept
{
return colorEvolveRate;
}
void SHTrajectoryRenderableComponent::SetMesh(Handle<SHMesh> newMesh) noexcept
{
mesh = newMesh;
}
void SHTrajectoryRenderableComponent::SetPositions(std::vector<SHVec3> const& inPositions) noexcept
{
positions = inPositions;
}
void SHTrajectoryRenderableComponent::SetStartColor(SHVec4 color) noexcept
{
startColor = color;
}
void SHTrajectoryRenderableComponent::SetEndColor(SHVec4 color) noexcept
{
endColor = color;
}
void SHTrajectoryRenderableComponent::SetColorEvolveRate(float rate) noexcept
{
colorEvolveRate = rate;
}
}
namespace rttr
{
RTTR_REGISTRATION
{
using namespace SHADE;
registration::class_<SHTrajectoryRenderableComponent>("Trajectory Renderer Component");
};
}

View File

@ -0,0 +1,58 @@
#pragma once
#include "Math/Vector/SHVec3.h"
#include "Math/Vector/SHVec4.h"
#include "Resource/SHHandle.h"
#include "ECS_Base/Components/SHComponent.h"
#include <rttr/registration>
namespace SHADE
{
class SHMesh;
class SHTrajectoryRenderableComponent : public SHComponent
{
private:
//! Mesh used to render the trajectory
Handle<SHMesh> mesh;
//! positions to plot for rendering. Will be cleared every frame.
std::vector<SHVec3> positions;
//! Starting color of the trajectory
SHVec4 startColor;
//! Color the trajectory should evolve to the longer it is
SHVec4 endColor;
//! evolving rate of the color
float colorEvolveRate;
public:
/*-----------------------------------------------------------------------*/
/* PRIVATE MEMBER FUNCTIONS */
/*-----------------------------------------------------------------------*/
void SetMesh(Handle<SHMesh> newMesh) noexcept;
void SetPositions (std::vector<SHVec3> const& inPositions) noexcept;
void SetStartColor(SHVec4 startColor) noexcept;
void SetEndColor (SHVec4 endColor) noexcept;
void SetColorEvolveRate (float rate) noexcept;
std::vector<SHVec3> GetPositions (void) const noexcept;
Handle<SHMesh> GetMesh (void) const noexcept;
SHVec4 const& GetStartColor (void) const noexcept;
SHVec4 const& GetEndColor (void) const noexcept;
float GetColorEvolveRate (void) const noexcept;
void OnCreate(void) override final;
void OnDestroy(void) override final;
void ClearPositions(void) noexcept;
bool HasPositions(void) const noexcept;
RTTR_ENABLE()
};
}

View File

@ -0,0 +1,191 @@
#include "SHpch.h"
#include "SHTrajectoryRenderingSubSystem.h"
#include "ECS_Base/Managers/SHComponentManager.h"
#include "Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderableComponent.h"
#include "Graphics/Devices/SHVkLogicalDevice.h"
#include "Math/Transform/SHTransformComponent.h"
#include "Graphics\MiddleEnd\Interface\SHMeshLibrary.h"
#include "Graphics/SHVkUtil.h"
#include "Graphics/MiddleEnd/GlobalData/SHGraphicsPredefinedData.h"
#include "Graphics/Pipeline/SHVkPipeline.h"
#include "Graphics/RenderGraph/SHSubpass.h"
#include "Graphics/MiddleEnd/GlobalData/SHGlobalDescriptorSets.h"
#include "Graphics/MiddleEnd/Interface/SHRenderer.h"
namespace SHADE
{
void SHTrajectoryRenderingSubSystem::Init(Handle<SHVkLogicalDevice> device, Handle<SHVkRenderpass> compatibleRenderpass, Handle<SHSubpass> subpass, Handle<SHVkShaderModule> trajectoryVS, Handle<SHVkShaderModule> trajectoryFS) noexcept
{
logicalDevice = device;
SHComponentManager::CreateComponentSparseSet<SHTrajectoryRenderableComponent>();
// prepare pipeline layout params
SHPipelineLayoutParams plParams
{
.shaderModules = {trajectoryVS, trajectoryFS},
.predefinedDescSetLayouts = SHGraphicsPredefinedData::GetSystemData(SHGraphicsPredefinedData::SystemType::TRAJECTORY_RENDERING).descSetLayouts
};
pipelineLayout = logicalDevice->CreatePipelineLayout(plParams);
// Create pipeline
pipeline = logicalDevice->CreateGraphicsPipeline(pipelineLayout, nullptr, compatibleRenderpass, subpass);
// vertex input state of the pipeline
SHVertexInputState vertexInputState;
vertexInputState.AddBinding(false, false, { SHVertexAttribute(SHAttribFormat::FLOAT_3D) }); // Attribute positions at binding 0
vertexInputState.AddBinding(false, false, { SHVertexAttribute(SHAttribFormat::FLOAT_2D) }); // Attribute uv at binding 1
vertexInputState.AddBinding(true, true, { SHVertexAttribute(SHAttribFormat::FLOAT_4D) }); // Instanced attribute color at binding 2
vertexInputState.AddBinding(true, true, { SHVertexAttribute(SHAttribFormat::MAT_4D) }); // Instanced Transform at binding 3 - 6 (4 slots)
pipeline->GetPipelineState().SetVertexInputState(vertexInputState);
SHColorBlendState colorBlendState{};
colorBlendState.logic_op_enable = VK_FALSE;
colorBlendState.logic_op = vk::LogicOp::eCopy;
auto const& subpassColorReferences = subpass->GetColorAttachmentReferences();
colorBlendState.attachments.reserve(static_cast<uint32_t>(subpassColorReferences.size()));
for (auto& att : subpassColorReferences)
{
colorBlendState.attachments.push_back(vk::PipelineColorBlendAttachmentState
{
.blendEnable = SHVkUtil::IsBlendCompatible(subpass->GetFormatFromAttachmentReference(att.attachment)) ? true : false,
.srcColorBlendFactor = vk::BlendFactor::eSrcAlpha,
.dstColorBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha,
.colorBlendOp = vk::BlendOp::eAdd,
.srcAlphaBlendFactor = vk::BlendFactor::eOne,
.dstAlphaBlendFactor = vk::BlendFactor::eZero,
.alphaBlendOp = vk::BlendOp::eAdd,
.colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA,
}
);
}
pipeline->GetPipelineState().SetColorBlenState(colorBlendState);
}
void SHTrajectoryRenderingSubSystem::Run(uint32_t frameIndex) noexcept
{
auto& comps = SHComponentManager::GetDense<SHTrajectoryRenderableComponent>();
for (auto& comp : comps)
{
comp.SetPositions(std::vector
{
SHVec3 {},
SHVec3 {}
});
// If has positions, feed data to buffer.
if (comp.HasPositions())
{
SHTransformComponent* transform = SHComponentManager::GetComponent_s<SHTransformComponent>(comp.GetEID());
if (transform)
{
// convenient variable
SHVec4 const& startColor = comp.GetStartColor();
SHVec4 const& endColor = comp.GetEndColor();
float colorEvolveRate = comp.GetColorEvolveRate();
// trs to be reused
SHMatrix trs = transform->GetTRS();
// starting color of trajectory
SHVec4 currentColor = comp.GetStartColor();
// Start from 0 and slowly evolve to 1
float lerpValue = 0.0f;
// Will be used for baseInstance later
uint32_t oldTransformDataSize = transformData.size();
auto meshHandle = comp.GetMesh();
auto const& positions = comp.GetPositions();
for (auto& pos : positions)
{
// modify position and reuse matrix
trs.m[3][0] = pos.x;
trs.m[3][1] = pos.y;
trs.m[3][2] = pos.z;
transformData.push_back(trs);
colorData.push_back(currentColor);
// evolve color
currentColor = SHVec4::Lerp(startColor, endColor, lerpValue);
// evolve lerp value and clamp to 1
lerpValue = std::max (1.0f, lerpValue + colorEvolveRate);
}
// add draw data for this trajectory
drawData.push_back(vk::DrawIndexedIndirectCommand
{
.indexCount = meshHandle->IndexCount,
.instanceCount = static_cast<uint32_t>(transformData.size()) - oldTransformDataSize,
.firstIndex = meshHandle->FirstIndex,
.vertexOffset = meshHandle->FirstVertex,
.firstInstance = oldTransformDataSize
});
}
}
// clear at the end of every frame since data is already in buffers
comp.ClearPositions();
}
if (!transformData.empty())
{
// read transform data to buffer
// read draw data to buffer
SHVkUtil::EnsureBufferAndCopyHostVisibleData(logicalDevice, transformBuffer, transformData.data(), sizeof (SHMatrix) * transformData.size(), vk::BufferUsageFlagBits::eVertexBuffer, "Trajectory System Transform Buffer");
SHVkUtil::EnsureBufferAndCopyHostVisibleData(logicalDevice, drawDataBuffer, drawData.data(), sizeof(vk::DrawIndexedIndirectCommand) * drawData.size(), vk::BufferUsageFlagBits::eIndirectBuffer, "Trajectory System Draw Data Buffer");
SHVkUtil::EnsureBufferAndCopyHostVisibleData(logicalDevice, colorBuffer, colorData.data(), sizeof(SHVec4) * colorData.size(), vk::BufferUsageFlagBits::eVertexBuffer, "Trajectory System Color Data Buffer");
}
}
void SHTrajectoryRenderingSubSystem::Render(Handle<SHVkCommandBuffer> cmdBuffer, Handle<SHRenderer> renderer, uint32_t frameIndex) noexcept
{
if (!transformData.empty())
{
auto const& mappings = SHGraphicsPredefinedData::GetMappings(SHGraphicsPredefinedData::SystemType::TRAJECTORY_RENDERING);
uint32_t staticGlobalSetIndex = mappings.at(SHPredefinedDescriptorTypes::STATIC_DATA);
uint32_t cameraSetIndex = mappings.at(SHPredefinedDescriptorTypes::CAMERA);
cmdBuffer->BindPipeline(pipeline);
// Bind global data
SHGlobalDescriptorSets::BindStaticGlobalData(cmdBuffer, SH_PIPELINE_TYPE::GRAPHICS, staticGlobalSetIndex);
// Bind camera data
renderer->BindDescriptorSet(cmdBuffer, SH_PIPELINE_TYPE::GRAPHICS, cameraSetIndex, frameIndex);
// Bind color vertex buffer
cmdBuffer->BindVertexBuffer(SHGraphicsConstants::VertexBufferBindings::TRAJECTORY_COLOR, colorBuffer, 0);
// call draw call
cmdBuffer->DrawMultiIndirect(drawDataBuffer, drawData.size());
// clear CPU transform and draw data
transformData.clear();
drawData.clear();
colorData.clear();
}
}
void SHTrajectoryRenderingSubSystem::Exit(void) noexcept
{
}
}

View File

@ -0,0 +1,66 @@
#pragma once
#include "Resource/SHHandle.h"
#include "Graphics/Pipeline/SHPipelineState.h"
#include "Math/SHMatrix.h"
namespace SHADE
{
class SHVkLogicalDevice;
class SHVkDescriptorPool;
class SHVkDescriptorSetGroup;
class SHVkDescriptorSetLayout;
class SHVkBuffer;
class SHLightComponent;
class SHVkCommandBuffer;
class SHVkPipeline;
class SHVkPipelineLayout;
class SHVkRenderpass;
class SHSubpass;
class SHVkShaderModule;
class SHRenderer;
class SHTrajectoryRenderingSubSystem
{
private:
Handle<SHVkLogicalDevice> logicalDevice;
//! Every trajectory renderable will have one of these
std::vector<vk::DrawIndexedIndirectCommand> drawData;
//! For the MDI call
Handle<SHVkBuffer> drawDataBuffer;
//! matrix data to copy into buffer
std::vector<SHMatrix> transformData;
//! All trajectory renderables will use this transform buffer
Handle<SHVkBuffer> transformBuffer;
//! Each object will have their own color data
std::vector<SHVec4> colorData;
//! buffer to hold color data for objects
Handle<SHVkBuffer> colorBuffer;
//! Pipeline for rendering the trajectories
Handle<SHVkPipeline> pipeline;
//! Pipeline layout for the pipeline
Handle<SHVkPipelineLayout> pipelineLayout;
public:
void Init (Handle<SHVkLogicalDevice> device, Handle<SHVkRenderpass> compatibleRenderpass, Handle<SHSubpass> subpass, Handle<SHVkShaderModule> textVS, Handle<SHVkShaderModule> textFS) noexcept;
void Run(uint32_t frameIndex) noexcept;
void Render(Handle<SHVkCommandBuffer> cmdBuffer, Handle<SHRenderer> renderer, uint32_t frameIndex) noexcept;
void Exit(void) noexcept;
};
}

View File

@ -185,12 +185,40 @@ namespace SHADE
void SHWindow::SetMouseVisible(bool show) void SHWindow::SetMouseVisible(bool show)
{ {
ShowCursor(show ? TRUE : FALSE); if (GetActiveWindow() == wndHWND)
ShowCursor(show);
} }
void SHWindow::SetMousePosition(unsigned x, unsigned y) void SHWindow::SetMousePosition(int x, int y)
{ {
SetCursorPos(x, y); if(GetActiveWindow() == wndHWND)
{
//if(x == -1)
// x = GetSystemMetrics(SM_CXSCREEN) * 0.5;
//if (y == -1)
// y = GetSystemMetrics(SM_CYSCREEN) * 0.5;
//SetCursorPos(x, y);
}
}
void SHWindow::ClipMouseCursor(int left, int top, int right, int bottom)
{
if (GetActiveWindow() == wndHWND)
{
RECT rect{};
if (left == 0 || right == 0)
{
GetClientRect(wndHWND, &rect);
}
else
{
rect.left = left;
rect.right = right;
rect.top = top;
rect.bottom = bottom;
}
ClipCursor(&rect);
}
} }
//unsigned SHWindow::GetBGColor() //unsigned SHWindow::GetBGColor()

View File

@ -106,7 +106,9 @@ namespace SHADE
void SetMouseVisible(bool show); void SetMouseVisible(bool show);
void SetMousePosition(unsigned x, unsigned y); void SetMousePosition(int x = -1, int y = -1);
void ClipMouseCursor(int left = 0, int top = 0, int right = 0, int bottom = 0);
//unsigned GetBGColor(); //unsigned GetBGColor();
@ -144,7 +146,6 @@ namespace SHADE
void SetHWND(HWND hwnd); void SetHWND(HWND hwnd);
HWND wndHWND = nullptr; HWND wndHWND = nullptr;
HINSTANCE hInstance = nullptr; HINSTANCE hInstance = nullptr;

View File

@ -18,6 +18,7 @@
#include "Graphics/MiddleEnd/Interface/SHDebugDrawSystem.h" #include "Graphics/MiddleEnd/Interface/SHDebugDrawSystem.h"
#include "Math/Transform/SHTransformComponent.h" #include "Math/Transform/SHTransformComponent.h"
#include "Physics/System/SHPhysicsSystem.h" #include "Physics/System/SHPhysicsSystem.h"
#include "Scene/SHSceneManager.h"
#include "Tools/Utilities/SHUtilities.h" #include "Tools/Utilities/SHUtilities.h"
namespace SHADE namespace SHADE
@ -53,14 +54,21 @@ namespace SHADE
{ {
const auto& COLLIDER_COMPONENT_DENSE = SHComponentManager::GetDense<SHColliderComponent>(); const auto& COLLIDER_COMPONENT_DENSE = SHComponentManager::GetDense<SHColliderComponent>();
for (const auto& COLLIDER_COMPONENT : COLLIDER_COMPONENT_DENSE) for (const auto& COLLIDER_COMPONENT : COLLIDER_COMPONENT_DENSE)
{
if (SHSceneManager::CheckNodeAndComponentsActive<SHColliderComponent>(COLLIDER_COMPONENT.GetEID()))
drawCollider(debugDrawSystem, COLLIDER_COMPONENT); drawCollider(debugDrawSystem, COLLIDER_COMPONENT);
} }
}
else if (!physicsDebugDrawSystem->collidersToDraw.empty()) else if (!physicsDebugDrawSystem->collidersToDraw.empty())
{ {
for (const auto EID : physicsDebugDrawSystem->collidersToDraw) for (const auto EID : physicsDebugDrawSystem->collidersToDraw)
{
if (SHSceneManager::CheckNodeAndHasComponentsActive<SHColliderComponent>(EID))
drawCollider(debugDrawSystem, *SHComponentManager::GetComponent<SHColliderComponent>(EID)); drawCollider(debugDrawSystem, *SHComponentManager::GetComponent<SHColliderComponent>(EID));
} }
}
auto* physicsSystem = SHSystemManager::GetSystem<SHPhysicsSystem>(); auto* physicsSystem = SHSystemManager::GetSystem<SHPhysicsSystem>();
if (!physicsSystem) if (!physicsSystem)
return; return;

View File

@ -105,16 +105,14 @@ namespace SHADE
* TODO: Test if the scene graph transforms abides by setting world position. Collisions will ignore the scene graph hierarchy. * TODO: Test if the scene graph transforms abides by setting world position. Collisions will ignore the scene graph hierarchy.
*/ */
} }
}
// Collision & Trigger messages
if (scriptingSystem != nullptr)
scriptingSystem->ExecuteCollisionFunctions();
// Since this function never runs when editor in not in play, execute the function anyway // Since this function never runs when editor in not in play, execute the function anyway
physicsSystem->collisionListener.CleanContainers(); physicsSystem->collisionListener.CleanContainers();
} }
// Collision & Trigger messages
if (scriptingSystem != nullptr)
scriptingSystem->ExecuteCollisionFunctions();
}
} // namespace SHADE } // namespace SHADE

View File

@ -239,6 +239,7 @@ namespace SHADE
// Unlink with managers // Unlink with managers
objectManager.SetPhysicsWorld(nullptr); objectManager.SetPhysicsWorld(nullptr);
collisionListener.ClearContainers();
return onSceneExitEvent.get()->handle; return onSceneExitEvent.get()->handle;
} }

View File

@ -387,6 +387,7 @@ namespace SHADE
{ {
auto eventData = reinterpret_cast<const SHEventSpec<SHEditorStateChangeEvent>*>(eventPtr.get()); auto eventData = reinterpret_cast<const SHEventSpec<SHEditorStateChangeEvent>*>(eventPtr.get());
csScriptRemoveAllForAllNow(true); csScriptRemoveAllForAllNow(true);
csEngineReloadScripts();
return eventData->handle; return eventData->handle;
} }
@ -569,7 +570,7 @@ namespace SHADE
SHEventManager::SubscribeTo(SH_ENTITY_DESTROYED_EVENT, std::dynamic_pointer_cast<SHEventReceiver>(destroyedEventReceiver)); SHEventManager::SubscribeTo(SH_ENTITY_DESTROYED_EVENT, std::dynamic_pointer_cast<SHEventReceiver>(destroyedEventReceiver));
/* Editor */ /* Editor */
// Register for editor state change event // Register for editor state change events
std::shared_ptr<SHEventReceiverSpec<SHScriptEngine>> destroyedSceneEventReceiver std::shared_ptr<SHEventReceiverSpec<SHScriptEngine>> destroyedSceneEventReceiver
{ {
std::make_shared<SHEventReceiverSpec<SHScriptEngine>>(this, &SHScriptEngine::onSceneDestroyed) std::make_shared<SHEventReceiverSpec<SHScriptEngine>>(this, &SHScriptEngine::onSceneDestroyed)

View File

@ -233,6 +233,10 @@ namespace SHADE
/// </summary> /// </summary>
/// <param name="path"></param> /// <param name="path"></param>
void OpenFile(const std::filesystem::path& path); void OpenFile(const std::filesystem::path& path);
/// <summary>
/// Resets all static data in the loaded assemblies to their default values.
/// </summary>
static void ResetStaticDataInLoadedAssembly();
private: private:
/*-----------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------*/

View File

@ -70,6 +70,7 @@ namespace SHADE
//Compile component IDs //Compile component IDs
const auto componentIDList = SHSerialization::GetComponentIDList(node[ComponentsNode]); const auto componentIDList = SHSerialization::GetComponentIDList(node[ComponentsNode]);
eid = SHEntityManager::CreateEntity(componentIDList, eid, name, parentEID); eid = SHEntityManager::CreateEntity(componentIDList, eid, name, parentEID);
createdEntities[oldEID] = eid; createdEntities[oldEID] = eid;
//createdEntities.push_back(eid); //createdEntities.push_back(eid);
if (node[NumberOfChildrenNode]) if (node[NumberOfChildrenNode])
@ -90,6 +91,12 @@ namespace SHADE
if (node[ScriptsNode]) if (node[ScriptsNode])
SHSystemManager::GetSystem<SHScriptEngine>()->DeserialiseScripts(eid, node[ScriptsNode]); SHSystemManager::GetSystem<SHScriptEngine>()->DeserialiseScripts(eid, node[ScriptsNode]);
auto& sceneGraph = SHSceneManager::GetCurrentSceneGraph();
if (node[IsActiveNode])
{
sceneGraph.SetActive(eid, node[IsActiveNode].as<bool>());
}
return eid; return eid;
} }

View File

@ -6,8 +6,7 @@
namespace SHADE namespace SHADE
{ {
SHButtonComponent::SHButtonComponent() SHButtonComponent::SHButtonComponent()
:size(1.0f), isHovered(false), isClicked(false), : defaultTexture(0), hoveredTexture(0), clickedTexture(0), currentTexture(0)
defaultTexture(0), hoveredTexture(0), clickedTexture(0), currentTexture(0)
{ {
} }
@ -41,6 +40,9 @@ namespace SHADE
clickedTexture = texture; clickedTexture = texture;
} }
} }

View File

@ -17,8 +17,6 @@ namespace SHADE
SHButtonComponent(); SHButtonComponent();
virtual ~SHButtonComponent() = default; virtual ~SHButtonComponent() = default;
SHVec2 size;
AssetID GetClickedTexture() const noexcept; AssetID GetClickedTexture() const noexcept;
AssetID GetDefaultTexture() const noexcept; AssetID GetDefaultTexture() const noexcept;
AssetID GetHoveredTexture() const noexcept; AssetID GetHoveredTexture() const noexcept;
@ -32,11 +30,7 @@ namespace SHADE
friend class SHUISystem; friend class SHUISystem;
private: private:
//Set to true when mouse is hovering over the button.
bool isHovered;
//This is set to true when the mouse clicks down, and set back to false when mouse releases.
//The event for the button click will be broadcasted when mouse release.
bool isClicked;
AssetID defaultTexture; AssetID defaultTexture;
AssetID hoveredTexture; AssetID hoveredTexture;
AssetID clickedTexture; AssetID clickedTexture;

View File

@ -6,7 +6,7 @@ namespace SHADE
{ {
SHCanvasComponent::SHCanvasComponent() SHCanvasComponent::SHCanvasComponent()
:width(1),height(1), dirtyMatrix(false), canvasMatrix() :width(1), height(1), dirtyMatrix(false), canvasMatrix(), scaleByCanvasWidth(false)
{ {
} }
@ -28,6 +28,8 @@ namespace SHADE
} }
SHCanvasComponent::CanvasSizeType SHCanvasComponent::GetCanvasWidth() const noexcept SHCanvasComponent::CanvasSizeType SHCanvasComponent::GetCanvasWidth() const noexcept
{ {
return width; return width;
@ -43,6 +45,8 @@ namespace SHADE
return canvasMatrix; return canvasMatrix;
} }
} }
@ -54,6 +58,7 @@ RTTR_REGISTRATION
registration::class_<SHCanvasComponent>("Canvas Component") registration::class_<SHCanvasComponent>("Canvas Component")
.property("Canvas Width", &SHCanvasComponent::GetCanvasWidth, &SHCanvasComponent::SetCanvasWidth) .property("Canvas Width", &SHCanvasComponent::GetCanvasWidth, &SHCanvasComponent::SetCanvasWidth)
.property("Canvas Height", &SHCanvasComponent::GetCanvasHeight, &SHCanvasComponent::SetCanvasHeight) .property("Canvas Height", &SHCanvasComponent::GetCanvasHeight, &SHCanvasComponent::SetCanvasHeight)
.property("Scale by canvas width", &SHCanvasComponent::scaleByCanvasWidth)
; ;

View File

@ -21,15 +21,18 @@ namespace SHADE
SHCanvasComponent(); SHCanvasComponent();
~SHCanvasComponent() = default; ~SHCanvasComponent() = default;
bool scaleByCanvasWidth;
void SetCanvasSize(CanvasSizeType width, CanvasSizeType height) noexcept; void SetCanvasSize(CanvasSizeType width, CanvasSizeType height) noexcept;
void SetCanvasWidth(CanvasSizeType width) noexcept; void SetCanvasWidth(CanvasSizeType width) noexcept;
void SetCanvasHeight(CanvasSizeType height) noexcept; void SetCanvasHeight(CanvasSizeType height) noexcept;
CanvasSizeType GetCanvasWidth() const noexcept; CanvasSizeType GetCanvasWidth() const noexcept;
CanvasSizeType GetCanvasHeight() const noexcept; CanvasSizeType GetCanvasHeight() const noexcept;
SHMatrix const& GetMatrix() const noexcept; SHMatrix const& GetMatrix() const noexcept;
private: private:
CanvasSizeType width; CanvasSizeType width;
CanvasSizeType height; CanvasSizeType height;

View File

@ -5,8 +5,7 @@
namespace SHADE namespace SHADE
{ {
SHToggleButtonComponent::SHToggleButtonComponent() SHToggleButtonComponent::SHToggleButtonComponent()
:size(1.0f), isHovered(false), isClicked(false), value(false), :value(false), defaultTexture(0), toggledTexture(0), currentTexture(0)
defaultTexture(0), toggledTexture(0), currentTexture(0)
{ {
} }

View File

@ -17,8 +17,6 @@ namespace SHADE
SHToggleButtonComponent(); SHToggleButtonComponent();
virtual ~SHToggleButtonComponent() = default; virtual ~SHToggleButtonComponent() = default;
SHVec2 size;
AssetID GetToggledTexture() const noexcept; AssetID GetToggledTexture() const noexcept;
AssetID GetDefaultTexture() const noexcept; AssetID GetDefaultTexture() const noexcept;
bool GetValue() const noexcept; bool GetValue() const noexcept;
@ -33,11 +31,7 @@ namespace SHADE
friend class SHUISystem; friend class SHUISystem;
private: private:
//Set to true when mouse is hovering over the button.
bool isHovered;
//This is set to true when the mouse clicks down, and set back to false when mouse releases.
//The event for the button click will be broadcasted when mouse release.
bool isClicked;
bool value; bool value;
AssetID defaultTexture; AssetID defaultTexture;
AssetID toggledTexture; AssetID toggledTexture;

View File

@ -7,6 +7,7 @@ namespace SHADE
{ {
SHUIComponent::SHUIComponent() SHUIComponent::SHUIComponent()
:size(1.0f), isHovered(false), isClicked(false)
{ {
} }
@ -27,6 +28,20 @@ namespace SHADE
(void)id; (void)id;
} }
bool SHUIComponent::GetIsHovered() const noexcept
{
return isHovered;
}
bool SHUIComponent::GetIsClicked() const noexcept
{
return isClicked;
}
void SHUIComponent::SetEmptyHoveredClick(bool value) noexcept
{
(void)value;
}
} }
@ -37,6 +52,8 @@ RTTR_REGISTRATION
registration::class_<SHUIComponent>("UI Component") registration::class_<SHUIComponent>("UI Component")
.property("Canvas ID", &SHUIComponent::GetCanvasID, &SHUIComponent::SetCanvasID) .property("Canvas ID", &SHUIComponent::GetCanvasID, &SHUIComponent::SetCanvasID)
.property("Hovered", &SHUIComponent::GetIsHovered, &SHUIComponent::SetEmptyHoveredClick)
.property("Clicked", &SHUIComponent::GetIsClicked, &SHUIComponent::SetEmptyHoveredClick)
; ;

View File

@ -5,6 +5,7 @@
#include "SH_API.h" #include "SH_API.h"
#include "ECS_Base/Components/SHComponent.h" #include "ECS_Base/Components/SHComponent.h"
#include "Math/SHMatrix.h" #include "Math/SHMatrix.h"
#include "Math/Vector/SHVec2.h"
namespace SHADE namespace SHADE
@ -17,14 +18,29 @@ namespace SHADE
SHUIComponent(); SHUIComponent();
~SHUIComponent() = default; ~SHUIComponent() = default;
SHVec2 size;
SHMatrix const& GetMatrix() const noexcept; SHMatrix const& GetMatrix() const noexcept;
EntityID GetCanvasID() const noexcept; EntityID GetCanvasID() const noexcept;
void SetCanvasID(EntityID id) noexcept; void SetCanvasID(EntityID id) noexcept;
bool GetIsHovered() const noexcept;
bool GetIsClicked() const noexcept;
void SetEmptyHoveredClick(bool value)noexcept;
private: private:
SHMatrix localToCanvasMatrix; SHMatrix localToCanvasMatrix;
EntityID canvasID; EntityID canvasID;
//Set to true when mouse is hovering over the button. Only set if there is a Button/Slider/ToggleButton comp.
bool isHovered;
//This is set to true when the mouse clicks down, and set back to false when mouse releases. Only set if there is a Button/Slider/ToggleButton comp.
bool isClicked;
RTTR_ENABLE() RTTR_ENABLE()
}; };

View File

@ -131,8 +131,17 @@ namespace SHADE
auto cameraSystem = SHSystemManager::GetSystem<SHCameraSystem>(); auto cameraSystem = SHSystemManager::GetSystem<SHCameraSystem>();
SHVec2 camSize = cameraSystem->GetCameraWidthHeight(0); SHVec2 camSize = cameraSystem->GetCameraWidthHeight(0);
comp.canvasMatrix = SHMatrix::Identity; comp.canvasMatrix = SHMatrix::Identity;
comp.canvasMatrix(0, 0) = camSize.x * 0.5f / (comp.GetCanvasWidth() * 0.5f); float scale = camSize.y / comp.GetCanvasHeight();
comp.canvasMatrix(1, 1) = camSize.y * 0.5f / (comp.GetCanvasHeight() * 0.5f); if (comp.scaleByCanvasWidth)
{
scale = camSize.x / comp.GetCanvasWidth();
}
comp.canvasMatrix(0, 0) = scale;
comp.canvasMatrix(1, 1) = scale;
//comp.canvasMatrix(0, 0) = camSize.x * 0.5f / (comp.GetCanvasWidth() * 0.5f);
//comp.canvasMatrix(1, 1) = camSize.y * 0.5f / (comp.GetCanvasHeight() * 0.5f);
} }
void SHUISystem::UpdateCanvasMatrixRoutine::Execute(double dt) noexcept void SHUISystem::UpdateCanvasMatrixRoutine::Execute(double dt) noexcept
@ -146,25 +155,15 @@ namespace SHADE
} }
} }
bool SHUISystem::CheckButtonHoveredOrClicked(SHUIComponent& comp) noexcept
void SHUISystem::UpdateButtonComponent(SHButtonComponent& comp) noexcept
{ {
if (!SHComponentManager::HasComponent<SHUIComponent>(comp.GetEID())) SHVec4 topExtent4 = SHMatrix::Translate(-comp.size.x * 0.5f, comp.size.y * 0.5f, 0.0f) * comp.GetMatrix() * SHVec4(0.0f, 0.0f, 0.0f, 1.0f);
{ SHVec4 btmExtent4 = SHMatrix::Translate(comp.size.x * 0.5f, -comp.size.y * 0.5f, 0.0f) * comp.GetMatrix() * SHVec4(0.0f, 0.0f, 0.0f, 1.0f);
return;
}
auto cameraSystem = SHSystemManager::GetSystem<SHCameraSystem>();
auto uiComp = SHComponentManager::GetComponent<SHUIComponent>(comp.GetEID());
//auto canvasComp = SHComponentManager::GetComponent_s<SHCanvasComponent>(uiComp->canvasID);
SHVec4 topExtent4 = SHMatrix::Translate(-comp.size.x * 0.5f, comp.size.y * 0.5f, 0.0f) * uiComp->GetMatrix() * SHVec4(0.0f, 0.0f, 0.0f, 1.0f);
SHVec4 btmExtent4 = SHMatrix::Translate(comp.size.x * 0.5f, -comp.size.y * 0.5f, 0.0f) * uiComp->GetMatrix() * SHVec4(0.0f,0.0f, 0.0f,1.0f);
SHVec2 topExtent{ topExtent4.x,topExtent4.y }; SHVec2 topExtent{ topExtent4.x,topExtent4.y };
SHVec2 btmExtent{ btmExtent4.x,btmExtent4.y }; SHVec2 btmExtent{ btmExtent4.x,btmExtent4.y };
auto cameraSystem = SHSystemManager::GetSystem<SHCameraSystem>();
SHVec2 mousePos; SHVec2 mousePos;
SHVec2 windowSize; SHVec2 windowSize;
#ifdef SHEDITOR #ifdef SHEDITOR
@ -188,11 +187,11 @@ namespace SHADE
mousePos /= windowSize; mousePos /= windowSize;
#endif #endif
SHVec2 camSize{ cameraSystem->GetCameraWidthHeight(0)}; SHVec2 camSize{ cameraSystem->GetCameraWidthHeight(0) };
//SHLOG_INFO("TopExtent: {}, {}", topExtent.x, topExtent.y) //SHLOG_INFO("TopExtent: {}, {}", topExtent.x, topExtent.y)
topExtent = CanvasToScreenPoint(topExtent,true); topExtent = CanvasToScreenPoint(topExtent, true);
btmExtent = CanvasToScreenPoint(btmExtent,true); btmExtent = CanvasToScreenPoint(btmExtent, true);
//SHLOG_INFO("TopExtent: {}, {} Btm Extent: {}, {}", topExtent.x, topExtent.y, btmExtent.x, btmExtent.y) //SHLOG_INFO("TopExtent: {}, {} Btm Extent: {}, {}", topExtent.x, topExtent.y, btmExtent.x, btmExtent.y)
@ -200,26 +199,48 @@ namespace SHADE
if (mousePos.x >= topExtent.x && mousePos.x <= btmExtent.x if (mousePos.x >= topExtent.x && mousePos.x <= btmExtent.x
&& mousePos.y >= topExtent.y && mousePos.y <= btmExtent.y) && mousePos.y >= topExtent.y && mousePos.y <= btmExtent.y)
{ {
if (comp.isHovered == false)
{
SHButtonClickEvent clickEvent;
clickEvent.EID = comp.GetEID();
SHEventManager::BroadcastEvent(clickEvent, SH_BUTTON_HOVER_ENTER_EVENT);
}
comp.isHovered = true; comp.isHovered = true;
#ifdef SHEDITOR
#ifdef SHEDITOR
//if (SHSystemManager::GetSystem<SHEditor>()->editorState == SHEditor::State::PLAY) //if (SHSystemManager::GetSystem<SHEditor>()->editorState == SHEditor::State::PLAY)
{ {
if (SHInputManager::GetKeyDown(SHInputManager::SH_KEYCODE::LMB)) if (SHInputManager::GetKeyDown(SHInputManager::SH_KEYCODE::LMB))
{ {
comp.isClicked = true; comp.isClicked = true;
SHButtonClickEvent clickEvent;
clickEvent.EID = comp.GetEID();
SHEventManager::BroadcastEvent(clickEvent, SH_BUTTON_CLICK_EVENT);
} }
} }
#else #else
if (SHInputManager::GetKeyDown(SHInputManager::SH_KEYCODE::LMB)) if (SHInputManager::GetKeyDown(SHInputManager::SH_KEYCODE::LMB))
{ {
comp.isClicked = true; comp.isClicked = true;
SHButtonClickEvent clickEvent;
clickEvent.EID = comp.GetEID();
SHEventManager::BroadcastEvent(clickEvent, SH_BUTTON_CLICK_EVENT);
} }
#endif #endif
//SHLOG_INFO("HOVERED") //SHLOG_INFO("HOVERED")
} }
else else
{ {
if (comp.isHovered == true)
{
SHButtonClickEvent clickEvent;
clickEvent.EID = comp.GetEID();
SHEventManager::BroadcastEvent(clickEvent, SH_BUTTON_HOVER_EXIT_EVENT);
}
comp.isHovered = false; comp.isHovered = false;
//SHLOG_INFO("NOT HOVERED") //SHLOG_INFO("NOT HOVERED")
} }
@ -228,9 +249,31 @@ namespace SHADE
comp.isClicked = false; comp.isClicked = false;
SHButtonClickEvent clickEvent; SHButtonClickEvent clickEvent;
clickEvent.EID = comp.GetEID(); clickEvent.EID = comp.GetEID();
SHEventManager::BroadcastEvent(clickEvent, SH_BUTTON_CLICK_EVENT); SHEventManager::BroadcastEvent(clickEvent, SH_BUTTON_RELEASE_EVENT);
return true;
} }
return false;
}
void SHUISystem::UpdateButtonComponent(SHButtonComponent& comp) noexcept
{
if (!SHComponentManager::HasComponent<SHUIComponent>(comp.GetEID()))
{
return;
}
auto cameraSystem = SHSystemManager::GetSystem<SHCameraSystem>();
auto uiComp = SHComponentManager::GetComponent<SHUIComponent>(comp.GetEID());
//auto canvasComp = SHComponentManager::GetComponent_s<SHCanvasComponent>(uiComp->canvasID);
CheckButtonHoveredOrClicked(*uiComp);
if (SHComponentManager::HasComponent<SHRenderable>(comp.GetEID())) if (SHComponentManager::HasComponent<SHRenderable>(comp.GetEID()))
{ {
auto renderable = SHComponentManager::GetComponent_s<SHRenderable>(comp.GetEID()); auto renderable = SHComponentManager::GetComponent_s<SHRenderable>(comp.GetEID());
@ -238,7 +281,7 @@ namespace SHADE
AssetID textureID = 0; AssetID textureID = 0;
if (!comp.isHovered && !comp.isClicked) if (!uiComp->isHovered && !uiComp->isClicked)
{ {
if (comp.GetDefaultTexture() != 0 && SHAssetManager::GetType(comp.GetDefaultTexture()) == AssetType::TEXTURE) if (comp.GetDefaultTexture() != 0 && SHAssetManager::GetType(comp.GetDefaultTexture()) == AssetType::TEXTURE)
{ {
@ -247,7 +290,7 @@ namespace SHADE
//SHLOG_INFO("SETTING DEFAULT TEXTURE") //SHLOG_INFO("SETTING DEFAULT TEXTURE")
} }
} }
else if (comp.isClicked) else if (uiComp->isClicked)
{ {
if (comp.GetClickedTexture() != 0 && SHAssetManager::GetType(comp.GetClickedTexture()) == AssetType::TEXTURE) if (comp.GetClickedTexture() != 0 && SHAssetManager::GetType(comp.GetClickedTexture()) == AssetType::TEXTURE)
{ {
@ -288,80 +331,10 @@ namespace SHADE
auto uiComp = SHComponentManager::GetComponent<SHUIComponent>(comp.GetEID()); auto uiComp = SHComponentManager::GetComponent<SHUIComponent>(comp.GetEID());
//auto canvasComp = SHComponentManager::GetComponent_s<SHCanvasComponent>(uiComp->canvasID); //auto canvasComp = SHComponentManager::GetComponent_s<SHCanvasComponent>(uiComp->canvasID);
SHVec4 topExtent4 = SHMatrix::Translate(-comp.size.x * 0.5f, comp.size.y * 0.5f, 0.0f) * uiComp->GetMatrix() * SHVec4(0.0f, 0.0f, 0.0f, 1.0f);
SHVec4 btmExtent4 = SHMatrix::Translate(comp.size.x * 0.5f, -comp.size.y * 0.5f, 0.0f) * uiComp->GetMatrix() * SHVec4(0.0f, 0.0f, 0.0f, 1.0f);
SHVec2 topExtent{ topExtent4.x,topExtent4.y }; if (CheckButtonHoveredOrClicked(*uiComp))
SHVec2 btmExtent{ btmExtent4.x,btmExtent4.y };
SHVec2 mousePos;
SHVec2 windowSize;
#ifdef SHEDITOR
windowSize = SHEditorWindowManager::GetEditorWindow<SHEditorViewport>()->beginContentRegionAvailable;
mousePos = SHEditorWindowManager::GetEditorWindow<SHEditorViewport>()->viewportMousePos;
//mousePos.y = windowSize.y - mousePos.y;
//SHLOG_INFO("mouse pos: {}, {}", mousePos.x, mousePos.y)
mousePos /= windowSize;
//SHLOG_INFO("mouse pos normalized: {}, {}", mousePos.x, mousePos.y)
#else
int x, y;
SHInputManager::GetMouseScreenPosition(&x, &y);
mousePos.x = x;
mousePos.y = y;
auto ws = SHSystemManager::GetSystem<SHGraphicsSystem>()->GetWindow()->GetWindowSize();
windowSize = { static_cast<float>(ws.first), static_cast<float>(ws.second) };
mousePos /= windowSize;
#endif
SHVec2 camSize{ cameraSystem->GetCameraWidthHeight(0) };
//SHLOG_INFO("TopExtent: {}, {}", topExtent.x, topExtent.y)
topExtent = CanvasToScreenPoint(topExtent, true);
btmExtent = CanvasToScreenPoint(btmExtent, true);
//SHLOG_INFO("TopExtent: {}, {} Btm Extent: {}, {}", topExtent.x, topExtent.y, btmExtent.x, btmExtent.y)
//comp.isClicked = false;
if (mousePos.x >= topExtent.x && mousePos.x <= btmExtent.x
&& mousePos.y >= topExtent.y && mousePos.y <= btmExtent.y)
{
comp.isHovered = true;
#ifdef SHEDITOR
//if (SHSystemManager::GetSystem<SHEditor>()->editorState == SHEditor::State::PLAY)
{
if (SHInputManager::GetKeyDown(SHInputManager::SH_KEYCODE::LMB))
{
comp.isClicked = true;
}
}
#else
if (SHInputManager::GetKeyDown(SHInputManager::SH_KEYCODE::LMB))
{
comp.isClicked = true;
}
#endif
//SHLOG_INFO("HOVERED")
}
else
{
comp.isHovered = false;
//SHLOG_INFO("NOT HOVERED")
}
if (comp.isClicked && SHInputManager::GetKeyUp(SHInputManager::SH_KEYCODE::LMB))
{
comp.isClicked = false;
comp.value = !comp.value; comp.value = !comp.value;
SHButtonClickEvent clickEvent;
clickEvent.EID = comp.GetEID();
SHEventManager::BroadcastEvent(clickEvent, SH_BUTTON_CLICK_EVENT);
}
if (SHComponentManager::HasComponent<SHRenderable>(comp.GetEID())) if (SHComponentManager::HasComponent<SHRenderable>(comp.GetEID()))
{ {

View File

@ -73,6 +73,11 @@ namespace SHADE
void UpdateToggleButtonComponent(SHToggleButtonComponent& comp) noexcept; void UpdateToggleButtonComponent(SHToggleButtonComponent& comp) noexcept;
void UpdateCanvasComponent(SHCanvasComponent& comp) noexcept; void UpdateCanvasComponent(SHCanvasComponent& comp) noexcept;
//returns true on button release.
bool CheckButtonHoveredOrClicked(SHUIComponent& comp) noexcept;
SHVec2 CanvasToScreenPoint(SHVec2& const canvasPoint, bool normalized) noexcept; SHVec2 CanvasToScreenPoint(SHVec2& const canvasPoint, bool normalized) noexcept;

View File

@ -81,7 +81,8 @@ namespace SHADE
// Add the script // Add the script
Script^ script; Script^ script;
ScriptStore::AddScriptViaNameWithRef(entity, type->Name, script); ScriptStore::AddScriptViaNameWithRef(entity, type->Name, script);
registerUndoScriptAddAction(entity, script); // TODO: Re-enable when undo-redo is fixed
// registerUndoScriptAddAction(entity, script);
break; break;
} }
} }
@ -375,7 +376,8 @@ namespace SHADE
{ {
// Mark script for removal // Mark script for removal
ScriptStore::RemoveScript(entity, script); ScriptStore::RemoveScript(entity, script);
registerUndoScriptRemoveAction(entity, script, scriptIndex); // TODO: Re-enable when undo-redo is fixed
// registerUndoScriptRemoveAction(entity, script, scriptIndex);
} }
SHEditorUI::EndPopup(); SHEditorUI::EndPopup();
} }

View File

@ -22,6 +22,7 @@ of DigiPen Institute of Technology is prohibited.
#include "Utility/Debug.hxx" #include "Utility/Debug.hxx"
#include "Utility/Convert.hxx" #include "Utility/Convert.hxx"
#include "Scripts/ScriptStore.hxx" #include "Scripts/ScriptStore.hxx"
#include "Serialisation/SerialisationUtilities.hxx"
namespace SHADE namespace SHADE
{ {
@ -267,7 +268,9 @@ namespace SHADE
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
ScriptAddCommand::ScriptAddCommand(EntityID id, Script^ script) ScriptAddCommand::ScriptAddCommand(EntityID id, Script^ script)
: entity { id } : entity { id }
, addedScript { script } , typeName { script->GetType()->FullName }
, serialisedScript { SerialisationUtilities::Serialise(script) }
, insertedIndex { ScriptStore::GetScriptIndex(script) }
{} {}
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
@ -275,12 +278,20 @@ namespace SHADE
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
bool ScriptAddCommand::Execute() bool ScriptAddCommand::Execute()
{ {
return ScriptStore::AddScript(entity, addedScript) != nullptr; Script^ script = nullptr;
if (ScriptStore::AddScriptViaNameWithRef(entity, typeName, script))
{
SerialisationUtilities::Deserialise(script, serialisedScript);
insertedIndex = ScriptStore::GetScriptIndex(script);
return true;
}
return false;
} }
bool ScriptAddCommand::Unexceute() bool ScriptAddCommand::Unexceute()
{ {
return ScriptStore::RemoveScript(entity, addedScript); return ScriptStore::RemoveScript(entity, insertedIndex);
} }
bool ScriptAddCommand::Merge(ICommand^) bool ScriptAddCommand::Merge(ICommand^)
@ -293,8 +304,9 @@ namespace SHADE
/* ScriptRemoveCommand - Constructor */ /* ScriptRemoveCommand - Constructor */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
ScriptRemoveCommand::ScriptRemoveCommand(EntityID id, Script^ script, int index) ScriptRemoveCommand::ScriptRemoveCommand(EntityID id, Script^ script, int index)
: entity { id } : entity{ id }
, removedScript { script } , typeName{ script->GetType()->FullName }
, serialisedScript{ SerialisationUtilities::Serialise(script) }
, originalIndex { index } , originalIndex { index }
{} {}
@ -303,12 +315,19 @@ namespace SHADE
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
bool ScriptRemoveCommand::Execute() bool ScriptRemoveCommand::Execute()
{ {
return ScriptStore::RemoveScript(entity, removedScript); return ScriptStore::RemoveScript(entity, originalIndex);
} }
bool ScriptRemoveCommand::Unexceute() bool ScriptRemoveCommand::Unexceute()
{ {
return ScriptStore::AddScript(entity, removedScript, originalIndex) != nullptr; Script^ script = nullptr;
if (ScriptStore::AddScriptViaNameWithRef(entity, typeName, script, originalIndex))
{
SerialisationUtilities::Deserialise(script, serialisedScript);
return true;
}
return false;
} }
bool ScriptRemoveCommand::Merge(ICommand^) bool ScriptRemoveCommand::Merge(ICommand^)

View File

@ -114,7 +114,9 @@ namespace SHADE
private: private:
EntityID entity; EntityID entity;
Script^ addedScript; System::String^ typeName;
System::String^ serialisedScript;
int insertedIndex;
}; };
private ref class ScriptRemoveCommand sealed : public ICommand private ref class ScriptRemoveCommand sealed : public ICommand
@ -128,7 +130,8 @@ namespace SHADE
private: private:
EntityID entity; EntityID entity;
Script^ removedScript; System::String^ typeName;
System::String^ serialisedScript;
int originalIndex; int originalIndex;
}; };

View File

@ -0,0 +1,85 @@
/****************************************************************************************
* \file CollisionTags.hxx
* \author Diren D Bharwani, diren.dbharwani, 390002520
* \brief Interface for the managed Collision Tag Matrix & Collision Tag classes.
*
* \copyright Copyright (C) 2022 DigiPen Institute of Technology. Reproduction or
* disclosure of this file or its contents without the prior written consent
* of DigiPen Institute of Technology is prohibited.
****************************************************************************************/
#pragma once
// Project Includes
#include "Math/Ray.hxx"
namespace SHADE
{
/*-----------------------------------------------------------------------------------*/
/* Type Definitions */
/*-----------------------------------------------------------------------------------*/
/// <summary>
/// Represents a collision tag.
/// </summary>
public ref struct CollisionTag sealed
{
public:
/*-----------------------------------------------------------------------------*/
/* Properties */
/*-----------------------------------------------------------------------------*/
/// <summary>
/// Name of the object that this Entity represents.
/// </summary>
property System::String^ Name
{
System::String^ get();
void set(System::String^ value);
}
property unsigned short Mask
{
unsigned short get();
}
/*-----------------------------------------------------------------------------*/
/* Property Functions */
/*-----------------------------------------------------------------------------*/
/// <summary>
/// Checks the state of a layer on the mask.
/// </summary>
/// <param name="layer">The layer to check.</param>
/// <returns>True if the state is active.</returns>
bool GetLayerState (int layer);
/// <summary>
/// Sets the state of a layer on the mask.
/// </summary>
/// <param name="layer">The layer to set.</param>
/// <param name="state">The state of the layer to set.</param>
void SetLayerState (int layer, bool state);
};
public ref class CollisionTagMatrix abstract sealed
{
public:
/*---------------------------------------------------------------------------------*/
/* Member Functions */
/*---------------------------------------------------------------------------------*/
/// <summary>
/// Get the name of a Collision Tag
/// </summary>
/// <param name="tagIndex">
/// The index of the tag in the matrix.
/// </param>
/// <returns>The name of the collision tag.</returns>
System::String^ GetTagName(int tagIndex);
int GetTagIndex(System::String^ tagName);
};
}

View File

@ -100,6 +100,11 @@ namespace SHADE
} }
bool ScriptStore::AddScriptViaNameWithRef(Entity entity, System::String^ scriptName, Script^% createdScript) bool ScriptStore::AddScriptViaNameWithRef(Entity entity, System::String^ scriptName, Script^% createdScript)
{
return AddScriptViaNameWithRef(entity, scriptName, createdScript, System::Int32::MaxValue);
}
bool ScriptStore::AddScriptViaNameWithRef(Entity entity, System::String^ scriptName, [System::Runtime::InteropServices::Out] Script^% createdScript, int index)
{ {
// Check if we are set up to get scripts // Check if we are set up to get scripts
if (addScriptMethod == nullptr) if (addScriptMethod == nullptr)
@ -120,17 +125,18 @@ namespace SHADE
return false; return false;
} }
// Otherwise, add the script // Add the script
System::Reflection::MethodInfo^ method = addScriptMethod->MakeGenericMethod(scriptType); System::Reflection::MethodInfo^ method = addScriptMethod->MakeGenericMethod(scriptType);
try try
{ {
array<Object^>^ params = gcnew array<Object^>{entity}; // Create the script and add it in
createdScript = safe_cast<Script^>(method->Invoke(nullptr, params)); createdScript = safe_cast<Script^>(System::Activator::CreateInstance(scriptType));
AddScript(entity, createdScript, index);
} }
catch (System::Exception^ e) catch (System::Exception^ e)
{ {
std::ostringstream oss; std::ostringstream oss;
oss << "[ScriptStore] Failed to add Script named \"" << Convert::ToNative(scriptName) oss << "[ScriptStore] Failed to add Script named \"" << Convert::ToNative(scriptType->Name)
<< "\" to Entity #" << entity << "! (" << Convert::ToNative(e->GetType()->Name) << ")"; << "\" to Entity #" << entity << "! (" << Convert::ToNative(e->GetType()->Name) << ")";
oss << Convert::ToNative(e->ToString()); oss << Convert::ToNative(e->ToString());
Debug::LogError(oss.str()); Debug::LogError(oss.str());
@ -321,6 +327,19 @@ namespace SHADE
} }
return nullptr; return nullptr;
} }
int ScriptStore::GetScriptIndex(Script^ script)
{
// Check if entity exists in the script storage
if (!scripts.ContainsKey(script->Owner.EntityId))
{
Debug::LogError("[ScriptStore] Attempted to query a Script that does not belong to the ScriptStore.");
return -1;
}
return scripts[script->Owner.EntityId]->IndexOf(script);
}
generic<typename T> generic<typename T>
void ScriptStore::RemoveScript(Entity entity) void ScriptStore::RemoveScript(Entity entity)
{ {
@ -376,6 +395,35 @@ namespace SHADE
removeScript(script); removeScript(script);
return true; return true;
} }
bool ScriptStore::RemoveScript(Entity entity, int index)
{
// Check if entity exists
if (!EntityUtils::IsValid(entity))
{
Debug::LogError("[ScriptStore] Attempted to remove a Script from an invalid Entity!");
return false;
}
// Check if entity exists in the script storage
if (!scripts.ContainsKey(entity))
{
Debug::LogError("[ScriptStore] Attempted to remove a Script that does not belong to the specified Entity!");
return false;
}
// Check if the script index is out of bounds
if (index < 0 || index >= scripts[entity]->Count)
{
Debug::LogError("[ScriptStore] Attempted to remove a Script from an out of range index!");
return false;
}
// Script found, queue it for deletion
removeScript((*scripts[entity])[index]);
return true;
}
void ScriptStore::RemoveAllScripts(Entity entity) void ScriptStore::RemoveAllScripts(Entity entity)
{ {
SAFE_NATIVE_CALL_BEGIN SAFE_NATIVE_CALL_BEGIN

View File

@ -82,9 +82,9 @@ namespace SHADE
/// <summary> /// <summary>
/// Adds a Script to a specified Entity. /// Adds a Script to a specified Entity.
/// <br/> /// <br/>
/// This function is meant for consumption from native code or for serialisation /// This function is meant for deserialisation purposes. If you are writing in
/// purposes. If you are writing in C# or C++/CLI and not doing serialisation, /// C# or C++/CLI and not doing serialisation, use AddScript&lt;T&gt;() instead
/// use AddScript&lt;T&gt;() instead as it is faster. /// as it is faster.
/// </summary> /// </summary>
/// <param name="entity">The entity to add a script to.</param> /// <param name="entity">The entity to add a script to.</param>
/// <param name="scriptName">The entity to add a script to.</param> /// <param name="scriptName">The entity to add a script to.</param>
@ -96,6 +96,7 @@ namespace SHADE
/// console. /// console.
/// </returns> /// </returns>
static bool AddScriptViaNameWithRef(Entity entity, System::String^ scriptName, [System::Runtime::InteropServices::Out] Script^% createdScript); static bool AddScriptViaNameWithRef(Entity entity, System::String^ scriptName, [System::Runtime::InteropServices::Out] Script^% createdScript);
static bool AddScriptViaNameWithRef(Entity entity, System::String^ scriptName, [System::Runtime::InteropServices::Out] Script^% createdScript, int index);
/// <summary> /// <summary>
/// Retrieves the first Script from the specified Entity that matches the /// Retrieves the first Script from the specified Entity that matches the
/// specified type. /// specified type.
@ -190,6 +191,12 @@ namespace SHADE
/// </returns> /// </returns>
static System::Collections::Generic::IEnumerable<Script^>^ GetAllScripts(Entity entity); static System::Collections::Generic::IEnumerable<Script^>^ GetAllScripts(Entity entity);
/// <summary> /// <summary>
/// Retrieves the index of a Script within the list of it's Entity's script list.
/// </summary>
/// <param name="script">Script to get the index of.</param>
/// <returns>Script index if valid. Otherwise -1.</returns>
static int GetScriptIndex(Script^ script);
/// <summary>
/// Removes all Scripts of the specified type from the specified Entity. /// Removes all Scripts of the specified type from the specified Entity.
/// </summary> /// </summary>
/// <typeparam name="T"> /// <typeparam name="T">
@ -210,6 +217,13 @@ namespace SHADE
/// <returns>True if successfully removed. False otherwise.</returns> /// <returns>True if successfully removed. False otherwise.</returns>
static bool RemoveScript(Entity entity, Script^ script); static bool RemoveScript(Entity entity, Script^ script);
/// <summary> /// <summary>
/// Removes a script at a specified index from the specified entity.
/// </summary>
/// <param name="entity">The entity to remove the script from.</param>
/// <param name="index">Index of the script to remove.</param>
/// <returns>True if successfully removed. False otherwise.</returns>
static bool RemoveScript(Entity entity, int index);
/// <summary>
/// Removes all Scripts attached to the specified Entity. Does not do anything /// Removes all Scripts attached to the specified Entity. Does not do anything
/// if the specified Entity is invalid or does not have any Scripts /// if the specified Entity is invalid or does not have any Scripts
/// attached. /// attached.

View File

@ -22,6 +22,7 @@ of DigiPen Institute of Technology is prohibited.
#include "Assets/MaterialAsset.hxx" #include "Assets/MaterialAsset.hxx"
#include "Assets/MeshAsset.hxx" #include "Assets/MeshAsset.hxx"
#include "Scripts/Script.hxx" #include "Scripts/Script.hxx"
#include "Scripts/ScriptStore.hxx"
/*-------------------------------------------------------------------------------------*/ /*-------------------------------------------------------------------------------------*/
/* File-Level Constants */ /* File-Level Constants */
@ -79,6 +80,19 @@ namespace SHADE
scriptListNode.push_back(scriptNode); scriptListNode.push_back(scriptNode);
} }
System::String^ SerialisationUtilities::Serialise(Script^ script)
{
YAML::Node node;
node.SetStyle(YAML::EmitterStyle::Block);
Serialise(script, node);
YAML::Emitter emitter;
emitter << YAML::BeginMap;
emitter << node;
emitter << YAML::EndMap;
return Convert::ToCLI(emitter.c_str());
}
void SerialisationUtilities::Deserialise(Object^ object, YAML::Node& yamlNode) void SerialisationUtilities::Deserialise(Object^ object, YAML::Node& yamlNode)
{ {
using namespace System::Reflection; using namespace System::Reflection;
@ -135,6 +149,12 @@ namespace SHADE
} }
} }
} }
void SerialisationUtilities::Deserialise(Script^ script, System::String^ yamlString)
{
Deserialise(script, YAML::Load(Convert::ToNative(yamlString)));
}
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/
/* Serialization Helper Functions */ /* Serialization Helper Functions */
/*---------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------*/

View File

@ -39,6 +39,7 @@ namespace SHADE
/// </summary> /// </summary>
/// <param name="object">The object to serialise.</param> /// <param name="object">The object to serialise.</param>
static void Serialise(System::Object^ object, YAML::Node& yamlNode); static void Serialise(System::Object^ object, YAML::Node& yamlNode);
static System::String^ Serialise(Script^ script);
/// <summary> /// <summary>
/// Deserialises a YAML node that contains a map of Scripts and copies the /// Deserialises a YAML node that contains a map of Scripts and copies the
/// deserialised data into the specified object if there are matching fields. /// deserialised data into the specified object if there are matching fields.
@ -48,6 +49,7 @@ namespace SHADE
/// </param> /// </param>
/// <param name="object">The object to copy deserialised data into.</param> /// <param name="object">The object to copy deserialised data into.</param>
static void Deserialise(System::Object^ object, YAML::Node& yamlNode); static void Deserialise(System::Object^ object, YAML::Node& yamlNode);
static void Deserialise(Script^ script, System::String^ yamlString);
private: private:
/*-----------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------*/