93 Commits

Author SHA1 Message Date
83512822b1 Support clipboard actions in Content Browser and Scene tree on Wayland
Some checks failed
Build Android / Game (Android, Release ARM64) (push) Has been cancelled
Build iOS / Game (iOS, Release ARM64) (push) Has been cancelled
Build Linux / Editor (Linux, Development x64) (push) Has been cancelled
Build Linux / Game (Linux, Release x64) (push) Has been cancelled
Build macOS / Editor (Mac, Development ARM64) (push) Has been cancelled
Build macOS / Game (Mac, Release ARM64) (push) Has been cancelled
Build Windows / Editor (Windows, Development x64) (push) Has been cancelled
Build Windows / Game (Windows, Release x64) (push) Has been cancelled
Cooker / Cook (Mac) (push) Has been cancelled
Tests / Tests (Linux) (push) Has been cancelled
Tests / Tests (Windows) (push) Has been cancelled
2025-06-23 17:50:02 +03:00
ccb78103ec Support clipboard actions in Content Browser and Scene tree on X11 2025-06-23 17:07:10 +03:00
6e79ffea34 Fix clipboard not working on X11 2025-06-23 17:07:10 +03:00
4f03d37a17 Merge remote-tracking branch 'origin/master' into sdl_platform 2025-06-23 12:03:41 +03:00
Wojtek Figat
6479a3d3c6 Fix log spam in task when waiting for task to end 2025-06-18 22:41:42 +02:00
Wojtek Figat
e41c48f9e5 Optimize NavMesh builder when updating a large number of tiles 2025-06-18 22:41:26 +02:00
Wojtek Figat
9cfcbfa9d2 Fix memory leak on recast objects when building NavMesh tile 2025-06-17 23:28:15 +02:00
Wojtek Figat
bcd2b1f0f2 Fix Array::RemoveAt to move element and avoid data copies 2025-06-17 23:27:26 +02:00
6fb8419b3c Disable window flashing on Wayland to fix focus issues 2025-06-17 14:23:20 +03:00
a4272d6ca9 Merge remote-tracking branch 'origin/master' into sdl_platform 2025-06-17 14:19:46 +03:00
Wojtek Figat
eb6010cba7 Fix BitArray again 2025-06-16 23:20:20 +02:00
Wojtek Figat
5a23060e05 Add GPUTexture.UploadData for changing texture contents via TextureData container 2025-06-16 22:35:50 +02:00
Wojtek Figat
b92c18cf25 Fix missing/incorrect toolchain exception to log only once 2025-06-16 19:10:35 +02:00
Wojtek Figat
6a82eb114d Fix BitArray bit indexing 2025-06-16 19:05:44 +02:00
Wojtek Figat
97b37b3ce4 Add PRAGMA_DISABLE_OPTIMIZATION/PRAGMA_ENABLE_OPTIMIZATION 2025-06-16 18:00:26 +02:00
4654117d5e Merge remote-tracking branch 'origin/master' into sdl_platform 2025-06-16 17:09:22 +03:00
Wojtek Figat
22911bbc45 Merge branch 'xxSeys1-VisjectCloseButtonFix' 2025-06-16 15:02:37 +02:00
Wojtek Figat
cae2720585 Merge branch 'VisjectCloseButtonFix' of https://github.com/xxSeys1/FlaxEngine into xxSeys1-VisjectCloseButtonFix 2025-06-16 15:02:32 +02:00
Wojtek Figat
90b6293bc2 Add OnPlayEnding to editor modules and windows
#3514
2025-06-16 14:56:35 +02:00
Wojtek Figat
117f890612 Merge branch 'Zode-scenetree-scroll' 2025-06-16 14:50:14 +02:00
Wojtek Figat
a6a2fd2c66 Format code
#3526
2025-06-16 14:48:18 +02:00
Wojtek Figat
a05ca12770 Merge branch 'scenetree-scroll' of https://github.com/Zode/FlaxEngine into Zode-scenetree-scroll 2025-06-16 14:44:54 +02:00
Wojtek Figat
abe7785e94 Merge branch 'xxSeys1-PrefabEditorScrollToSelectionFix' 2025-06-16 14:43:40 +02:00
Wojtek Figat
2cedac8d96 Merge branch 'PrefabEditorScrollToSelectionFix' of https://github.com/xxSeys1/FlaxEngine into xxSeys1-PrefabEditorScrollToSelectionFix 2025-06-16 14:43:34 +02:00
Wojtek Figat
ea854a0f7b Fix potential Grid shader accuracy issues
#3229
2025-06-16 14:41:43 +02:00
Wojtek Figat
d0817809ff Merge branch 'xxSeys1-ContentFinderImprovements' 2025-06-16 14:34:25 +02:00
Wojtek Figat
95f2216f97 Merge branch 'ContentFinderImprovements' of https://github.com/xxSeys1/FlaxEngine into xxSeys1-ContentFinderImprovements 2025-06-16 14:32:31 +02:00
Wojtek Figat
7e5edf1b33 Merge branch 'xxSeys1-ClearSearchOnAssetReferenceNavigate' 2025-06-16 14:30:58 +02:00
Wojtek Figat
c649a4f4b2 Merge branch 'ClearSearchOnAssetReferenceNavigate' of https://github.com/xxSeys1/FlaxEngine into xxSeys1-ClearSearchOnAssetReferenceNavigate 2025-06-16 14:30:53 +02:00
6ff260d052 Merge remote-tracking branch 'origin/master' into sdl_platform 2025-06-16 14:09:29 +03:00
88d2b72822 Update SDL to 3.3.x
Fixes popup focus issues on Linux
2025-06-16 14:09:04 +03:00
Wojtek Figat
3c74b315a8 Merge branch 'Zode-console-hotkey' 2025-06-15 23:47:29 +02:00
Wojtek Figat
f841575378 Merge branch 'console-hotkey' of https://github.com/Zode/FlaxEngine into Zode-console-hotkey 2025-06-15 23:25:09 +02:00
Wojtek Figat
d90377ed62 Merge branch 'Zode-import-export-warnings' 2025-06-15 23:23:22 +02:00
Wojtek Figat
c8d622bda9 Merge branch 'import-export-warnings' of https://github.com/Zode/FlaxEngine into Zode-import-export-warnings 2025-06-15 23:23:18 +02:00
Wojtek Figat
fbf2d8f567 Merge branch 'xxSeys1-ItemListImprovedKeyboardNav' 2025-06-15 23:06:26 +02:00
Wojtek Figat
42687a792c Merge branch 'ItemListImprovedKeyboardNav' of https://github.com/xxSeys1/FlaxEngine into xxSeys1-ItemListImprovedKeyboardNav 2025-06-15 22:59:20 +02:00
Wojtek Figat
5c43d35146 Merge branch 'Zode-node-alignment' 2025-06-15 22:32:29 +02:00
Wojtek Figat
c1e1dee975 Merge branch 'node-alignment' of https://github.com/Zode/FlaxEngine into Zode-node-alignment 2025-06-15 22:32:24 +02:00
Wojtek Figat
742d74a2d0 Merge branch 'xxSeys1-ModelSliders' 2025-06-15 21:43:04 +02:00
Wojtek Figat
614ffa70a0 Merge branch 'ModelSliders' of https://github.com/xxSeys1/FlaxEngine into xxSeys1-ModelSliders 2025-06-15 21:43:00 +02:00
Wojtek Figat
4b4331fd70 Merge branch 'Zode-visject-better-selection' 2025-06-15 21:28:42 +02:00
Wojtek Figat
e221f7204b Merge branch 'visject-better-selection' of https://github.com/Zode/FlaxEngine into Zode-visject-better-selection 2025-06-15 21:22:27 +02:00
Wojtek Figat
18fa8e1c47 Merge branch 'Zode-particles-sourcecode' 2025-06-15 20:48:22 +02:00
Wojtek Figat
2f02ec52ed Cleanup code
#3546
2025-06-15 20:48:19 +02:00
Wojtek Figat
9464f97e16 Merge branch 'particles-sourcecode' of https://github.com/Zode/FlaxEngine into Zode-particles-sourcecode 2025-06-15 20:45:18 +02:00
Wojtek Figat
54467a4a5e Merge branch 'Zode-layers-matrix-improvements' 2025-06-15 20:41:23 +02:00
Wojtek Figat
3a9e175043 Merge branch 'layers-matrix-improvements' of https://github.com/Zode/FlaxEngine into Zode-layers-matrix-improvements 2025-06-15 20:40:22 +02:00
Wojtek Figat
9dff048cb5 Merge branch 'Tryibion-main-menu-get-add' 2025-06-15 20:36:37 +02:00
Wojtek Figat
f376fd50a9 Merge branch 'main-menu-get-add' of https://github.com/Tryibion/FlaxEngine into Tryibion-main-menu-get-add 2025-06-15 20:36:32 +02:00
Wojtek Figat
e27cf04f91 Merge branch 'Zode-debug-quicktoggle' 2025-06-15 20:32:00 +02:00
Wojtek Figat
648504ceb1 Format code
#3544
2025-06-15 20:31:04 +02:00
xxSeys1
e2f741cab9 adjust model window and animated model slider speeds 2025-06-12 18:45:02 +02:00
xxSeys1
214ec9f2b1 fix node delete button not checking if the user is performing certain actions on the surface before deleting node 2025-06-12 00:49:39 +02:00
Zode
27ac755bbe Make particle emitter editor window source code button disable itself is no source code is available 2025-06-11 23:15:11 +03:00
Zode
00055ef663 Make tool strip buttons more responsive by also reaction to double left clicks 2025-06-11 17:47:27 +03:00
Zode
aa59a6faf7 Extract function to lessen repeat code for debug group buttons, add shift functionality to quick toggle others. 2025-06-11 17:46:37 +03:00
Zode
e7d2025010 Merge less flicker pr, and snatch the badge
Co-authored-by: Zode <jonzqzode@gmail.com>
Co-authored-by: Saas <kaktusreiniger@gmail.com>
2025-06-10 16:45:02 +03:00
xxSeys1
b418ab5275 reduce flickering in highlights and boxes 2025-06-10 14:58:31 +02:00
Zode
c1e782bb32 Add hotkey to quick focus debug console input 2025-06-09 23:34:02 +03:00
Chandler Cox
e1a2a36978 Add GetOrAddButton utility for MainMenu. 2025-06-09 15:02:43 -05:00
xxSeys1
793bc33b2f fix right clicking on item reset search and scroll 2025-06-09 18:40:33 +02:00
xxSeys1
2109a2d261 update content finder popup to wrap on keyboard navigation
- Fixes auto scroll
- Make it wrap
- Add pressing backspace to focus search bar and select all text
2025-06-09 18:40:12 +02:00
Zode
9e50a39ebf Add define guards so that the messagebox only appears in editor builds 2025-06-09 16:19:39 +03:00
Zode
7fc564a0ac Pop error box on lightmap UV generation also 2025-06-09 15:07:52 +03:00
Zode
8dfb564fb3 Add messagebox to windows import too 2025-06-09 15:04:34 +03:00
Zode
f8daff273a Add import & export warning messageboxes. 2025-06-09 14:56:54 +03:00
xxSeys1
112e728465 fix scroll to node on selection in prefab editor 2025-06-09 13:56:41 +02:00
Zode
9c9d560ce5 Add hotkeys to visject formatting 2025-06-08 03:32:51 +03:00
Zode
f1945552ab Add horizontal and vertical distribution 2025-06-08 02:42:28 +03:00
Zode
ecd5559aad Clean up a bit code after moving it around. 2025-06-08 00:41:02 +03:00
Zode
1fa83639c2 Fix update order inconsistencies between machines by exposing an action for when defered layout happens. 2025-06-08 00:38:59 +03:00
Zode
568719b615 Fix scroll issue caused by tree's defered layout update 2025-06-07 23:21:41 +03:00
Zode
74000fa766 Expand tree if necessary, so the selected node will be shown 2025-06-07 22:53:07 +03:00
Zode
1d63067614 Add ability to do additive and subtractive selections in visject surfaces using ctrl and shift during selection. 2025-06-07 21:04:59 +03:00
xxSeys1
85fd1389db clear content panel search when selecting asset picker asset 2025-06-07 18:17:40 +02:00
xxSeys1
cce042045e wrap scrolling items with arrow keys and simplify scrolling logic 2025-06-07 17:34:01 +02:00
Zode
53e3cee196 Scroll selected to view when emptying out search box 2025-06-07 17:15:54 +03:00
Zode
6ee3b23261 Add highlighting to layers matrix editor to improve UX 2025-06-07 16:57:28 +03:00
Zode
1a77ba4552 Add node alignment formatting options to visject 2025-06-07 13:15:39 +03:00
Wojtek Figat
eee4e55cf0 Fix debug shapes change 2025-06-05 22:26:45 +02:00
Wojtek Figat
c2cbaeed30 Add option to change Character Controller capsule origin to start at feet location 2025-06-05 17:48:07 +02:00
Wojtek Figat
e982a23ed3 Add CharacterController.Resize for quick crouching implementation for characters 2025-06-05 15:07:51 +02:00
Wojtek Figat
f6feae5cf2 Optimize collider cached scale 2025-06-05 15:06:03 +02:00
Wojtek Figat
ba75fd5882 Fix crash regression when textbox watermak is null 2025-06-05 12:47:45 +02:00
Wojtek Figat
1eaf40f2f7 Fix changing CharacterController center at runtime to maintain actor placement 2025-06-05 12:40:47 +02:00
Wojtek Figat
fe98a23cb4 Merge branch 'GoaLitiuM-update_tracy' 2025-06-05 00:01:04 +02:00
Wojtek Figat
77bf03128e Merge branch 'update_tracy' of https://github.com/GoaLitiuM/FlaxEngine into GoaLitiuM-update_tracy 2025-06-04 23:53:32 +02:00
Wojtek Figat
8f49a492d8 Fix duplicating json assets to properly remap object IDs
#3441
2025-06-04 23:49:19 +02:00
Wojtek Figat
496856d12e Add shader header proxy for easy .hlsl files creation within Editor 2025-06-04 00:12:43 +02:00
6c63c2f650 Update tracy to 0.12.0 2025-06-02 20:00:06 +03:00
7c5628d47e Fix crash caused by conflicting tracy DbgHelp lock helper names 2025-05-02 14:20:18 +03:00
9645008460 Update tracy to 0.11.1 2025-05-02 14:20:18 +03:00
121 changed files with 5580 additions and 1202 deletions

BIN
Content/Shaders/Editor/Grid.flax (Stored with Git LFS)

Binary file not shown.

View File

@@ -10,11 +10,9 @@ using FlaxEngine;
namespace FlaxEditor.Content
{
/// <summary>
/// Context proxy object for shader source files (represented by <see cref="ShaderSourceItem"/>).
/// Base class for shader source files.
/// </summary>
/// <seealso cref="FlaxEditor.Content.ContentProxy" />
[ContentContextMenu("New/Shader Source")]
public class ShaderSourceProxy : ContentProxy
public abstract class ShaderBaseProxy : ContentProxy
{
/// <inheritdoc />
public override bool CanCreate(ContentFolder targetLocation)
@@ -29,6 +27,21 @@ namespace FlaxEditor.Content
return targetLocation.ShortName == "Source" && prevTargetLocation.ShortName == "Shaders";
}
/// <inheritdoc />
public override EditorWindow Open(Editor editor, ContentItem item)
{
Editor.Instance.CodeEditing.OpenFile(item.Path);
return null;
}
}
/// <summary>
/// Context proxy object for shader source files (represented by <see cref="ShaderSourceItem"/>).
/// </summary>
/// <seealso cref="FlaxEditor.Content.ContentProxy" />
[ContentContextMenu("New/Shader Source (.shader)")]
public class ShaderSourceProxy : ShaderBaseProxy
{
/// <inheritdoc />
public override void Create(string outputPath, object arg)
{
@@ -44,13 +57,6 @@ namespace FlaxEditor.Content
File.WriteAllText(outputPath, shaderTemplate, Encoding.UTF8);
}
/// <inheritdoc />
public override EditorWindow Open(Editor editor, ContentItem item)
{
Editor.Instance.CodeEditing.OpenFile(item.Path);
return null;
}
/// <inheritdoc />
public override Color AccentColor => Color.FromRGB(0x7542f5);
@@ -66,4 +72,33 @@ namespace FlaxEditor.Content
return item is ShaderSourceItem;
}
}
/// <summary>
/// Context proxy object for shader header files.
/// </summary>
/// <seealso cref="FlaxEditor.Content.ContentProxy" />
[ContentContextMenu("New/Shader Header (.hlsl)")]
public class ShaderHeaderProxy : ShaderBaseProxy
{
/// <inheritdoc />
public override void Create(string outputPath, object arg)
{
File.WriteAllText(outputPath, "\n", Encoding.UTF8);
}
/// <inheritdoc />
public override Color AccentColor => Color.FromRGB(0x2545a5);
/// <inheritdoc />
public override string FileExtension => "hlsl";
/// <inheritdoc />
public override string Name => "Shader Header";
/// <inheritdoc />
public override bool IsProxyFor(ContentItem item)
{
return false;
}
}
}

View File

@@ -1,6 +1,5 @@
// Copyright (c) Wojciech Figat. All rights reserved.
using System;
using System.Collections.Generic;
using FlaxEditor.Content.Settings;
using FlaxEngine;
@@ -16,6 +15,11 @@ namespace FlaxEditor.CustomEditors.Dedicated
{
private int _layersCount;
private List<CheckBox> _checkBoxes;
private VerticalPanel _upperRightCell;
private VerticalPanel _bottomLeftCell;
private UniformGridPanel _grid;
private Border _horizontalHighlight;
private Border _verticalHighlight;
/// <inheritdoc />
public override DisplayStyle Style => DisplayStyle.InlineIntoParent;
@@ -37,12 +41,29 @@ namespace FlaxEditor.CustomEditors.Dedicated
Parent = panel,
};
var style = FlaxEngine.GUI.Style.Current;
_horizontalHighlight = new Border()
{
Parent = panel,
BorderColor = style.Foreground,
BorderWidth = 1.0f,
Visible = false,
};
_verticalHighlight = new Border()
{
Parent = panel,
BorderColor = style.Foreground,
BorderWidth = 1.0f,
Visible = false,
};
var upperLeftCell = new Label
{
Parent = gridPanel,
};
var upperRightCell = new VerticalPanel
_upperRightCell = new VerticalPanel
{
ClipChildren = false,
Pivot = new Float2(0.00001f, 0.0f),
@@ -54,7 +75,7 @@ namespace FlaxEditor.CustomEditors.Dedicated
Parent = gridPanel,
};
var bottomLeftCell = new VerticalPanel
_bottomLeftCell = new VerticalPanel
{
Pivot = Float2.Zero,
Spacing = 0,
@@ -63,7 +84,7 @@ namespace FlaxEditor.CustomEditors.Dedicated
Parent = gridPanel,
};
var grid = new UniformGridPanel(0)
_grid = new UniformGridPanel(0)
{
SlotsHorizontally = layersCount,
SlotsVertically = layersCount,
@@ -74,13 +95,13 @@ namespace FlaxEditor.CustomEditors.Dedicated
int layerIndex = 0;
for (; layerIndex < layerNames.Length; layerIndex++)
{
upperRightCell.AddChild(new Label
_upperRightCell.AddChild(new Label
{
Height = labelsHeight,
Text = layerNames[layerNames.Length - layerIndex - 1],
HorizontalAlignment = TextAlignment.Near,
});
bottomLeftCell.AddChild(new Label
_bottomLeftCell.AddChild(new Label
{
Height = labelsHeight,
Text = layerNames[layerIndex],
@@ -90,13 +111,13 @@ namespace FlaxEditor.CustomEditors.Dedicated
for (; layerIndex < layersCount; layerIndex++)
{
string name = "Layer " + layerIndex;
upperRightCell.AddChild(new Label
_upperRightCell.AddChild(new Label
{
Height = labelsHeight,
Text = name,
HorizontalAlignment = TextAlignment.Near,
});
bottomLeftCell.AddChild(new Label
_bottomLeftCell.AddChild(new Label
{
Height = labelsHeight,
Text = name,
@@ -118,7 +139,7 @@ namespace FlaxEditor.CustomEditors.Dedicated
var box = new CheckBox(0, 0, true)
{
Tag = new Float2(_layersCount - column - 1, row),
Parent = grid,
Parent = _grid,
Checked = GetBit(column, row),
};
box.StateChanged += OnCheckBoxChanged;
@@ -126,7 +147,7 @@ namespace FlaxEditor.CustomEditors.Dedicated
}
for (; column < layersCount; column++)
{
grid.AddChild(new Label());
_grid.AddChild(new Label());
}
}
}
@@ -141,6 +162,18 @@ namespace FlaxEditor.CustomEditors.Dedicated
/// <inheritdoc />
public override void Refresh()
{
int selectedColumn = -1;
int selectedRow = -1;
var style = FlaxEngine.GUI.Style.Current;
bool mouseOverGrid = _grid.IsMouseOver;
// Only hide highlights if mouse is not over the grid to reduce flickering
if (!mouseOverGrid)
{
_horizontalHighlight.Visible = false;
_verticalHighlight.Visible = false;
}
// Sync check boxes
for (int i = 0; i < _checkBoxes.Count; i++)
{
@@ -148,6 +181,39 @@ namespace FlaxEditor.CustomEditors.Dedicated
int column = (int)((Float2)box.Tag).X;
int row = (int)((Float2)box.Tag).Y;
box.Checked = GetBit(column, row);
if (box.IsMouseOver)
{
selectedColumn = column;
selectedRow = row;
_horizontalHighlight.X = _grid.X - _bottomLeftCell.Width;
_horizontalHighlight.Y = _grid.Y + box.Y;
_horizontalHighlight.Width = _bottomLeftCell.Width + box.Width + box.X;
_horizontalHighlight.Height = box.Height;
_horizontalHighlight.Visible = true;
_verticalHighlight.X = _grid.X + box.X;
_verticalHighlight.Y = _grid.Y - _upperRightCell.Height;
_verticalHighlight.Width = box.Width;
_verticalHighlight.Height = _upperRightCell.Height + box.Height + box.Y;
_verticalHighlight.Visible = true;
}
}
for (int i = 0; i < _checkBoxes.Count; i++)
{
var box = _checkBoxes[i];
int column = (int)((Float2)box.Tag).X;
int row = (int)((Float2)box.Tag).Y;
if (!mouseOverGrid)
box.ImageColor = style.BorderSelected;
else if (selectedColumn > -1 && selectedRow > -1)
{
bool isRowOrColumn = column == selectedColumn || row == selectedRow;
box.ImageColor = style.BorderSelected * (isRowOrColumn ? 1.2f : 0.75f);
}
}
}

View File

@@ -670,6 +670,8 @@ namespace FlaxEditor
{
FlaxEngine.Networking.NetworkManager.Stop(); // Shutdown any multiplayer from playmode
PlayModeEnding?.Invoke();
for (int i = 0; i < _modules.Count; i++)
_modules[i].OnPlayEnding();
}
internal void OnPlayEnd()

View File

@@ -299,6 +299,7 @@ namespace FlaxEditor.GUI
{
// Select asset
Editor.Instance.Windows.ContentWin.Select(Validator.SelectedItem);
Editor.Instance.Windows.ContentWin.ClearItemsSearch();
}
}
else if (Button1Rect.Contains(location))
@@ -312,6 +313,7 @@ namespace FlaxEditor.GUI
{
// Select asset
Editor.Instance.Windows.ContentWin.Select(Validator.SelectedItem);
Editor.Instance.Windows.ContentWin.ClearItemsSearch();
}
else if (Button3Rect.Contains(location))
{

View File

@@ -563,8 +563,17 @@ namespace FlaxEditor.GUI
case KeyboardKeys.Escape:
Hide();
return true;
case KeyboardKeys.Backspace:
// Alow the user to quickly focus the searchbar
if (_searchBox != null && !_searchBox.IsFocused)
{
_searchBox.Focus();
_searchBox.SelectAll();
return true;
}
break;
case KeyboardKeys.ArrowDown:
{
case KeyboardKeys.ArrowUp:
if (RootWindow.FocusedControl == null)
{
// Focus search box if nothing is focused
@@ -572,39 +581,17 @@ namespace FlaxEditor.GUI
return true;
}
// Focus the first visible item or then next one
// Get the next item
var items = GetVisibleItems();
var focusedIndex = items.IndexOf(focusedItem);
if (focusedIndex == -1)
focusedIndex = -1;
if (focusedIndex + 1 < items.Count)
{
var item = items[focusedIndex + 1];
item.Focus();
_scrollPanel.ScrollViewTo(item);
return true;
}
break;
}
case KeyboardKeys.ArrowUp:
if (focusedItem != null)
{
// Focus the previous visible item or the search box
var items = GetVisibleItems();
var focusedIndex = items.IndexOf(focusedItem);
if (focusedIndex == 0)
{
_searchBox?.Focus();
}
else if (focusedIndex > 0)
{
var item = items[focusedIndex - 1];
item.Focus();
_scrollPanel.ScrollViewTo(item);
return true;
}
}
break;
int delta = key == KeyboardKeys.ArrowDown ? -1 : 1;
int nextIndex = Mathf.Wrap(focusedIndex - delta, 0, items.Count - 1);
var nextItem = items[nextIndex];
// Focus the next item
nextItem.Focus();
_scrollPanel.ScrollViewTo(nextItem);
return true;
case KeyboardKeys.Return:
if (focusedItem != null)
{

View File

@@ -268,6 +268,19 @@ namespace FlaxEditor.GUI
return AddChild(new MainMenuButton(text));
}
/// <summary>
/// Gets or adds a button.
/// </summary>
/// <param name="text">The button text</param>
/// <returns>The existing or created button control.</returns>
public MainMenuButton GetOrAddButton(string text)
{
MainMenuButton result = GetButton(text);
if (result == null)
result = AddButton(text);
return result;
}
/// <summary>
/// Gets the button.
/// </summary>

View File

@@ -122,6 +122,14 @@ namespace FlaxEditor.GUI
return this;
}
private void OnClicked()
{
if (AutoCheck)
Checked = !Checked;
Clicked?.Invoke();
(Parent as ToolStrip)?.OnButtonClicked(this);
}
/// <inheritdoc />
public override void Draw()
{
@@ -196,11 +204,7 @@ namespace FlaxEditor.GUI
if (button == MouseButton.Left && _primaryMouseDown)
{
_primaryMouseDown = false;
if (AutoCheck)
Checked = !Checked;
Clicked?.Invoke();
(Parent as ToolStrip)?.OnButtonClicked(this);
OnClicked();
return true;
}
if (button == MouseButton.Right && _secondaryMouseDown)
@@ -215,6 +219,18 @@ namespace FlaxEditor.GUI
return base.OnMouseUp(location, button);
}
/// <inheritdoc />
public override bool OnMouseDoubleClick(Float2 location, MouseButton button)
{
if (button == MouseButton.Left)
{
OnClicked();
return true;
}
return false;
}
/// <inheritdoc />
public override void OnMouseLeave()
{

View File

@@ -73,6 +73,11 @@ namespace FlaxEditor.GUI.Tree
/// </summary>
public bool DrawRootTreeLine = true;
/// <summary>
/// Occurs when the deferred layout operation was performed.
/// </summary>
public event Action AfterDeferredLayout;
/// <summary>
/// Gets or sets the margin for the child tree nodes.
/// </summary>
@@ -375,6 +380,7 @@ namespace FlaxEditor.GUI.Tree
if (_deferLayoutUpdate)
{
base.PerformLayout();
AfterDeferredLayout?.Invoke();
_deferLayoutUpdate = false;
}

View File

@@ -1135,6 +1135,7 @@ namespace FlaxEditor.Modules
Proxy.Add(new FontProxy());
Proxy.Add(new ShaderProxy());
Proxy.Add(new ShaderSourceProxy());
Proxy.Add(new ShaderHeaderProxy());
Proxy.Add(new ParticleEmitterProxy());
Proxy.Add(new ParticleEmitterFunctionProxy());
Proxy.Add(new ParticleSystemProxy());

View File

@@ -76,6 +76,13 @@ namespace FlaxEditor.Modules
{
}
/// <summary>
/// Called when Editor will leave the play mode.
/// </summary>
public virtual void OnPlayEnding()
{
}
/// <summary>
/// Called when Editor leaves the play mode.
/// </summary>

View File

@@ -1226,6 +1226,13 @@ namespace FlaxEditor.Modules
Windows[i].OnPlayBegin();
}
/// <inheritdoc />
public override void OnPlayEnding()
{
for (int i = 0; i < Windows.Count; i++)
Windows[i].OnPlayEnding();
}
/// <inheritdoc />
public override void OnPlayEnd()
{

View File

@@ -139,6 +139,10 @@ namespace FlaxEditor.Options
[EditorDisplay("Common"), EditorOrder(240)]
public InputBinding ToggleFullscreen = new InputBinding(KeyboardKeys.F11);
[DefaultValue(typeof(InputBinding), "Ctrl+BackQuote")]
[EditorDisplay("Common"), EditorOrder(250)]
public InputBinding FocusConsoleCommand = new InputBinding(KeyboardKeys.BackQuote, KeyboardKeys.Control);
#endregion
#region File
@@ -647,5 +651,45 @@ namespace FlaxEditor.Options
public InputBinding VisualScriptDebuggerWindow = new InputBinding(KeyboardKeys.None);
#endregion
#region Node editors
[DefaultValue(typeof(InputBinding), "Shift+W")]
[EditorDisplay("Node editors"), EditorOrder(4500)]
public InputBinding NodesAlignTop = new InputBinding(KeyboardKeys.W, KeyboardKeys.Shift);
[DefaultValue(typeof(InputBinding), "Shift+A")]
[EditorDisplay("Node editors"), EditorOrder(4510)]
public InputBinding NodesAlignLeft = new InputBinding(KeyboardKeys.A, KeyboardKeys.Shift);
[DefaultValue(typeof(InputBinding), "Shift+S")]
[EditorDisplay("Node editors"), EditorOrder(4520)]
public InputBinding NodesAlignBottom = new InputBinding(KeyboardKeys.S, KeyboardKeys.Shift);
[DefaultValue(typeof(InputBinding), "Shift+D")]
[EditorDisplay("Node editors"), EditorOrder(4530)]
public InputBinding NodesAlignRight = new InputBinding(KeyboardKeys.D, KeyboardKeys.Shift);
[DefaultValue(typeof(InputBinding), "Alt+Shift+W")]
[EditorDisplay("Node editors"), EditorOrder(4540)]
public InputBinding NodesAlignMiddle = new InputBinding(KeyboardKeys.W, KeyboardKeys.Shift, KeyboardKeys.Alt);
[DefaultValue(typeof(InputBinding), "Alt+Shift+S")]
[EditorDisplay("Node editors"), EditorOrder(4550)]
public InputBinding NodesAlignCenter = new InputBinding(KeyboardKeys.S, KeyboardKeys.Shift, KeyboardKeys.Alt);
[DefaultValue(typeof(InputBinding), "Q")]
[EditorDisplay("Node editors"), EditorOrder(4560)]
public InputBinding NodesAutoFormat = new InputBinding(KeyboardKeys.Q);
[DefaultValue(typeof(InputBinding), "None")]
[EditorDisplay("Node editors"), EditorOrder(4570)]
public InputBinding NodesDistributeHorizontal = new InputBinding(KeyboardKeys.None);
[DefaultValue(typeof(InputBinding), "None")]
[EditorDisplay("Node editors"), EditorOrder(4580)]
public InputBinding NodesDistributeVertical = new InputBinding(KeyboardKeys.None);
#endregion
}
}

View File

@@ -0,0 +1,43 @@
// Copyright (c) Wojciech Figat. All rights reserved.
using FlaxEngine;
namespace FlaxEditor.Surface
{
/// <summary>
/// Node Alignment type
/// </summary>
[HideInEditor]
public enum NodeAlignmentType
{
/// <summary>
/// Align nodes vertically to top, matching top-most node
/// </summary>
Top,
/// <summary>
/// Align nodes vertically to middle, using average of all nodes
/// </summary>
Middle,
/// <summary>
/// Align nodes vertically to bottom, matching bottom-most node
/// </summary>
Bottom,
/// <summary>
/// Align nodes horizontally to left, matching left-most node
/// </summary>
Left,
/// <summary>
/// Align nodes horizontally to center, using average of all nodes
/// </summary>
Center,
/// <summary>
/// Align nodes horizontally to right, matching right-most node
/// </summary>
Right,
}
}

View File

@@ -912,7 +912,7 @@ namespace FlaxEditor.Surface
/// <inheritdoc />
public override bool OnTestTooltipOverControl(ref Float2 location)
{
return _headerRect.Contains(ref location) && ShowTooltip;
return _headerRect.Contains(ref location) && ShowTooltip && !Surface.IsConnecting && !Surface.IsBoxSelecting;
}
/// <inheritdoc />
@@ -1070,7 +1070,7 @@ namespace FlaxEditor.Surface
// Header
var headerColor = style.BackgroundHighlighted;
if (_headerRect.Contains(ref _mousePosition))
if (_headerRect.Contains(ref _mousePosition) && !Surface.IsConnecting && !Surface.IsBoxSelecting)
headerColor *= 1.07f;
Render2D.FillRectangle(_headerRect, headerColor);
Render2D.DrawText(style.FontLarge, Title, _headerRect, style.Foreground, TextAlignment.Center, TextAlignment.Center);
@@ -1078,7 +1078,8 @@ namespace FlaxEditor.Surface
// Close button
if ((Archetype.Flags & NodeFlags.NoCloseButton) == 0 && Surface.CanEdit)
{
Render2D.DrawSprite(style.Cross, _closeButtonRect, _closeButtonRect.Contains(_mousePosition) ? style.Foreground : style.ForegroundGrey);
bool highlightClose = _closeButtonRect.Contains(_mousePosition) && !Surface.IsConnecting && !Surface.IsBoxSelecting;
Render2D.DrawSprite(style.Cross, _closeButtonRect, highlightClose ? style.Foreground : style.ForegroundGrey);
}
// Footer
@@ -1123,8 +1124,9 @@ namespace FlaxEditor.Surface
if (base.OnMouseUp(location, button))
return true;
// Close
if (button == MouseButton.Left && (Archetype.Flags & NodeFlags.NoCloseButton) == 0 && _closeButtonRect.Contains(ref location))
// Close/ delete
bool canDelete = !Surface.IsConnecting && !Surface.WasBoxSelecting && !Surface.WasMovingSelection;
if (button == MouseButton.Left && canDelete && (Archetype.Flags & NodeFlags.NoCloseButton) == 0 && _closeButtonRect.Contains(ref location))
{
Surface.Delete(this);
return true;

View File

@@ -191,7 +191,16 @@ namespace FlaxEditor.Surface
private ContextMenuButton _cmCopyButton;
private ContextMenuButton _cmDuplicateButton;
private ContextMenuChildMenu _cmFormatNodesMenu;
private ContextMenuButton _cmFormatNodesConnectionButton;
private ContextMenuButton _cmAlignNodesTopButton;
private ContextMenuButton _cmAlignNodesMiddleButton;
private ContextMenuButton _cmAlignNodesBottomButton;
private ContextMenuButton _cmAlignNodesLeftButton;
private ContextMenuButton _cmAlignNodesCenterButton;
private ContextMenuButton _cmAlignNodesRightButton;
private ContextMenuButton _cmDistributeNodesHorizontallyButton;
private ContextMenuButton _cmDistributeNodesVerticallyButton;
private ContextMenuButton _cmRemoveNodeConnectionsButton;
private ContextMenuButton _cmRemoveBoxConnectionsButton;
private readonly Float2 ContextMenuOffset = new Float2(5);
@@ -399,8 +408,24 @@ namespace FlaxEditor.Surface
}
menu.AddSeparator();
_cmFormatNodesConnectionButton = menu.AddButton("Format node(s)", () => { FormatGraph(SelectedNodes); });
_cmFormatNodesConnectionButton.Enabled = CanEdit && HasNodesSelection;
_cmFormatNodesMenu = menu.AddChildMenu("Format node(s)");
_cmFormatNodesMenu.Enabled = CanEdit && HasNodesSelection;
_cmFormatNodesConnectionButton = _cmFormatNodesMenu.ContextMenu.AddButton("Auto format", Editor.Instance.Options.Options.Input.NodesAutoFormat, () => { FormatGraph(SelectedNodes); });
_cmFormatNodesMenu.ContextMenu.AddSeparator();
_cmAlignNodesTopButton = _cmFormatNodesMenu.ContextMenu.AddButton("Align top", Editor.Instance.Options.Options.Input.NodesAlignTop, () => { AlignNodes(SelectedNodes, NodeAlignmentType.Top); });
_cmAlignNodesMiddleButton = _cmFormatNodesMenu.ContextMenu.AddButton("Align middle", Editor.Instance.Options.Options.Input.NodesAlignMiddle, () => { AlignNodes(SelectedNodes, NodeAlignmentType.Middle); });
_cmAlignNodesBottomButton = _cmFormatNodesMenu.ContextMenu.AddButton("Align bottom", Editor.Instance.Options.Options.Input.NodesAlignBottom, () => { AlignNodes(SelectedNodes, NodeAlignmentType.Bottom); });
_cmFormatNodesMenu.ContextMenu.AddSeparator();
_cmAlignNodesLeftButton = _cmFormatNodesMenu.ContextMenu.AddButton("Align left", Editor.Instance.Options.Options.Input.NodesAlignLeft, () => { AlignNodes(SelectedNodes, NodeAlignmentType.Left); });
_cmAlignNodesCenterButton = _cmFormatNodesMenu.ContextMenu.AddButton("Align center", Editor.Instance.Options.Options.Input.NodesAlignCenter, () => { AlignNodes(SelectedNodes, NodeAlignmentType.Center); });
_cmAlignNodesRightButton = _cmFormatNodesMenu.ContextMenu.AddButton("Align right", Editor.Instance.Options.Options.Input.NodesAlignRight, () => { AlignNodes(SelectedNodes, NodeAlignmentType.Right); });
_cmFormatNodesMenu.ContextMenu.AddSeparator();
_cmDistributeNodesHorizontallyButton = _cmFormatNodesMenu.ContextMenu.AddButton("Distribute horizontally", Editor.Instance.Options.Options.Input.NodesDistributeHorizontal, () => { DistributeNodes(SelectedNodes, false); });
_cmDistributeNodesVerticallyButton = _cmFormatNodesMenu.ContextMenu.AddButton("Distribute vertically", Editor.Instance.Options.Options.Input.NodesDistributeVertical, () => { DistributeNodes(SelectedNodes, true); });
_cmRemoveNodeConnectionsButton = menu.AddButton("Remove all connections to that node(s)", () =>
{

View File

@@ -225,7 +225,7 @@ namespace FlaxEditor.Surface
_rootControl.DrawComments();
if (IsSelecting)
if (IsBoxSelecting)
{
DrawSelection();
}

View File

@@ -282,5 +282,122 @@ namespace FlaxEditor.Surface
return maxOffset;
}
/// <summary>
/// Align given nodes on a graph using the given alignment type.
/// Ignores any potential overlap.
/// </summary>
/// <param name="nodes">List of nodes</param>
/// <param name="alignmentType">Alignemnt type</param>
public void AlignNodes(List<SurfaceNode> nodes, NodeAlignmentType alignmentType)
{
if(nodes.Count <= 1)
return;
var undoActions = new List<MoveNodesAction>();
var boundingBox = GetNodesBounds(nodes);
for(int i = 0; i < nodes.Count; i++)
{
var centerY = boundingBox.Center.Y - (nodes[i].Height / 2);
var centerX = boundingBox.Center.X - (nodes[i].Width / 2);
var newLocation = alignmentType switch
{
NodeAlignmentType.Top => new Float2(nodes[i].Location.X, boundingBox.Top),
NodeAlignmentType.Middle => new Float2(nodes[i].Location.X, centerY),
NodeAlignmentType.Bottom => new Float2(nodes[i].Location.X, boundingBox.Bottom - nodes[i].Height),
NodeAlignmentType.Left => new Float2(boundingBox.Left, nodes[i].Location.Y),
NodeAlignmentType.Center => new Float2(centerX, nodes[i].Location.Y),
NodeAlignmentType.Right => new Float2(boundingBox.Right - nodes[i].Width, nodes[i].Location.Y),
_ => throw new NotImplementedException($"Unsupported node alignment type: {alignmentType}"),
};
var locationDelta = newLocation - nodes[i].Location;
nodes[i].Location = newLocation;
if(Undo != null)
undoActions.Add(new MoveNodesAction(Context, new[] { nodes[i].ID }, locationDelta));
}
MarkAsEdited(false);
Undo?.AddAction(new MultiUndoAction(undoActions, $"Align nodes ({alignmentType})"));
}
/// <summary>
/// Distribute the given nodes as equally as possible inside the bounding box, if no fit can be done it will use a default pad of 10 pixels between nodes.
/// </summary>
/// <param name="nodes">List of nodes</param>
/// <param name="vertically">If false will be done horizontally, if true will be done vertically</param>
public void DistributeNodes(List<SurfaceNode> nodes, bool vertically)
{
if(nodes.Count <= 1)
return;
var undoActions = new List<MoveNodesAction>();
var boundingBox = GetNodesBounds(nodes);
float padding = 10;
float totalSize = 0;
for (int i = 0; i < nodes.Count; i++)
{
if (vertically)
{
totalSize += nodes[i].Height;
}
else
{
totalSize += nodes[i].Width;
}
}
if(vertically)
{
nodes.Sort((leftValue, rightValue) => { return leftValue.Y.CompareTo(rightValue.Y); });
float position = boundingBox.Top;
if(totalSize < boundingBox.Height)
{
padding = (boundingBox.Height - totalSize) / nodes.Count;
}
for(int i = 0; i < nodes.Count; i++)
{
var newLocation = new Float2(nodes[i].X, position);
var locationDelta = newLocation - nodes[i].Location;
nodes[i].Location = newLocation;
position += nodes[i].Height + padding;
if (Undo != null)
undoActions.Add(new MoveNodesAction(Context, new[] { nodes[i].ID }, locationDelta));
}
}
else
{
nodes.Sort((leftValue, rightValue) => { return leftValue.X.CompareTo(rightValue.X); });
float position = boundingBox.Left;
if(totalSize < boundingBox.Width)
{
padding = (boundingBox.Width - totalSize) / nodes.Count;
}
for(int i = 0; i < nodes.Count; i++)
{
var newLocation = new Float2(position, nodes[i].Y);
var locationDelta = newLocation - nodes[i].Location;
nodes[i].Location = newLocation;
position += nodes[i].Width + padding;
if (Undo != null)
undoActions.Add(new MoveNodesAction(Context, new[] { nodes[i].ID }, locationDelta));
}
}
MarkAsEdited(false);
Undo?.AddAction(new MultiUndoAction(undoActions, vertically ? "Distribute nodes vertically" : "Distribute nodes horizontally"));
}
}
}

View File

@@ -27,6 +27,7 @@ namespace FlaxEditor.Surface
private Float2 _movingNodesDelta;
private Float2 _gridRoundingDelta;
private HashSet<SurfaceNode> _movingNodes;
private HashSet<SurfaceNode> _temporarySelectedNodes;
private readonly Stack<InputBracket> _inputBrackets = new Stack<InputBracket>();
private class InputBracket
@@ -130,13 +131,34 @@ namespace FlaxEditor.Surface
if (_rootControl.Children[i] is SurfaceControl control)
{
var select = control.IsSelectionIntersecting(ref selectionRect);
if (select != control.IsSelected)
if (Root.GetKey(KeyboardKeys.Shift))
{
control.IsSelected = select;
selectionChanged = true;
if (select == control.IsSelected && _temporarySelectedNodes.Contains(control))
{
control.IsSelected = !select;
selectionChanged = true;
}
}
else if (Root.GetKey(KeyboardKeys.Control))
{
if (select != control.IsSelected && !_temporarySelectedNodes.Contains(control))
{
control.IsSelected = select;
selectionChanged = true;
}
}
else
{
if (select != control.IsSelected)
{
control.IsSelected = select;
selectionChanged = true;
}
}
}
}
if (selectionChanged)
SelectionChanged?.Invoke();
}
@@ -461,6 +483,19 @@ namespace FlaxEditor.Surface
// Cache data
_isMovingSelection = false;
_mousePos = location;
if(_temporarySelectedNodes == null)
_temporarySelectedNodes = new HashSet<SurfaceNode>();
else
_temporarySelectedNodes.Clear();
for (int i = 0; i < _rootControl.Children.Count; i++)
{
if (_rootControl.Children[i] is SurfaceNode node && node.IsSelected)
{
_temporarySelectedNodes.Add(node);
}
}
if (button == MouseButton.Left)
{
_leftMouseDown = true;
@@ -488,9 +523,11 @@ namespace FlaxEditor.Surface
// Check if user is pressing control
if (Root.GetKey(KeyboardKeys.Control))
{
// Add/remove from selection
controlUnderMouse.IsSelected = !controlUnderMouse.IsSelected;
SelectionChanged?.Invoke();
AddToSelection(controlUnderMouse);
}
else if (Root.GetKey(KeyboardKeys.Shift))
{
RemoveFromSelection(controlUnderMouse);
}
// Check if node isn't selected
else if (!controlUnderMouse.IsSelected)
@@ -500,10 +537,14 @@ namespace FlaxEditor.Surface
}
// Start moving selected nodes
StartMouseCapture();
_movingSelectionViewPos = _rootControl.Location;
_movingNodesDelta = Float2.Zero;
OnGetNodesToMove();
if (!Root.GetKey(KeyboardKeys.Shift))
{
StartMouseCapture();
_movingSelectionViewPos = _rootControl.Location;
_movingNodesDelta = Float2.Zero;
OnGetNodesToMove();
}
Focus();
return true;
}
@@ -515,7 +556,12 @@ namespace FlaxEditor.Surface
{
// Start selecting or commenting
StartMouseCapture();
ClearSelection();
if (!Root.GetKey(KeyboardKeys.Control) && !Root.GetKey(KeyboardKeys.Shift))
{
ClearSelection();
}
Focus();
return true;
}
@@ -544,6 +590,9 @@ namespace FlaxEditor.Surface
// Cache flags and state
if (_leftMouseDown && button == MouseButton.Left)
{
WasBoxSelecting = IsBoxSelecting;
WasMovingSelection = _isMovingSelection;
_leftMouseDown = false;
EndMouseCapture();
Cursor = CursorType.Default;

View File

@@ -232,15 +232,25 @@ namespace FlaxEditor.Surface
}
/// <summary>
/// Gets a value indicating whether user is selecting nodes.
/// Gets a value indicating whether user is box selecting nodes.
/// </summary>
public bool IsSelecting => _leftMouseDown && !_isMovingSelection && _connectionInstigator == null;
public bool IsBoxSelecting => _leftMouseDown && !_isMovingSelection && _connectionInstigator == null;
/// <summary>
/// Gets a value indicating whether user was previously box selecting nodes.
/// </summary>
public bool WasBoxSelecting { get; private set; }
/// <summary>
/// Gets a value indicating whether user is moving selected nodes.
/// </summary>
public bool IsMovingSelection => _leftMouseDown && _isMovingSelection && _connectionInstigator == null;
/// <summary>
/// Gets a value indicating whether user was previously moving selected nodes.
/// </summary>
public bool WasMovingSelection { get; private set; }
/// <summary>
/// Gets a value indicating whether user is connecting nodes.
/// </summary>
@@ -405,6 +415,15 @@ namespace FlaxEditor.Surface
new InputActionsContainer.Binding(options => options.Paste, Paste),
new InputActionsContainer.Binding(options => options.Cut, Cut),
new InputActionsContainer.Binding(options => options.Duplicate, Duplicate),
new InputActionsContainer.Binding(options => options.NodesAutoFormat, () => { FormatGraph(SelectedNodes); }),
new InputActionsContainer.Binding(options => options.NodesAlignTop, () => { AlignNodes(SelectedNodes, NodeAlignmentType.Top); }),
new InputActionsContainer.Binding(options => options.NodesAlignMiddle, () => { AlignNodes(SelectedNodes, NodeAlignmentType.Middle); }),
new InputActionsContainer.Binding(options => options.NodesAlignBottom, () => { AlignNodes(SelectedNodes, NodeAlignmentType.Bottom); }),
new InputActionsContainer.Binding(options => options.NodesAlignLeft, () => { AlignNodes(SelectedNodes, NodeAlignmentType.Left); }),
new InputActionsContainer.Binding(options => options.NodesAlignCenter, () => { AlignNodes(SelectedNodes, NodeAlignmentType.Center); }),
new InputActionsContainer.Binding(options => options.NodesAlignRight, () => { AlignNodes(SelectedNodes, NodeAlignmentType.Right); }),
new InputActionsContainer.Binding(options => options.NodesDistributeHorizontal, () => { DistributeNodes(SelectedNodes, false); }),
new InputActionsContainer.Binding(options => options.NodesDistributeVertical, () => { DistributeNodes(SelectedNodes, true); }),
});
Context.ControlSpawned += OnSurfaceControlSpawned;
@@ -710,6 +729,18 @@ namespace FlaxEditor.Surface
SelectionChanged?.Invoke();
}
/// <summary>
/// Removes the specified control from the selection.
/// </summary>
/// <param name="control">The control.</param>
public void RemoveFromSelection(SurfaceControl control)
{
if (!control.IsSelected)
return;
control.IsSelected = false;
SelectionChanged?.Invoke();
}
/// <summary>
/// Selects the specified control.
/// </summary>

View File

@@ -1518,6 +1518,7 @@ namespace FlaxEditor.Utilities
inputActions.Add(options => options.OpenScriptsProject, () => Editor.Instance.CodeEditing.OpenSolution());
inputActions.Add(options => options.GenerateScriptsProject, () => Editor.Instance.ProgressReporting.GenerateScriptsProjectFiles.RunAsync());
inputActions.Add(options => options.RecompileScripts, ScriptsBuilder.Compile);
inputActions.Add(options => options.FocusConsoleCommand, () => Editor.Instance.Windows.OutputLogWin.FocusCommand());
}
internal static string ToPathProject(string path)

View File

@@ -236,6 +236,7 @@ namespace FlaxEditor.Windows.Assets
var group = layout.Group("General");
var minScreenSize = group.FloatValue("Min Screen Size", "The minimum screen size to draw model (the bottom limit). Used to cull small models. Set to 0 to disable this feature.");
minScreenSize.ValueBox.SlideSpeed = 0.005f;
minScreenSize.ValueBox.MinValue = 0.0f;
minScreenSize.ValueBox.MaxValue = 1.0f;
minScreenSize.ValueBox.Value = proxy.Asset.MinScreenSize;
@@ -476,12 +477,12 @@ namespace FlaxEditor.Windows.Assets
}
}
[EditorOrder(1), EditorDisplay(null, "LOD"), Limit(0, Model.MaxLODs), VisibleIf("ShowUVs")]
[Tooltip("Level Of Detail index to preview UVs layout.")]
[EditorOrder(1), EditorDisplay(null, "LOD"), Limit(0, Model.MaxLODs, 0.01f), VisibleIf("ShowUVs")]
[Tooltip("Level Of Detail index to preview UVs layout at.")]
public int LOD = 0;
[EditorOrder(2), EditorDisplay(null, "Mesh"), Limit(-1, 1000000), VisibleIf("ShowUVs")]
[Tooltip("Mesh index to preview UVs layout. Use -1 for all meshes")]
[EditorOrder(2), EditorDisplay(null, "Mesh"), Limit(-1, 1000000, 0.01f), VisibleIf("ShowUVs")]
[Tooltip("Mesh index to show UVs layout for. Use -1 to display all UVs of all meshes")]
public int Mesh = -1;
private bool ShowUVs => _uvChannel != UVChannel.None;

View File

@@ -81,6 +81,7 @@ namespace FlaxEditor.Windows.Assets
}
var resolution = group.FloatValue("Resolution Scale", Window.Editor.CodeDocs.GetTooltip(typeof(ModelTool.Options), nameof(ModelImportSettings.Settings.SDFResolution)));
resolution.ValueBox.SlideSpeed = 0.001f;
resolution.ValueBox.MinValue = 0.0001f;
resolution.ValueBox.MaxValue = 100.0f;
resolution.ValueBox.Value = sdf.Texture != null ? sdf.ResolutionScale : 1.0f;

View File

@@ -5,6 +5,7 @@ using System.Collections.Generic;
using System.Linq;
using FlaxEditor.Content;
using FlaxEditor.CustomEditors;
using FlaxEditor.GUI;
using FlaxEditor.Scripting;
using FlaxEditor.Surface;
using FlaxEditor.Viewport.Previews;
@@ -114,6 +115,7 @@ namespace FlaxEditor.Windows.Assets
private readonly PropertiesProxy _properties;
private Tab _previewTab;
private ToolStripButton _showSourceCodeButton;
/// <inheritdoc />
public ParticleEmitterWindow(Editor editor, AssetItem item)
@@ -146,7 +148,8 @@ namespace FlaxEditor.Windows.Assets
// Toolstrip
SurfaceUtils.PerformCommonSetup(this, _toolstrip, _surface, out _saveButton, out _undoButton, out _redoButton);
_toolstrip.AddButton(editor.Icons.Code64, ShowSourceCode).LinkTooltip("Show generated shader source code");
_showSourceCodeButton = _toolstrip.AddButton(editor.Icons.Code64, ShowSourceCode);
_showSourceCodeButton.LinkTooltip("Show generated shader source code");
_toolstrip.AddSeparator();
_toolstrip.AddButton(editor.Icons.Docs64, () => Platform.OpenUrl(Utilities.Constants.DocsUrl + "manual/particles/index.html")).LinkTooltip("See documentation to learn more");
}
@@ -285,5 +288,15 @@ namespace FlaxEditor.Windows.Assets
/// <inheritdoc />
public SearchAssetTypes AssetType => SearchAssetTypes.ParticleEmitter;
/// <inheritdoc />
public override void Update(float deltaTime)
{
base.Update(deltaTime);
if (_asset == null)
return;
_showSourceCodeButton.Enabled = _asset.HasShaderCode;
}
}
}

View File

@@ -97,10 +97,7 @@ namespace FlaxEditor.Windows.Assets
// For single node selected scroll view so user can see it
if (nodes.Count == 1)
{
nodes[0].ExpandAllParents(true);
ScrollViewTo(nodes[0]);
}
ScrollToSelectedNode();
}
// Update properties editor

View File

@@ -318,7 +318,7 @@ namespace FlaxEditor.Windows
private Color _colorWarning;
private Color _colorError;
private bool _colorDebugLogText;
/// <summary>
/// Initializes a new instance of the <see cref="DebugLogWindow"/> class.
/// </summary>
@@ -352,24 +352,12 @@ namespace FlaxEditor.Windows
editor.Options.Apply(editor.Options.Options);
}).SetAutoCheck(true).LinkTooltip("Performs auto pause on error");
toolstrip.AddSeparator();
_groupButtons[0] = (ToolStripButton)toolstrip.AddButton(editor.Icons.Error32, () =>
{
UpdateLogTypeVisibility(LogGroup.Error, _groupButtons[0].Checked);
editor.Options.Options.Interface.DebugLogShowErrorMessages = _groupButtons[0].Checked;
editor.Options.Apply(editor.Options.Options);
}).SetAutoCheck(true).LinkTooltip("Shows/hides error messages");
_groupButtons[1] = (ToolStripButton)toolstrip.AddButton(editor.Icons.Warning32, () =>
{
UpdateLogTypeVisibility(LogGroup.Warning, _groupButtons[1].Checked);
editor.Options.Options.Interface.DebugLogShowWarningMessages = _groupButtons[1].Checked;
editor.Options.Apply(editor.Options.Options);
}).SetAutoCheck(true).LinkTooltip("Shows/hides warning messages");
_groupButtons[2] = (ToolStripButton)toolstrip.AddButton(editor.Icons.Info32, () =>
{
UpdateLogTypeVisibility(LogGroup.Info, _groupButtons[2].Checked);
editor.Options.Options.Interface.DebugLogShowInfoMessages = _groupButtons[2].Checked;
editor.Options.Apply(editor.Options.Options);
}).SetAutoCheck(true).LinkTooltip("Shows/hides info messages");
_groupButtons[0] = (ToolStripButton)toolstrip.AddButton(editor.Icons.Error32, () => { OnGroupButtonPressed(0); })
.SetAutoCheck(true).LinkTooltip("Shows/hides error messages");
_groupButtons[1] = (ToolStripButton)toolstrip.AddButton(editor.Icons.Warning32, () => { OnGroupButtonPressed(1); })
.SetAutoCheck(true).LinkTooltip("Shows/hides warning messages");
_groupButtons[2] = (ToolStripButton)toolstrip.AddButton(editor.Icons.Info32, () => { OnGroupButtonPressed(2); })
.SetAutoCheck(true).LinkTooltip("Shows/hides info messages");
UpdateCount();
// Split panel
@@ -418,6 +406,27 @@ namespace FlaxEditor.Windows
OnEditorOptionsChanged(Editor.Options.Options);
}
private void OnGroupButtonPressed(int index)
{
UpdateLogTypeVisibility((LogGroup)index, _groupButtons[index].Checked);
if (Input.GetKey(KeyboardKeys.Shift))
{
for (int i = 0; i < (int)LogGroup.Max; i++)
{
if (i == index)
continue;
_groupButtons[i].Checked = !_groupButtons[index].Checked;
UpdateLogTypeVisibility((LogGroup)i, _groupButtons[i].Checked);
}
}
var options = Editor.Options.Options.Interface;
options.DebugLogShowErrorMessages = _groupButtons[0].Checked;
options.DebugLogShowWarningMessages = _groupButtons[1].Checked;
options.DebugLogShowInfoMessages = _groupButtons[2].Checked;
Editor.Options.Apply(Editor.Options.Options);
}
private void OnEditorOptionsChanged(EditorOptions options)
{
_timestampsFormats = options.Interface.DebugLogTimestampsFormat;
@@ -455,15 +464,9 @@ namespace FlaxEditor.Windows
// Create new entry
switch (_timestampsFormats)
{
case InterfaceOptions.TimestampsFormats.Utc:
desc.Title = $"[{DateTime.UtcNow}] {desc.Title}";
break;
case InterfaceOptions.TimestampsFormats.LocalTime:
desc.Title = $"[{DateTime.Now}] {desc.Title}";
break;
case InterfaceOptions.TimestampsFormats.TimeSinceStartup:
desc.Title = string.Format("[{0:g}] ", TimeSpan.FromSeconds(Time.TimeSinceStartup)) + desc.Title;
break;
case InterfaceOptions.TimestampsFormats.Utc: desc.Title = $"[{DateTime.UtcNow}] {desc.Title}"; break;
case InterfaceOptions.TimestampsFormats.LocalTime: desc.Title = $"[{DateTime.Now}] {desc.Title}"; break;
case InterfaceOptions.TimestampsFormats.TimeSinceStartup: desc.Title = string.Format("[{0:g}] ", TimeSpan.FromSeconds(Time.TimeSinceStartup)) + desc.Title; break;
}
var newEntry = new LogEntry(this, ref desc);

View File

@@ -219,6 +219,13 @@ namespace FlaxEditor.Windows
{
}
/// <summary>
/// Called when Editor will leave the play mode.
/// </summary>
public virtual void OnPlayEnding()
{
}
/// <summary>
/// Called when Editor leaves the play mode.
/// </summary>

View File

@@ -405,6 +405,7 @@ namespace FlaxEditor.Windows
return;
Editor.Instance.SceneEditing.Delete();
});
InputActions.Add(options => options.FocusConsoleCommand, () => Editor.Instance.Windows.OutputLogWin.FocusCommand());
}
private void ChangeViewportRatio(ViewportScaleOptions v)

View File

@@ -830,6 +830,15 @@ namespace FlaxEditor.Windows
OnOutputTextChanged();
}
/// <summary>
/// Focus the debug command line and ensure that the output log window is visible.
/// </summary>
public void FocusCommand()
{
FocusOrShow();
_commandLineBox.Focus();
}
/// <inheritdoc />
public override void Update(float deltaTime)
{

View File

@@ -33,6 +33,7 @@ namespace FlaxEditor.Windows
private DragScriptItems _dragScriptItems;
private DragHandlers _dragHandlers;
private bool _isDropping = false;
private bool _forceScrollNodeToView = false;
/// <summary>
/// Scene tree panel.
@@ -90,6 +91,15 @@ namespace FlaxEditor.Windows
_tree.SelectedChanged += Tree_OnSelectedChanged;
_tree.RightClick += OnTreeRightClick;
_tree.Parent = _sceneTreePanel;
_tree.AfterDeferredLayout += () =>
{
if (_forceScrollNodeToView)
{
_forceScrollNodeToView = false;
ScrollToSelectedNode();
}
};
headerPanel.Parent = this;
// Setup input actions
@@ -141,6 +151,16 @@ namespace FlaxEditor.Windows
root.TreeNode.UpdateFilter(query);
_tree.UnlockChildrenRecursive();
// When keep the selected nodes in a view
var nodeSelection = _tree.Selection;
if (nodeSelection.Count != 0)
{
var node = nodeSelection[nodeSelection.Count - 1];
node.Expand(true);
_forceScrollNodeToView = true;
}
PerformLayout();
PerformLayout();
}

View File

@@ -42,6 +42,7 @@ namespace FlaxEditor.Windows.Search
if (value == _selectedItem || (value != null && !_matchedItems.Contains(value)))
return;
// Restore the previous selected item to the non-selected color
if (_selectedItem != null)
{
_selectedItem.BackgroundColor = Color.Transparent;
@@ -54,6 +55,7 @@ namespace FlaxEditor.Windows.Search
_selectedItem.BackgroundColor = Style.Current.BackgroundSelected;
if (_matchedItems.Count > VisibleItemCount)
{
_selectedItem.Focus();
_resultPanel.ScrollViewTo(_selectedItem, true);
}
}
@@ -180,39 +182,17 @@ namespace FlaxEditor.Windows.Search
switch (key)
{
case KeyboardKeys.ArrowDown:
{
if (_matchedItems.Count == 0)
return true;
int currentPos;
if (_selectedItem != null)
{
currentPos = _matchedItems.IndexOf(_selectedItem) + 1;
if (currentPos >= _matchedItems.Count)
currentPos--;
}
else
{
currentPos = 0;
}
SelectedItem = _matchedItems[currentPos];
return true;
}
case KeyboardKeys.ArrowUp:
{
if (_matchedItems.Count == 0)
return true;
int currentPos;
if (_selectedItem != null)
{
currentPos = _matchedItems.IndexOf(_selectedItem) - 1;
if (currentPos < 0)
currentPos = 0;
}
else
{
currentPos = 0;
}
SelectedItem = _matchedItems[currentPos];
var focusedIndex = _matchedItems.IndexOf(_selectedItem);
int delta = key == KeyboardKeys.ArrowDown ? -1 : 1;
int nextIndex = Mathf.Wrap(focusedIndex - delta, 0, _matchedItems.Count - 1);
var nextItem = _matchedItems[nextIndex];
SelectedItem = nextItem;
return true;
}
case KeyboardKeys.Return:
@@ -234,6 +214,17 @@ namespace FlaxEditor.Windows.Search
Hide();
return true;
}
case KeyboardKeys.Backspace:
{
// Alow the user to quickly focus the searchbar
if (_searchBox != null && !_searchBox.IsFocused)
{
_searchBox.Focus();
_searchBox.SelectAll();
return true;
}
break;
}
}
return base.OnKeyDown(key);

View File

@@ -9,6 +9,10 @@
#include "Engine/Level/Types.h"
#include "Engine/Debug/Exceptions/JsonParseException.h"
#include "Engine/Profiler/ProfilerCPU.h"
#if USE_EDITOR
#include "Engine/Core/Collections/HashSet.h"
#include "Engine/Core/Collections/Dictionary.h"
#endif
#include <ThirdParty/rapidjson/document.h>
bool JsonStorageProxy::IsValidExtension(const StringView& extension)
@@ -56,27 +60,31 @@ bool JsonStorageProxy::GetAssetInfo(const StringView& path, Guid& resultId, Stri
#if USE_EDITOR
void ChangeIds(rapidjson_flax::Value& obj, rapidjson_flax::Document& document, const StringAnsi& srcId, const StringAnsi& dstId)
void FindObjectIds(const rapidjson_flax::Value& obj, const rapidjson_flax::Document& document, HashSet<Guid>& ids, const char* parentName = nullptr)
{
if (obj.IsObject())
{
for (rapidjson_flax::Value::MemberIterator i = obj.MemberBegin(); i != obj.MemberEnd(); ++i)
for (rapidjson_flax::Value::ConstMemberIterator i = obj.MemberBegin(); i != obj.MemberEnd(); ++i)
{
ChangeIds(i->value, document, srcId, dstId);
FindObjectIds(i->value, document, ids, i->name.GetString());
}
}
else if (obj.IsArray())
{
for (rapidjson::SizeType i = 0; i < obj.Size(); i++)
{
ChangeIds(obj[i], document, srcId, dstId);
FindObjectIds(obj[i], document, ids, parentName);
}
}
else if (obj.IsString())
else if (obj.IsString() && obj.GetStringLength() == 32)
{
if (StringUtils::Compare(srcId.Get(), obj.GetString()) == 0)
if (parentName && StringUtils::Compare(parentName, "ID") == 0)
{
obj.SetString(dstId.Get(), document.GetAllocator());
auto value = JsonTools::GetGuid(obj);
if (value.IsValid())
{
ids.Add(value);
}
}
}
}
@@ -91,9 +99,7 @@ bool JsonStorageProxy::ChangeId(const StringView& path, const Guid& newId)
// Load file
Array<byte> fileData;
if (File::ReadAllBytes(path, fileData))
{
return false;
}
// Parse data
rapidjson_flax::Document document;
@@ -107,33 +113,35 @@ bool JsonStorageProxy::ChangeId(const StringView& path, const Guid& newId)
return false;
}
// Try get asset metadata
// Get all IDs inside the file
HashSet<Guid> ids;
FindObjectIds(document, document, ids);
// Remap into a unique IDs
Dictionary<Guid, Guid> remap;
remap.EnsureCapacity(ids.Count());
for (const auto& id : ids)
remap.Add(id.Item, Guid::New());
// Remap asset ID using the provided value
auto idNode = document.FindMember("ID");
if (idNode == document.MemberEnd())
{
return true;
}
remap[JsonTools::GetGuid(idNode->value)] = newId;
// Change IDs
auto oldIdStr = idNode->value.GetString();
auto newIdStr = newId.ToString(Guid::FormatType::N).ToStringAnsi();
ChangeIds(document, document, oldIdStr, newIdStr);
// Change IDs of asset and objects inside asset
JsonTools::ChangeIds(document, remap);
// Save to file
rapidjson_flax::StringBuffer buffer;
PrettyJsonWriter writer(buffer);
document.Accept(writer.GetWriter());
if (File::WriteAllBytes(path, (byte*)buffer.GetString(), (int32)buffer.GetSize()))
{
return true;
}
return false;
#else
LOG(Warning, "Editing cooked content is invalid.");
return true;
#endif
}

View File

@@ -18,6 +18,7 @@
#include "Engine/Tools/AudioTool/OggVorbisDecoder.h"
#include "Engine/Tools/AudioTool/OggVorbisEncoder.h"
#include "Engine/Serialization/JsonWriters.h"
#include "Engine/Platform/MessageBox.h"
bool ImportAudio::TryGetImportOptions(const StringView& path, Options& options)
{
@@ -118,6 +119,7 @@ CreateAssetResult ImportAudio::Import(CreateAssetContext& context, AudioDecoder&
}
#else
#define HANDLE_VORBIS(chunkIndex, dataPtr, dataSize) \
MessageBox::Show(TEXT("Vorbis format is not supported."), TEXT("Import warning"), MessageBoxButtons::OK, MessageBoxIcon::Warning);
LOG(Warning, "Vorbis format is not supported."); \
return CreateAssetResult::Error;
#endif
@@ -140,6 +142,7 @@ CreateAssetResult ImportAudio::Import(CreateAssetContext& context, AudioDecoder&
break; \
default: \
{ \
MessageBox::Show(TEXT("Unknown audio format."), TEXT("Import warning"), MessageBoxButtons::OK, MessageBoxIcon::Warning); \
LOG(Warning, "Unknown audio format."); \
return CreateAssetResult::Error; \
} \

View File

@@ -697,7 +697,7 @@ public:
--_count;
T* data = _allocation.Get();
if (_count)
data[index] = data[_count];
data[index] = MoveTemp(data[_count]);
Memory::DestructItems(data + _count, 1);
}

View File

@@ -209,8 +209,8 @@ public:
bool Get(const int32 index) const
{
ASSERT(index >= 0 && index < _count);
const ItemType offset = index / sizeof(ItemType);
const ItemType bitMask = (ItemType)(int32)(1 << (index & ((int32)sizeof(ItemType) - 1)));
const ItemType offset = index / 64;
const ItemType bitMask = 1ull << (index & 63ull);
const ItemType item = ((ItemType*)_allocation.Get())[offset];
return (item & bitMask) != 0;
}
@@ -223,13 +223,13 @@ public:
void Set(const int32 index, const bool value)
{
ASSERT(index >= 0 && index < _count);
const ItemType offset = index / sizeof(ItemType);
const ItemType bitMask = (ItemType)(int32)(1 << (index & ((int32)sizeof(ItemType) - 1)));
const ItemType offset = index / 64;
const ItemType bitMask = 1ull << (index & 63ull);
ItemType& item = ((ItemType*)_allocation.Get())[offset];
if (value)
item |= bitMask;
item |= bitMask; // Set the bit
else
item &= ~bitMask; // Clear the bit
item &= ~bitMask; // Unset the bit
}
public:

View File

@@ -26,6 +26,8 @@
_Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"")
#define PRAGMA_ENABLE_DEPRECATION_WARNINGS \
_Pragma("clang diagnostic pop")
#define PRAGMA_DISABLE_OPTIMIZATION
#define PRAGMA_ENABLE_OPTIMIZATION
#pragma clang diagnostic ignored "-Wswitch"
#pragma clang diagnostic ignored "-Wmacro-redefined"
@@ -54,6 +56,8 @@
#define OFFSET_OF(X, Y) __builtin_offsetof(X, Y)
#define PRAGMA_DISABLE_DEPRECATION_WARNINGS
#define PRAGMA_ENABLE_DEPRECATION_WARNINGS
#define PRAGMA_DISABLE_OPTIMIZATION
#define PRAGMA_ENABLE_OPTIMIZATION
#elif defined(_MSC_VER)
@@ -86,6 +90,8 @@
__pragma(warning(disable: 4996))
#define PRAGMA_ENABLE_DEPRECATION_WARNINGS \
__pragma (warning(pop))
#define PRAGMA_DISABLE_OPTIMIZATION __pragma(optimize("", off))
#define PRAGMA_ENABLE_OPTIMIZATION __pragma(optimize("", on))
#pragma warning(disable: 4251)

View File

@@ -12,6 +12,7 @@
#include "Engine/Tools/ModelTool/VertexTriangleAdjacency.h"
#include "Engine/Profiler/ProfilerCPU.h"
#include "Engine/Platform/Platform.h"
#include "Engine/Platform/MessageBox.h"
#define USE_MIKKTSPACE 1
#include "ThirdParty/MikkTSpace/mikktspace.h"
#if USE_ASSIMP
@@ -181,6 +182,7 @@ bool MeshData::GenerateLightmapUVs()
for (int32 i = 0; i < (int32)vb.size(); i++)
lightmapChannel.Get()[i] = *(Float2*)&vb[i].uv;
#else
MessageBox::Show(TEXT("Model lightmap UVs generation is not supported on this platform."), TEXT("Import error"), MessageBoxButtons::OK, MessageBoxIcon::Error);
LOG(Error, "Model lightmap UVs generation is not supported on this platform.");
#endif

View File

@@ -630,6 +630,23 @@ GPUTask* GPUTexture::UploadMipMapAsync(const BytesContainer& data, int32 mipInde
return task;
}
bool GPUTexture::UploadData(TextureData& data, bool copyData)
{
if (!IsAllocated())
return true;
if (data.Width != Width() || data.Height != Height() || data.Depth != Depth() || data.GetArraySize() != ArraySize() || data.Format != Format())
return true;
for (int32 arrayIndex = 0; arrayIndex < ArraySize(); arrayIndex++)
{
for (int32 mipLevel = 0; mipLevel < MipLevels(); mipLevel++)
{
TextureMipData* mip = data.GetData(arrayIndex, mipLevel);
UploadMipMapAsync(mip->Data, mipLevel, mip->RowPitch, mip->DepthPitch, copyData);
}
}
return false;
}
class TextureDownloadDataTask : public ThreadPoolTask
{
private:

View File

@@ -499,7 +499,7 @@ public:
/// <summary>
/// Uploads mip map data to the GPU. Creates async GPU task.
/// </summary>
/// <param name="data">Data to upload (it must be valid for the next a few frames due to GPU latency and async works executing)</param>
/// <param name="data">Data to upload, it must match texture dimensions. It must be valid for the next couple of frames due to GPU async task latency or use data copy.</param>
/// <param name="mipIndex">Mip level index.</param>
/// <param name="copyData">If true, the data will be copied to the async execution task instead of using the input pointer provided.</param>
/// <returns>Created async task or null if cannot.</returns>
@@ -508,7 +508,7 @@ public:
/// <summary>
/// Uploads mip map data to the GPU. Creates async GPU task.
/// </summary>
/// <param name="data">Data to upload (it must be valid for the next a few frames due to GPU latency and async works executing)</param>
/// <param name="data">Data to upload, it must match texture dimensions. It must be valid for the next couple of frames due to GPU async task latency or use data copy.</param>
/// <param name="mipIndex">Mip level index.</param>
/// <param name="rowPitch">The data row pitch.</param>
/// <param name="slicePitch">The data slice pitch.</param>
@@ -516,6 +516,14 @@ public:
/// <returns>Created async task or null if cannot.</returns>
GPUTask* UploadMipMapAsync(const BytesContainer& data, int32 mipIndex, int32 rowPitch, int32 slicePitch, bool copyData = false);
/// <summary>
/// Uploads texture data to the GPU. Actual data copy to the GPU memory is performed via async task.
/// </summary>
/// <param name="data">Data to upload, it must match texture dimensions. It must be valid for the next couple of frames due to GPU async task latency or use data copy.</param>
/// <param name="copyData">If true, the data will be copied to the async execution task instead of using the input pointer provided.</param>
/// <returns>True if cannot upload data, otherwise false.</returns>
API_FUNCTION() bool UploadData(TextureData& data, bool copyData = false);
/// <summary>
/// Downloads the texture data to be accessible from CPU. For frequent access, use staging textures, otherwise current thread will be stalled to wait for the GPU frame to copy data into staging buffer.
/// </summary>

View File

@@ -110,7 +110,7 @@ public:
/// <summary>
/// The animation update delta timescale. Can be used to speed up animation playback or create slow motion effect.
/// </summary>
API_FIELD(Attributes="EditorOrder(45), EditorDisplay(\"Skinned Model\")")
API_FIELD(Attributes="EditorOrder(45), Limit(0, float.MaxValue, 0.025f), EditorDisplay(\"Skinned Model\")")
float UpdateSpeed = 1.0f;
/// <summary>
@@ -122,7 +122,7 @@ public:
/// <summary>
/// The master scale parameter for the actor bounding box. Helps to reduce mesh flickering effect on screen edges.
/// </summary>
API_FIELD(Attributes="EditorOrder(60), DefaultValue(1.5f), Limit(0), EditorDisplay(\"Skinned Model\")")
API_FIELD(Attributes="EditorOrder(60), DefaultValue(1.5f), Limit(0, float.MaxValue, 0.025f), EditorDisplay(\"Skinned Model\")")
float BoundsScale = 1.5f;
/// <summary>

View File

@@ -10,6 +10,7 @@
#include "NavModifierVolume.h"
#include "NavMeshRuntime.h"
#include "Engine/Core/Log.h"
#include "Engine/Core/ScopeExit.h"
#include "Engine/Core/Math/BoundingBox.h"
#include "Engine/Core/Math/Vector3.h"
#include "Engine/Physics/Colliders/BoxCollider.h"
@@ -67,6 +68,11 @@ struct Modifier
NavAreaProperties* NavArea;
};
struct TileId
{
int32 X, Y, Layer;
};
struct NavSceneRasterizer
{
NavMesh* NavMesh;
@@ -197,13 +203,15 @@ struct NavSceneRasterizer
// Transform vertices into world space vertex buffer
vb.Resize(vertexCount);
Float3* vbData = vb.Get();
for (int32 i = 0; i < vertexCount; i++)
vb[i] = sphere.Center + vertices[i] * sphere.Radius;
vbData[i] = sphere.Center + vertices[i] * sphere.Radius;
// Generate index buffer
const int32 stride = horizontalSegments + 1;
int32 indexCount = 0;
ib.Resize(verticalSegments * (horizontalSegments + 1) * 6);
int32* ibData = ib.Get();
for (int32 i = 0; i < verticalSegments; i++)
{
const int32 nextI = i + 1;
@@ -211,13 +219,13 @@ struct NavSceneRasterizer
{
const int32 nextJ = (j + 1) % stride;
ib[indexCount++] = i * stride + j;
ib[indexCount++] = nextI * stride + j;
ib[indexCount++] = i * stride + nextJ;
ibData[indexCount++] = i * stride + j;
ibData[indexCount++] = nextI * stride + j;
ibData[indexCount++] = i * stride + nextJ;
ib[indexCount++] = i * stride + nextJ;
ib[indexCount++] = nextI * stride + j;
ib[indexCount++] = nextI * stride + nextJ;
ibData[indexCount++] = i * stride + nextJ;
ibData[indexCount++] = nextI * stride + j;
ibData[indexCount++] = nextI * stride + nextJ;
}
}
}
@@ -334,54 +342,8 @@ struct NavSceneRasterizer
}
};
// Builds navmesh tile bounds and check if there are any valid navmesh volumes at that tile location
// Returns true if tile is intersecting with any navmesh bounds volume actor - which means tile is in use
bool GetNavMeshTileBounds(Scene* scene, NavMesh* navMesh, int32 x, int32 y, float tileSize, BoundingBox& tileBoundsNavMesh, const Matrix& worldToNavMesh)
{
// Build initial tile bounds (with infinite extent)
tileBoundsNavMesh.Minimum.X = (float)x * tileSize;
tileBoundsNavMesh.Minimum.Y = -NAV_MESH_TILE_MAX_EXTENT;
tileBoundsNavMesh.Minimum.Z = (float)y * tileSize;
tileBoundsNavMesh.Maximum.X = tileBoundsNavMesh.Minimum.X + tileSize;
tileBoundsNavMesh.Maximum.Y = NAV_MESH_TILE_MAX_EXTENT;
tileBoundsNavMesh.Maximum.Z = tileBoundsNavMesh.Minimum.Z + tileSize;
// Check if any navmesh volume intersects with the tile
bool foundAnyVolume = false;
Vector2 rangeY;
for (int32 i = 0; i < scene->Navigation.Volumes.Count(); i++)
{
const auto volume = scene->Navigation.Volumes[i];
if (!volume->AgentsMask.IsNavMeshSupported(navMesh->Properties))
continue;
const auto& volumeBounds = volume->GetBox();
BoundingBox volumeBoundsNavMesh;
BoundingBox::Transform(volumeBounds, worldToNavMesh, volumeBoundsNavMesh);
if (volumeBoundsNavMesh.Intersects(tileBoundsNavMesh))
{
if (foundAnyVolume)
{
rangeY.X = Math::Min(rangeY.X, volumeBoundsNavMesh.Minimum.Y);
rangeY.Y = Math::Max(rangeY.Y, volumeBoundsNavMesh.Maximum.Y);
}
else
{
rangeY.X = volumeBoundsNavMesh.Minimum.Y;
rangeY.Y = volumeBoundsNavMesh.Maximum.Y;
}
foundAnyVolume = true;
}
}
if (foundAnyVolume)
{
// Build proper tile bounds
tileBoundsNavMesh.Minimum.Y = rangeY.X;
tileBoundsNavMesh.Maximum.Y = rangeY.Y;
}
return foundAnyVolume;
}
void CancelNavMeshTileBuildTasks(NavMeshRuntime* runtime);
void CancelNavMeshTileBuildTasks(NavMeshRuntime* runtime, int32 x, int32 y);
void RemoveTile(NavMesh* navMesh, NavMeshRuntime* runtime, int32 x, int32 y, int32 layer)
{
@@ -403,9 +365,10 @@ void RemoveTile(NavMesh* navMesh, NavMeshRuntime* runtime, int32 x, int32 y, int
runtime->RemoveTile(x, y, layer);
}
bool GenerateTile(NavMesh* navMesh, NavMeshRuntime* runtime, int32 x, int32 y, BoundingBox& tileBoundsNavMesh, const Matrix& worldToNavMesh, float tileSize, rcConfig& config)
bool GenerateTile(NavMesh* navMesh, NavMeshRuntime* runtime, int32 x, int32 y, BoundingBox& tileBoundsNavMesh, const Matrix& worldToNavMesh, float tileSize, rcConfig& config, Task* task)
{
rcContext context;
context.enableLog(false);
int32 layer = 0;
// Expand tile bounds by a certain margin
@@ -422,6 +385,7 @@ bool GenerateTile(NavMesh* navMesh, NavMeshRuntime* runtime, int32 x, int32 y, B
LOG(Warning, "Could not generate navmesh: Out of memory for heightfield.");
return true;
}
SCOPE_EXIT{ rcFreeHeightField(heightfield); };
if (!rcCreateHeightfield(&context, *heightfield, config.width, config.height, config.bmin, config.bmax, config.cs, config.ch))
{
LOG(Warning, "Could not generate navmesh: Could not create solid heightfield.");
@@ -462,6 +426,9 @@ bool GenerateTile(NavMesh* navMesh, NavMeshRuntime* runtime, int32 x, int32 y, B
}
}
if (task->IsCancelRequested())
return false;
{
PROFILE_CPU_NAMED("FilterHeightfield");
rcFilterLowHangingWalkableObstacles(&context, config.walkableClimb, *heightfield);
@@ -475,6 +442,7 @@ bool GenerateTile(NavMesh* navMesh, NavMeshRuntime* runtime, int32 x, int32 y, B
LOG(Warning, "Could not generate navmesh: Out of memory compact heightfield.");
return true;
}
SCOPE_EXIT{ rcFreeCompactHeightfield(compactHeightfield); };
{
PROFILE_CPU_NAMED("CompactHeightfield");
if (!rcBuildCompactHeightfield(&context, config.walkableHeight, config.walkableClimb, *heightfield, *compactHeightfield))
@@ -483,7 +451,6 @@ bool GenerateTile(NavMesh* navMesh, NavMeshRuntime* runtime, int32 x, int32 y, B
return true;
}
}
rcFreeHeightField(heightfield);
{
PROFILE_CPU_NAMED("ErodeWalkableArea");
if (!rcErodeWalkableArea(&context, config.walkableRadius, *compactHeightfield))
@@ -505,6 +472,9 @@ bool GenerateTile(NavMesh* navMesh, NavMeshRuntime* runtime, int32 x, int32 y, B
}
}
if (task->IsCancelRequested())
return false;
{
PROFILE_CPU_NAMED("BuildDistanceField");
if (!rcBuildDistanceField(&context, *compactHeightfield))
@@ -528,6 +498,7 @@ bool GenerateTile(NavMesh* navMesh, NavMeshRuntime* runtime, int32 x, int32 y, B
LOG(Warning, "Could not generate navmesh: Out of memory for contour set.");
return true;
}
SCOPE_EXIT{ rcFreeContourSet(contourSet); };
{
PROFILE_CPU_NAMED("BuildContours");
if (!rcBuildContours(&context, *compactHeightfield, config.maxSimplificationError, config.maxEdgeLen, *contourSet))
@@ -543,6 +514,7 @@ bool GenerateTile(NavMesh* navMesh, NavMeshRuntime* runtime, int32 x, int32 y, B
LOG(Warning, "Could not generate navmesh: Out of memory for poly mesh.");
return true;
}
SCOPE_EXIT{ rcFreePolyMesh(polyMesh); };
{
PROFILE_CPU_NAMED("BuildPolyMesh");
if (!rcBuildPolyMesh(&context, *contourSet, config.maxVertsPerPoly, *polyMesh))
@@ -558,6 +530,7 @@ bool GenerateTile(NavMesh* navMesh, NavMeshRuntime* runtime, int32 x, int32 y, B
LOG(Warning, "Could not generate navmesh: Out of memory for detail mesh.");
return true;
}
SCOPE_EXIT{ rcFreePolyMeshDetail(detailMesh); };
{
PROFILE_CPU_NAMED("BuildPolyMeshDetail");
if (!rcBuildPolyMeshDetail(&context, *polyMesh, *compactHeightfield, config.detailSampleDist, config.detailSampleMaxError, *detailMesh))
@@ -567,9 +540,6 @@ bool GenerateTile(NavMesh* navMesh, NavMeshRuntime* runtime, int32 x, int32 y, B
}
}
rcFreeCompactHeightfield(compactHeightfield);
rcFreeContourSet(contourSet);
for (int i = 0; i < polyMesh->npolys; i++)
polyMesh->flags[i] = polyMesh->areas[i] != RC_NULL_AREA ? 1 : 0;
if (polyMesh->nverts == 0)
@@ -646,6 +616,9 @@ bool GenerateTile(NavMesh* navMesh, NavMeshRuntime* runtime, int32 x, int32 y, B
params.offMeshConUserID = offMeshId.Get();
}
if (task->IsCancelRequested())
return false;
// Generate navmesh tile data
unsigned char* navData = nullptr;
int navDataSize = 0;
@@ -659,9 +632,9 @@ bool GenerateTile(NavMesh* navMesh, NavMeshRuntime* runtime, int32 x, int32 y, B
}
ASSERT_LOW_LAYER(navDataSize > 4 && *(uint32*)navData == DT_NAVMESH_MAGIC); // Sanity check for Detour header
if (!task->IsCancelRequested())
{
PROFILE_CPU_NAMED("CreateTiles");
ScopeLock lock(runtime->Locker);
navMesh->IsDataDirty = true;
@@ -761,7 +734,7 @@ public:
const auto navMesh = NavMesh.Get();
if (!navMesh)
return false;
if (GenerateTile(NavMesh, Runtime, X, Y, TileBoundsNavMesh, WorldToNavMesh, TileSize, Config))
if (GenerateTile(NavMesh, Runtime, X, Y, TileBoundsNavMesh, WorldToNavMesh, TileSize, Config, this))
{
LOG(Warning, "Failed to generate navmesh tile at {0}x{1}.", X, Y);
}
@@ -778,6 +751,50 @@ public:
}
};
void CancelNavMeshTileBuildTasks(NavMeshRuntime* runtime)
{
NavBuildTasksLocker.Lock();
for (int32 i = 0; i < NavBuildTasks.Count(); i++)
{
auto task = NavBuildTasks[i];
if (task->Runtime == runtime)
{
NavBuildTasksLocker.Unlock();
// Cancel task but without locking queue from this thread to prevent deadlocks
task->Cancel();
NavBuildTasksLocker.Lock();
i--;
if (NavBuildTasks.IsEmpty())
break;
}
}
NavBuildTasksLocker.Unlock();
}
void CancelNavMeshTileBuildTasks(NavMeshRuntime* runtime, int32 x, int32 y)
{
NavBuildTasksLocker.Lock();
for (int32 i = 0; i < NavBuildTasks.Count(); i++)
{
auto task = NavBuildTasks[i];
if (task->Runtime == runtime && task->X == x && task->Y == y)
{
NavBuildTasksLocker.Unlock();
// Cancel task but without locking queue from this thread to prevent deadlocks
task->Cancel();
NavBuildTasksLocker.Lock();
i--;
if (NavBuildTasks.IsEmpty())
break;
}
}
NavBuildTasksLocker.Unlock();
}
void OnSceneUnloading(Scene* scene, const Guid& sceneId)
{
// Cancel pending build requests
@@ -842,14 +859,15 @@ float NavMeshBuilder::GetNavMeshBuildingProgress()
void BuildTileAsync(NavMesh* navMesh, const int32 x, const int32 y, const rcConfig& config, const BoundingBox& tileBoundsNavMesh, const Matrix& worldToNavMesh, float tileSize)
{
PROFILE_CPU();
NavMeshRuntime* runtime = navMesh->GetRuntime();
NavBuildTasksLocker.Lock();
// Skip if this tile is already during cooking
for (int32 i = 0; i < NavBuildTasks.Count(); i++)
{
const auto task = NavBuildTasks[i];
if (task->X == x && task->Y == y && task->Runtime == runtime)
const auto task = NavBuildTasks.Get()[i];
if (task->GetState() == TaskState::Queued && task->X == x && task->Y == y && task->Runtime == runtime)
{
NavBuildTasksLocker.Unlock();
return;
@@ -898,11 +916,16 @@ void BuildDirtyBounds(Scene* scene, NavMesh* navMesh, const BoundingBox& dirtyBo
{
PROFILE_CPU_NAMED("Prepare");
runtime->Locker.Lock();
// Prepare scene data and navmesh
rebuild |= Math::NotNearEqual(navMesh->Data.TileSize, tileSize);
if (rebuild)
{
runtime->Locker.Unlock();
CancelNavMeshTileBuildTasks(runtime);
runtime->Locker.Lock();
// Remove all tiles from navmesh runtime
runtime->RemoveTiles(navMesh);
runtime->SetTileSize(tileSize);
@@ -917,9 +940,10 @@ void BuildDirtyBounds(Scene* scene, NavMesh* navMesh, const BoundingBox& dirtyBo
else
{
// Ensure to have enough memory for tiles
runtime->SetTileSize(tileSize);
runtime->EnsureCapacity(tilesX * tilesY);
}
runtime->Locker.Unlock();
}
// Initialize nav mesh configuration
@@ -930,21 +954,93 @@ void BuildDirtyBounds(Scene* scene, NavMesh* navMesh, const BoundingBox& dirtyBo
{
PROFILE_CPU_NAMED("StartBuildingTiles");
// Cache navmesh volumes
Array<BoundingBox, InlinedAllocation<8>> volumes;
for (int32 i = 0; i < scene->Navigation.Volumes.Count(); i++)
{
const auto volume = scene->Navigation.Volumes.Get()[i];
if (!volume->AgentsMask.IsNavMeshSupported(navMesh->Properties) ||
!volume->GetBox().Intersects(dirtyBoundsAligned))
continue;
auto& bounds = volumes.AddOne();
BoundingBox::Transform(volume->GetBox(), worldToNavMesh, bounds);
}
Array<TileId> unusedTiles;
Array<Pair<TileId, BoundingBox>> usedTiles;
for (int32 y = tilesMin.Z; y < tilesMax.Z; y++)
{
for (int32 x = tilesMin.X; x < tilesMax.X; x++)
{
// Build initial tile bounds (with infinite extent)
BoundingBox tileBoundsNavMesh;
if (GetNavMeshTileBounds(scene, navMesh, x, y, tileSize, tileBoundsNavMesh, worldToNavMesh))
tileBoundsNavMesh.Minimum.X = (float)x * tileSize;
tileBoundsNavMesh.Minimum.Y = -NAV_MESH_TILE_MAX_EXTENT;
tileBoundsNavMesh.Minimum.Z = (float)y * tileSize;
tileBoundsNavMesh.Maximum.X = tileBoundsNavMesh.Minimum.X + tileSize;
tileBoundsNavMesh.Maximum.Y = NAV_MESH_TILE_MAX_EXTENT;
tileBoundsNavMesh.Maximum.Z = tileBoundsNavMesh.Minimum.Z + tileSize;
// Check if any navmesh volume intersects with the tile
bool foundAnyVolume = false;
Vector2 rangeY;
for (const auto& bounds : volumes)
{
BuildTileAsync(navMesh, x, y, config, tileBoundsNavMesh, worldToNavMesh, tileSize);
if (bounds.Intersects(tileBoundsNavMesh))
{
if (foundAnyVolume)
{
rangeY.X = Math::Min(rangeY.X, bounds.Minimum.Y);
rangeY.Y = Math::Max(rangeY.Y, bounds.Maximum.Y);
}
else
{
rangeY.X = bounds.Minimum.Y;
rangeY.Y = bounds.Maximum.Y;
foundAnyVolume = true;
}
}
}
// Check if tile is intersecting with any navmesh bounds volume actor - which means tile is in use
if (foundAnyVolume)
{
// Setup proper tile bounds
tileBoundsNavMesh.Minimum.Y = rangeY.X;
tileBoundsNavMesh.Maximum.Y = rangeY.Y;
usedTiles.Add({ { x, y, 0 }, tileBoundsNavMesh });
}
else
{
RemoveTile(navMesh, runtime, x, y, 0);
unusedTiles.Add({ x, y, 0 });
}
}
}
// Remove unused tiles
{
PROFILE_CPU_NAMED("RemoveUnused");
for (const auto& tile : unusedTiles)
{
// Wait for any async tasks that are producing this tile
CancelNavMeshTileBuildTasks(runtime, tile.X, tile.Y);
}
runtime->Locker.Lock();
for (const auto& tile : unusedTiles)
{
RemoveTile(navMesh, runtime, tile.X, tile.Y, 0);
}
runtime->Locker.Unlock();
}
// Build used tiles
{
PROFILE_CPU_NAMED("AddNew");
for (const auto& e : usedTiles)
{
BuildTileAsync(navMesh, e.First.X, e.First.Y, config, e.Second, worldToNavMesh, tileSize);
}
}
}
}
@@ -1024,7 +1120,7 @@ void BuildDirtyBounds(Scene* scene, const BoundingBox& dirtyBounds, bool rebuild
NavBuildTasksLocker.Lock();
for (int32 i = 0; i < NavBuildTasks.Count(); i++)
{
if (NavBuildTasks[i]->NavMesh == navMesh)
if (NavBuildTasks.Get()[i]->NavMesh == navMesh)
usageCount++;
}
NavBuildTasksLocker.Unlock();
@@ -1063,7 +1159,7 @@ void NavMeshBuilder::Update()
const auto now = DateTime::NowUTC();
for (int32 i = 0; NavBuildQueue.HasItems() && i < NavBuildQueue.Count(); i++)
{
auto req = NavBuildQueue[i];
auto req = NavBuildQueue.Get()[i];
if (now - req.Time >= 0)
{
NavBuildQueue.RemoveAt(i--);
@@ -1117,7 +1213,7 @@ void NavMeshBuilder::Build(Scene* scene, float timeoutMs)
for (int32 i = 0; i < NavBuildQueue.Count(); i++)
{
auto& e = NavBuildQueue[i];
auto& e = NavBuildQueue.Get()[i];
if (e.Scene == scene && e.DirtyBounds == req.DirtyBounds)
{
e = req;

View File

@@ -15,6 +15,19 @@
#define USE_DATA_LINK 0
#define USE_NAV_MESH_ALLOC 0
#if USE_NAV_MESH_ALLOC
#define GET_NAV_TILE_DATA(tile) \
const int32 dataSize = (tile).Data.Length(); \
const auto flags = DT_TILE_FREE_DATA; \
const auto data = (byte*)dtAlloc(dataSize, DT_ALLOC_PERM); \
Platform::MemoryCopy(data, (tile).Data.Get(), dataSize)
#else
#define GET_NAV_TILE_DATA(tile) \
const int32 dataSize = (tile).Data.Length(); \
const auto flags = 0; \
const auto data = (tile).Data.Get()
#endif
namespace
{
FORCE_INLINE void InitFilter(dtQueryFilter& filter)
@@ -353,15 +366,7 @@ void NavMeshRuntime::EnsureCapacity(int32 tilesToAddCount)
// Restore previous tiles
for (auto& tile : _tiles)
{
const int32 dataSize = tile.Data.Length();
#if USE_NAV_MESH_ALLOC
const auto flags = DT_TILE_FREE_DATA;
const auto data = (byte*)dtAlloc(dataSize, DT_ALLOC_PERM);
Platform::MemoryCopy(data, tile.Data.Get(), dataSize);
#else
const auto flags = 0;
const auto data = tile.Data.Get();
#endif
GET_NAV_TILE_DATA(tile);
const auto result = _navMesh->addTile(data, dataSize, flags, 0, nullptr);
if (dtStatusFailed(result))
{
@@ -661,15 +666,7 @@ void NavMeshRuntime::AddTileInternal(NavMesh* navMesh, NavMeshTileData& tileData
#endif
// Add tile to navmesh
const int32 dataSize = tile->Data.Length();
#if USE_NAV_MESH_ALLOC
const auto flags = DT_TILE_FREE_DATA;
const auto data = (byte*)dtAlloc(dataSize, DT_ALLOC_PERM);
Platform::MemoryCopy(data, tile->Data.Get(), dataSize);
#else
const auto flags = 0;
const auto data = tile->Data.Get();
#endif
GET_NAV_TILE_DATA(*tile);
const auto result = _navMesh->addTile(data, dataSize, flags, 0, nullptr);
if (dtStatusFailed(result))
{

View File

@@ -440,4 +440,18 @@ bool ParticleEmitter::Save(const StringView& path)
return SaveSurface(data);
}
bool ParticleEmitter::HasShaderCode() const
{
if (SimulationMode != ParticlesSimulationMode::GPU)
return false;
#if COMPILE_WITH_PARTICLE_GPU_GRAPH && COMPILE_WITH_SHADER_COMPILER
if (_shaderHeader.ParticleEmitter.GraphVersion == PARTICLE_GPU_GRAPH_VERSION
&& HasChunk(SHADER_FILE_CHUNK_SOURCE)
&& !HasDependenciesModified())
return true;
#endif
return false;
}
#endif

View File

@@ -173,6 +173,11 @@ public:
#if USE_EDITOR
void GetReferences(Array<Guid>& assets, Array<String>& files) const override;
bool Save(const StringView& path = StringView::Empty) override;
/// <summary>
/// Checks if the particle emitter has valid shader code present.
/// </summary>
API_PROPERTY() bool HasShaderCode() const;
#endif
protected:

View File

@@ -162,7 +162,7 @@ void BoxCollider::UpdateBounds()
void BoxCollider::GetGeometry(CollisionShape& collision)
{
Float3 size = _size * _cachedScale;
Float3 size = _size * _transform.Scale;
const float minSize = 0.001f;
size = Float3::Max(size.GetAbsolute() * 0.5f, Float3(minSize));
collision.SetBox(size.Raw);

View File

@@ -43,10 +43,9 @@ void CapsuleCollider::DrawPhysicsDebug(RenderView& view)
return;
Quaternion rotation;
Quaternion::Multiply(_transform.Orientation, Quaternion::Euler(0, 90, 0), rotation);
const float scaling = _cachedScale.GetAbsolute().MaxValue();
const float minSize = 0.001f;
const float radius = Math::Max(Math::Abs(_radius) * scaling, minSize);
const float height = Math::Max(Math::Abs(_height) * scaling, minSize);
const float radius = Math::Max(Math::Abs(_radius) * _cachedScale, minSize);
const float height = Math::Max(Math::Abs(_height) * _cachedScale, minSize);
if (view.Mode == ViewMode::PhysicsColliders && !GetIsTrigger())
DEBUG_DRAW_CAPSULE(_transform.LocalToWorld(_center), rotation, radius, height, _staticActor ? Color::CornflowerBlue : Color::Orchid, 0, true);
else
@@ -57,10 +56,9 @@ void CapsuleCollider::OnDebugDrawSelected()
{
Quaternion rotation;
Quaternion::Multiply(_transform.Orientation, Quaternion::Euler(0, 90, 0), rotation);
const float scaling = _cachedScale.GetAbsolute().MaxValue();
const float minSize = 0.001f;
const float radius = Math::Max(Math::Abs(_radius) * scaling, minSize);
const float height = Math::Max(Math::Abs(_height) * scaling, minSize);
const float radius = Math::Max(Math::Abs(_radius) * _cachedScale, minSize);
const float height = Math::Max(Math::Abs(_height) * _cachedScale, minSize);
const Vector3 position = _transform.LocalToWorld(_center);
DEBUG_DRAW_WIRE_CAPSULE(position, rotation, radius, height, Color::GreenYellow, 0, false);
@@ -92,9 +90,8 @@ void CapsuleCollider::UpdateBounds()
void CapsuleCollider::GetGeometry(CollisionShape& collision)
{
const float scaling = _cachedScale.GetAbsolute().MaxValue();
const float minSize = 0.001f;
const float radius = Math::Max(Math::Abs(_radius) * scaling, minSize);
const float height = Math::Max(Math::Abs(_height) * scaling, minSize);
const float radius = Math::Max(Math::Abs(_radius) * _cachedScale, minSize);
const float height = Math::Max(Math::Abs(_height) * _cachedScale, minSize);
collision.SetCapsule(radius, height * 0.5f);
}

View File

@@ -21,6 +21,7 @@ CharacterController::CharacterController(const SpawnParams& params)
, _upDirection(Vector3::Up)
, _gravityDisplacement(Vector3::Zero)
, _nonWalkableMode(NonWalkableModes::PreventClimbing)
, _originMode(OriginModes::CapsuleCenter)
, _lastFlags(CollisionFlags::None)
{
_contactOffset = 10.0f;
@@ -35,9 +36,7 @@ void CharacterController::SetRadius(const float value)
{
if (value == _radius)
return;
_radius = value;
UpdateSize();
UpdateBounds();
}
@@ -51,9 +50,7 @@ void CharacterController::SetHeight(const float value)
{
if (value == _height)
return;
_height = value;
UpdateSize();
UpdateBounds();
}
@@ -87,6 +84,23 @@ void CharacterController::SetNonWalkableMode(NonWalkableModes value)
PhysicsBackend::SetControllerNonWalkableMode(_controller, (int32)value);
}
CharacterController::OriginModes CharacterController::GetOriginMode() const
{
return _originMode;
}
void CharacterController::SetOriginMode(OriginModes value)
{
if (_originMode == value)
return;
_originMode = value;
if (_controller)
{
DeleteController();
CreateController();
}
}
float CharacterController::GetStepOffset() const
{
return _stepOffset;
@@ -96,15 +110,11 @@ void CharacterController::SetStepOffset(float value)
{
if (value == _stepOffset)
return;
_stepOffset = value;
if (_controller)
{
const float scaling = _cachedScale.GetAbsolute().MaxValue();
const float contactOffset = Math::Max(_contactOffset, ZeroTolerance);
const float height = Math::Max(Math::Abs(_height) * scaling, CC_MIN_SIZE);
const float radius = Math::Max(Math::Abs(_radius) * scaling - contactOffset, CC_MIN_SIZE);
float height, radius;
GetControllerSize(height, radius);
PhysicsBackend::SetControllerStepOffset(_controller, Math::Min(value, height + radius * 2.0f - CC_MIN_SIZE));
}
}
@@ -169,17 +179,69 @@ CharacterController::CollisionFlags CharacterController::SimpleMove(const Vector
CharacterController::CollisionFlags CharacterController::Move(const Vector3& displacement)
{
CollisionFlags result = CollisionFlags::None;
if (_controller)
if (_controller && !_isUpdatingTransform)
{
// Perform move
const float deltaTime = Time::GetCurrentSafe()->DeltaTime.GetTotalSeconds();
result = (CollisionFlags)PhysicsBackend::MoveController(_controller, _shape, displacement, _minMoveDistance, deltaTime);
_lastFlags = result;
Vector3 position = PhysicsBackend::GetControllerPosition(_controller) - _center;
// Update position
Vector3 position;
if (_originMode == OriginModes::Base)
position = PhysicsBackend::GetControllerBasePosition(_controller);
else
position = PhysicsBackend::GetControllerPosition(_controller);
position -= _center;
_isUpdatingTransform = true;
SetPosition(position);
_isUpdatingTransform = false;
}
return result;
}
void CharacterController::Resize(float height, float radius)
{
const float heightDiff = height - _height;
const float radiusDiff = radius - _radius;
if (Math::IsZero(heightDiff) && Math::IsZero(radiusDiff))
return;
_height = height;
_radius = radius;
if (_controller)
{
float centerDiff = heightDiff * 0.5f + radiusDiff;
// Change physics size
GetControllerSize(height, radius);
PhysicsBackend::SetControllerSize(_controller, radius, height);
Vector3 positionDelta = _upDirection * centerDiff;
// Change physics position to maintain feet placement (base)
Vector3 position;
switch (_originMode)
{
case OriginModes::CapsuleCenter:
position = PhysicsBackend::GetControllerPosition(_controller);
position += positionDelta;
_center += positionDelta;
PhysicsBackend::SetControllerPosition(_controller, position);
break;
case OriginModes::Base:
position = PhysicsBackend::GetControllerBasePosition(_controller);
position += positionDelta;
PhysicsBackend::SetControllerBasePosition(_controller, position);
break;
}
// Change actor position
_isUpdatingTransform = true;
SetPosition(position - _center);
_isUpdatingTransform = false;
}
UpdateBounds();
}
#if USE_EDITOR
#include "Engine/Debug/DebugDraw.h"
@@ -187,23 +249,38 @@ CharacterController::CollisionFlags CharacterController::Move(const Vector3& dis
void CharacterController::DrawPhysicsDebug(RenderView& view)
{
const float scaling = _cachedScale.GetAbsolute().MaxValue();
const float radius = Math::Max(Math::Abs(_radius) * scaling, CC_MIN_SIZE);
const float height = Math::Max(Math::Abs(_height) * scaling, CC_MIN_SIZE);
const Vector3 position = _transform.LocalToWorld(_center);
Quaternion rotation = Quaternion::Euler(90, 0, 0);
const Vector3 position = GetControllerPosition();
if (view.Mode == ViewMode::PhysicsColliders)
DEBUG_DRAW_CAPSULE(position, Quaternion::Euler(90, 0, 0), radius, height, Color::LightYellow, 0, true);
DEBUG_DRAW_CAPSULE(position, rotation, _radius, _height, Color::LightYellow, 0, true);
else
DEBUG_DRAW_WIRE_CAPSULE(position, Quaternion::Euler(90, 0, 0), radius, height, Color::GreenYellow * 0.8f, 0, true);
DEBUG_DRAW_WIRE_CAPSULE(position, rotation, _radius, _height, Color::GreenYellow * 0.8f, 0, true);
}
void CharacterController::OnDebugDrawSelected()
{
const float scaling = _cachedScale.GetAbsolute().MaxValue();
const float radius = Math::Max(Math::Abs(_radius) * scaling, CC_MIN_SIZE);
const float height = Math::Max(Math::Abs(_height) * scaling, CC_MIN_SIZE);
const Vector3 position = _transform.LocalToWorld(_center);
DEBUG_DRAW_WIRE_CAPSULE(position, Quaternion::Euler(90, 0, 0), radius, height, Color::GreenYellow, 0, false);
Quaternion rotation = Quaternion::Euler(90, 0, 0);
const Vector3 position = GetControllerPosition();
DEBUG_DRAW_WIRE_CAPSULE(position, rotation, _radius, _height, Color::GreenYellow, 0, false);
if (_controller)
{
// Physics backend capsule shape
float height, radius;
GetControllerSize(height, radius);
Vector3 pos = PhysicsBackend::GetControllerPosition(_controller);
DEBUG_DRAW_WIRE_CAPSULE(pos, rotation, radius, height, Color::Blue.AlphaMultiplied(0.2f), 0, false);
#if 0
// More technical visuals debugging
Vector3 base = PhysicsBackend::GetControllerBasePosition(_controller);
DEBUG_DRAW_WIRE_SPHERE(BoundingSphere(base, 5.0f), Color::Red, 0, false);
DEBUG_DRAW_WIRE_SPHERE(BoundingSphere(pos, 4.0f), Color::Red, 0, false);
DEBUG_DRAW_WIRE_SPHERE(BoundingSphere(pos + Vector3(0, height * 0.5f, 0), 2.0f), Color::Red, 0, false);
DEBUG_DRAW_WIRE_SPHERE(BoundingSphere(pos - Vector3(0, height * 0.5f, 0), 2.0f), Color::Red, 0, false);
DEBUG_DRAW_WIRE_SPHERE(BoundingSphere(pos + Vector3(0, height * 0.5f, 0), radius), Color::Red.AlphaMultiplied(0.5f), 0, false);
DEBUG_DRAW_WIRE_SPHERE(BoundingSphere(pos - Vector3(0, height * 0.5f, 0), radius), Color::Red.AlphaMultiplied(0.5f), 0, false);
DEBUG_DRAW_WIRE_CYLINDER(pos, Quaternion::Identity, radius, height, Color::Red.AlphaMultiplied(0.2f), 0, false);
#endif
}
// Base
Collider::OnDebugDrawSelected();
@@ -215,10 +292,14 @@ void CharacterController::CreateController()
{
// Create controller
ASSERT(_controller == nullptr && _shape == nullptr);
_cachedScale = GetScale();
const float scaling = _cachedScale.GetAbsolute().MaxValue();
const Vector3 position = _transform.LocalToWorld(_center);
_controller = PhysicsBackend::CreateController(GetPhysicsScene()->GetPhysicsScene(), this, this, _contactOffset, position, _slopeLimit, (int32)_nonWalkableMode, Material, Math::Abs(_radius) * scaling, Math::Abs(_height) * scaling, _stepOffset, _shape);
_cachedScale = GetScale().GetAbsolute().MaxValue();
float height, radius;
GetControllerSize(height, radius);
Vector3 position = _center;
if (_originMode == OriginModes::Base)
position += _upDirection * (_height * 0.5f + _radius);
position = _transform.LocalToWorld(position);
_controller = PhysicsBackend::CreateController(GetPhysicsScene()->GetPhysicsScene(), this, this, _contactOffset, position, _slopeLimit, (int32)_nonWalkableMode, Material, radius, height, _stepOffset, _shape);
// Setup
PhysicsBackend::SetControllerUpDirection(_controller, _upDirection);
@@ -241,13 +322,35 @@ void CharacterController::UpdateSize() const
{
if (_controller)
{
const float scaling = _cachedScale.GetAbsolute().MaxValue();
const float radius = Math::Max(Math::Abs(_radius) * scaling - Math::Max(_contactOffset, ZeroTolerance), CC_MIN_SIZE);
const float height = Math::Max(Math::Abs(_height) * scaling, CC_MIN_SIZE);
float height, radius;
GetControllerSize(height, radius);
PhysicsBackend::SetControllerSize(_controller, radius, height);
}
}
Vector3 CharacterController::GetControllerPosition() const
{
Vector3 position = _center;
if (_originMode == OriginModes::Base)
position += _upDirection * (_height * 0.5f + _radius);
position = _transform.LocalToWorld(position);
return position;
}
void CharacterController::GetControllerSize(float& height, float& radius) const
{
// Use absolute values including scale
height = Math::Abs(_height) * _cachedScale;
radius = Math::Abs(_radius) * _cachedScale;
// Exclude contact offset around the capsule (otherwise character floats in the air)
radius = radius - Math::Max(_contactOffset, 0.0f);
// Prevent too small controllers
height = Math::Max(height, CC_MIN_SIZE);
radius = Math::Max(radius, CC_MIN_SIZE);
}
void CharacterController::CreateShape()
{
// Not used
@@ -255,10 +358,10 @@ void CharacterController::CreateShape()
void CharacterController::UpdateBounds()
{
const float scaling = GetScale().GetAbsolute().MaxValue();
const float radius = Math::Max(Math::Abs(_radius) * scaling, CC_MIN_SIZE);
const float height = Math::Max(Math::Abs(_height) * scaling, CC_MIN_SIZE);
const Vector3 position = _transform.LocalToWorld(_center);
_cachedScale = GetScale().GetAbsolute().MaxValue();
float height, radius;
GetControllerSize(height, radius);
const Vector3 position = GetControllerPosition();
const Vector3 extent(radius, height * 0.5f + radius, radius);
_box = BoundingBox(position - extent, position + extent);
BoundingSphere::FromBox(_box, _sphere);
@@ -292,6 +395,21 @@ RigidBody* CharacterController::GetAttachedRigidBody() const
return nullptr;
}
void CharacterController::SetCenter(const Vector3& value)
{
if (value == _center)
return;
Vector3 delta = value - _center;
_center = value;
if (_controller)
{
// Change physics position while maintaining actor placement
Vector3 position = PhysicsBackend::GetControllerPosition(_controller);
position += _upDirection * delta;
PhysicsBackend::SetControllerPosition(_controller, position);
}
}
void CharacterController::OnActiveTransformChanged()
{
if (!_shape)
@@ -300,7 +418,12 @@ void CharacterController::OnActiveTransformChanged()
// Change actor transform (but with locking)
ASSERT(!_isUpdatingTransform);
_isUpdatingTransform = true;
const Vector3 position = PhysicsBackend::GetControllerPosition(_controller) - _center;
Vector3 position;
if (_originMode == OriginModes::Base)
position = PhysicsBackend::GetControllerBasePosition(_controller);
else
position = PhysicsBackend::GetControllerPosition(_controller);
position -= _center;
SetPosition(position);
_isUpdatingTransform = false;
@@ -319,7 +442,7 @@ void CharacterController::UpdateGeometry()
return;
// Setup shape geometry
_cachedScale = GetScale();
_cachedScale = GetScale().GetAbsolute().MaxValue();
UpdateSize();
}
@@ -382,8 +505,11 @@ void CharacterController::OnTransformChanged()
const Vector3 position = _transform.LocalToWorld(_center);
if (!_isUpdatingTransform && _controller)
{
PhysicsBackend::SetControllerPosition(_controller, position);
const Float3 scale = GetScale();
if (_originMode == OriginModes::Base)
PhysicsBackend::SetControllerBasePosition(_controller, position);
else
PhysicsBackend::SetControllerPosition(_controller, position);
const float scale = GetScale().GetAbsolute().MaxValue();
if (_cachedScale != scale)
UpdateGeometry();
UpdateBounds();

View File

@@ -41,6 +41,22 @@ public:
Below = 1 << 2,
};
/// <summary>
/// Specifies how a character controller capsule placement.
/// </summary>
API_ENUM() enum class OriginModes
{
/// <summary>
/// Character origin starts at capsule center (including Center offset properly).
/// </summary>
CapsuleCenter,
/// <summary>
/// Character origin starts at capsule base position aka character feet placement.
/// </summary>
Base,
};
/// <summary>
/// Specifies how a character controller interacts with non-walkable parts.
/// </summary>
@@ -69,6 +85,7 @@ private:
Vector3 _upDirection;
Vector3 _gravityDisplacement;
NonWalkableModes _nonWalkableMode;
OriginModes _originMode;
CollisionFlags _lastFlags;
public:
@@ -84,13 +101,13 @@ public:
API_PROPERTY() void SetRadius(float value);
/// <summary>
/// Gets the height of the capsule, measured in the object's local space. The capsule height will be scaled by the actor's world scale.
/// Gets the height of the capsule as a distance between the two sphere centers at the end of the capsule. The capsule height is measured in the object's local space and will be scaled by the actor's world scale.
/// </summary>
API_PROPERTY(Attributes="EditorOrder(110), DefaultValue(150.0f), EditorDisplay(\"Collider\"), ValueCategory(Utils.ValueCategory.Distance)")
float GetHeight() const;
/// <summary>
/// Sets the height of the capsule, measured in the object's local space. The capsule height will be scaled by the actor's world scale.
/// Sets the height of the capsule as a distance between the two sphere centers at the end of the capsule. The capsule height is measured in the object's local space and will be scaled by the actor's world scale.
/// </summary>
API_PROPERTY() void SetHeight(float value);
@@ -116,6 +133,17 @@ public:
/// </summary>
API_PROPERTY() void SetNonWalkableMode(NonWalkableModes value);
/// <summary>
/// Gets the position origin placement mode.
/// </summary>
API_PROPERTY(Attributes="EditorOrder(216), DefaultValue(OriginModes.CapsuleCenter), EditorDisplay(\"Character Controller\")")
OriginModes GetOriginMode() const;
/// <summary>
/// Sets the position origin placement mode.
/// </summary>
API_PROPERTY() void SetOriginMode(OriginModes value);
/// <summary>
/// Gets the step height. The character will step up a stair only if it is closer to the ground than the indicated value. This should not be greater than the Character Controllers height or it will generate an error.
/// </summary>
@@ -194,6 +222,13 @@ public:
/// <returns>The collision flags. It can be used to trigger various character animations.</returns>
API_FUNCTION() CollisionFlags Move(const Vector3& displacement);
/// <summary>
/// Updates the character height and center position to ensure its feet position stays the same. This can be used to implement a 'crouch' functionality for example. Maintains the same actor position to stay in the middle of capsule by adjusting center of collider accordingly to height difference.
/// </summary>
/// <param name="height">The height of the capsule, measured in the object's local space.</param>
/// <param name="radius">The radius of the capsule, measured in the object's local space.</param>
API_FUNCTION() void Resize(float height, float radius);
protected:
/// <summary>
/// Creates the physics actor.
@@ -210,6 +245,10 @@ protected:
/// </summary>
void UpdateSize() const;
private:
Vector3 GetControllerPosition() const;
void GetControllerSize(float& height, float& radius) const;
public:
// [Collider]
#if USE_EDITOR
@@ -220,6 +259,7 @@ public:
void AddMovement(const Vector3& translation, const Quaternion& rotation) override;
bool CanAttach(RigidBody* rigidBody) const override;
RigidBody* GetAttachedRigidBody() const override;
void SetCenter(const Vector3& value) override;
// [IPhysicsActor]
void OnActiveTransformChanged() override;

View File

@@ -205,7 +205,7 @@ void Collider::CreateShape()
ASSERT(_shape == nullptr);
// Setup shape geometry
_cachedScale = GetScale();
_cachedScale = GetScale().GetAbsolute().MaxValue();
CollisionShape shape;
GetGeometry(shape);
@@ -222,7 +222,7 @@ void Collider::UpdateGeometry()
return;
// Setup shape geometry
_cachedScale = GetScale();
_cachedScale = GetScale().GetAbsolute().MaxValue();
CollisionShape shape;
GetGeometry(shape);
@@ -427,7 +427,7 @@ void Collider::OnTransformChanged()
}
}
const Float3 scale = GetScale();
const float scale = GetScale().GetAbsolute().MaxValue();
if (_cachedScale != scale)
UpdateGeometry();
UpdateBounds();

View File

@@ -24,7 +24,7 @@ protected:
bool _isTrigger;
void* _shape;
void* _staticActor;
Float3 _cachedScale;
float _cachedScale;
float _contactOffset;
Vector3 _cachedLocalPosePos;
Quaternion _cachedLocalPoseRot;
@@ -61,7 +61,7 @@ public:
/// <summary>
/// Sets the center of the collider, measured in the object's local space.
/// </summary>
API_PROPERTY() void SetCenter(const Vector3& value);
API_PROPERTY() virtual void SetCenter(const Vector3& value);
/// <summary>
/// Gets the contact offset. Colliders whose distance is less than the sum of their ContactOffset values will generate contacts. The contact offset must be positive. Contact offset allows the collision detection system to predictively enforce the contact constraint even when the objects are slightly separated.

View File

@@ -131,7 +131,7 @@ void MeshCollider::UpdateBounds()
void MeshCollider::GetGeometry(CollisionShape& collision)
{
// Prepare scale
Float3 scale = _cachedScale;
Float3 scale = _transform.Scale;
const float minSize = 0.001f;
Float3 scaleAbs = scale.GetAbsolute();
if (scaleAbs.X < minSize)

View File

@@ -67,8 +67,7 @@ void SphereCollider::UpdateBounds()
void SphereCollider::GetGeometry(CollisionShape& collision)
{
const float scaling = _cachedScale.GetAbsolute().MaxValue();
const float radius = Math::Abs(_radius) * scaling;
const float radius = Math::Abs(_radius) * _cachedScale;
const float minSize = 0.001f;
collision.SetSphere(Math::Max(radius, minSize));
}

View File

@@ -259,8 +259,7 @@ void SplineCollider::GetGeometry(CollisionShape& collision)
}
// Prepare scale
Float3 scale = _cachedScale;
scale = Float3::Max(scale.GetAbsolute(), minSize);
Float3 scale = Float3::Max(_transform.Scale.GetAbsolute(), minSize);
// TODO: add support for cooking collision for static splines in editor and reusing it in game

View File

@@ -3155,10 +3155,9 @@ void* PhysicsBackend::CreateController(void* scene, IPhysicsActor* actor, Physic
desc.material = (PxMaterial*)((PhysicalMaterial*)material->Instance)->GetPhysicsMaterial();
else
desc.material = DefaultMaterial;
const float minSize = 0.001f;
desc.height = Math::Max(height, minSize);
desc.radius = Math::Max(radius - Math::Max(contactOffset, 0.0f), minSize);
desc.stepOffset = Math::Min(stepOffset, desc.height + desc.radius * 2.0f - minSize);
desc.height = height;
desc.radius = radius;
desc.stepOffset = Math::Min(stepOffset, desc.height + desc.radius * 2.0f - 0.001f);
auto controllerPhysX = (PxCapsuleController*)scenePhysX->ControllerManager->createController(desc);
PxRigidActor* actorPhysX = controllerPhysX->getActor();
ASSERT(actorPhysX && actorPhysX->getNbShapes() == 1);
@@ -3183,7 +3182,7 @@ void PhysicsBackend::SetControllerSize(void* controller, float radius, float hei
{
auto controllerPhysX = (PxCapsuleController*)controller;
controllerPhysX->setRadius(radius);
controllerPhysX->resize(height);
controllerPhysX->setHeight(height);
}
void PhysicsBackend::SetControllerSlopeLimit(void* controller, float value)
@@ -3204,6 +3203,20 @@ void PhysicsBackend::SetControllerStepOffset(void* controller, float value)
controllerPhysX->setStepOffset(value);
}
Vector3 PhysicsBackend::GetControllerBasePosition(void* controller)
{
auto controllerPhysX = (PxCapsuleController*)controller;
const Vector3 origin = SceneOrigins[controllerPhysX->getScene()];
return P2C(controllerPhysX->getFootPosition()) + origin;
}
void PhysicsBackend::SetControllerBasePosition(void* controller, const Vector3& value)
{
auto controllerPhysX = (PxCapsuleController*)controller;
const Vector3 sceneOrigin = SceneOrigins[controllerPhysX->getScene()];
controllerPhysX->setFootPosition(PxExtendedVec3(value.X - sceneOrigin.X, value.Y - sceneOrigin.Y, value.Z - sceneOrigin.Z));
}
Vector3 PhysicsBackend::GetControllerUpDirection(void* controller)
{
auto controllerPhysX = (PxCapsuleController*)controller;

View File

@@ -248,6 +248,8 @@ public:
static void SetControllerSlopeLimit(void* controller, float value);
static void SetControllerNonWalkableMode(void* controller, int32 value);
static void SetControllerStepOffset(void* controller, float value);
static Vector3 GetControllerBasePosition(void* controller);
static void SetControllerBasePosition(void* controller, const Vector3& value);
static Vector3 GetControllerUpDirection(void* controller);
static void SetControllerUpDirection(void* controller, const Vector3& value);
static Vector3 GetControllerPosition(void* controller);

View File

@@ -407,6 +407,8 @@ namespace X11Impl
X11::Atom xAtomText;
X11::Atom xAtomString;
X11::Atom xAtomUTF8String;
X11::Atom xAtomFlaxRaw;
X11::Atom xAtomUriList;
X11::Atom xAtomXselData;
X11::Atom xDnDRequested = 0;
@@ -417,6 +419,8 @@ namespace X11Impl
int32 XFixesSelectionNotifyEvent = 0;
StringAnsi ClipboardText;
Array<byte> ClipboardData;
Array<StringAnsi> ClipboardFiles;
void ClipboardGetText(String& result, X11::Atom source, X11::Atom atom, X11::Window window)
{
@@ -447,11 +451,99 @@ namespace X11Impl
return;
if (event.xselection.property)
{
X11::XGetWindowProperty(event.xselection.display, event.xselection.requestor, event.xselection.property, 0L,(~0L), 0, AnyPropertyType, &target, &format, &size, &N,(unsigned char**)&data);
X11::XGetWindowProperty(event.xselection.display, event.xselection.requestor, event.xselection.property, 0L, (~0L), 0, AnyPropertyType, &target, &format, &size, &N, (unsigned char**)&data);
if (target == xAtomUTF8String || target == xAtomString)
{
// Got text to paste
result.Set(data , size);
result.Set(data, size);
X11::XFree(data);
}
X11::XDeleteProperty(event.xselection.display, event.xselection.requestor, event.xselection.property);
}
}
}
void ClipboardGetData(Array<byte>& result, X11::Atom source, X11::Atom atom, X11::Window window)
{
X11::Window selectionOwner = X11::XGetSelectionOwner(xDisplay, source);
if (selectionOwner == 0)
{
// No copy owner
return;
}
if (selectionOwner == window)
{
// Copy/paste from self
result.Set(ClipboardData.Get(), ClipboardData.Count());
return;
}
// Send event to get data from the owner
int format;
unsigned long N, size;
byte* data;
X11::Atom target;
X11::XEvent event;
X11::XConvertSelection(xDisplay, xAtomClipboard, atom, xAtomXselData, window, CurrentTime);
X11::XSync(xDisplay, 0);
if (X11::XCheckTypedEvent(xDisplay, SelectionNotify, &event))
{
if (event.xselection.selection != xAtomClipboard)
return;
if (event.xselection.property)
{
X11::XGetWindowProperty(event.xselection.display, event.xselection.requestor, event.xselection.property, 0L,(~0L), 0, AnyPropertyType, &target, &format, &size, &N, (byte**)&data);
if (target == atom)
{
result.Set(data, size);
X11::XFree(data);
}
X11::XDeleteProperty(event.xselection.display, event.xselection.requestor, event.xselection.property);
}
}
}
void ClipboardGetFiles(Array<String>& result, X11::Atom source, X11::Atom atom, X11::Window window)
{
X11::Window selectionOwner = X11::XGetSelectionOwner(xDisplay, source);
if (selectionOwner == 0)
{
// No copy owner
return;
}
if (selectionOwner == window)
{
// Copy/paste from self
result.Clear();
for (auto file : ClipboardFiles)
result.Add(String(file));
return;
}
// Send event to get data from the owner
int format;
unsigned long N, size;
char* data;
X11::Atom target;
X11::XEvent event;
X11::XConvertSelection(xDisplay, xAtomClipboard, atom, xAtomXselData, window, CurrentTime);
X11::XSync(xDisplay, 0);
if (X11::XCheckTypedEvent(xDisplay, SelectionNotify, &event))
{
if (event.xselection.selection != xAtomClipboard)
return;
if (event.xselection.property)
{
X11::XGetWindowProperty(event.xselection.display, event.xselection.requestor, event.xselection.property, 0L, (~0L), 0, AnyPropertyType, &target, &format, &size, &N, (unsigned char**)&data);
if (target == atom)
{
String filesString(StringAnsi(data, size));
filesString.Split('\n', result);
for (auto& file : result)
{
if (file.StartsWith(TEXT("file://")))
file = file.Substring(7);
file = file.TrimTrailing(); // Trim '\r'
}
X11::XFree(data);
}
X11::XDeleteProperty(event.xselection.display, event.xselection.requestor, event.xselection.property);
@@ -1105,24 +1197,123 @@ void SDLClipboard::SetText(const StringView& text)
if (X11Impl::xDisplay)
{
X11::Window window = (X11::Window)(mainWindow->GetNativePtr());
X11Impl::ClipboardText.Set(text.Get(), text.Length());
X11Impl::ClipboardData.Clear();
X11Impl::ClipboardFiles.Clear();
X11::Window window = (X11::Window)(mainWindow->GetNativePtr());
X11::XSetSelectionOwner(X11Impl::xDisplay, X11Impl::xAtomClipboard, window, CurrentTime); // CLIPBOARD
//X11::XSetSelectionOwner(xDisplay, xAtomPrimary, window, CurrentTime); // XA_PRIMARY
X11::XFlush(X11Impl::xDisplay);
X11::XGetSelectionOwner(X11Impl::xDisplay, X11Impl::xAtomClipboard);
//X11::XGetSelectionOwner(xDisplay, xAtomPrimary);
}
else
{
SDL_SetClipboardText(StringAnsi(text).GetText());
}
}
void SDLClipboard::SetRawData(const Span<byte>& data)
{
if (CommandLine::Options.Headless.IsTrue())
return;
auto mainWindow = Engine::MainWindow;
if (!mainWindow)
return;
if (X11Impl::xDisplay)
{
X11Impl::ClipboardData.Set(data.Get(), data.Length());
X11Impl::ClipboardText.Clear();
X11Impl::ClipboardFiles.Clear();
X11::Window window = (X11::Window)(mainWindow->GetNativePtr());
X11::XSetSelectionOwner(X11Impl::xDisplay, X11Impl::xAtomClipboard, window, CurrentTime); // CLIPBOARD
//X11::XSetSelectionOwner(xDisplay, xAtomPrimary, window, CurrentTime); // XA_PRIMARY
X11::XFlush(X11Impl::xDisplay);
}
else
{
if (data.Length() == 0)
return;
const char* uriList = "flaxengine/raw";
Array<byte>* buffer = New<Array<byte>>(data.Get(), data.Length());
SDL_SetClipboardData([](void* userdata, const char* mime_type, size_t* size) -> const void*
{
// Clipboard data is requested
Array<byte>* buffer = static_cast<Array<byte>*>(userdata);
if (StringUtils::Compare(mime_type, "flaxengine/raw") == 0)
{
*size = buffer->Count();
return buffer->Get();
}
*size = 0;
return nullptr;
},
[](void* userdata)
{
// Cleanup previous clipboard data
Array<byte>* buffer = static_cast<Array<byte>*>(userdata);
Delete(buffer);
}, buffer, &uriList, 1);
}
}
void SDLClipboard::SetFiles(const Array<String>& files)
{
if (CommandLine::Options.Headless.IsTrue())
return;
auto mainWindow = Engine::MainWindow;
if (!mainWindow)
return;
if (X11Impl::xDisplay)
{
X11Impl::ClipboardFiles.Clear();
for (auto file : files)
X11Impl::ClipboardFiles.Add(StringAnsi(file));
X11Impl::ClipboardText.Clear();
X11Impl::ClipboardData.Clear();
X11::Window window = (X11::Window)(mainWindow->GetNativePtr());
X11::XSetSelectionOwner(X11Impl::xDisplay, X11Impl::xAtomClipboard, window, CurrentTime); // CLIPBOARD
//X11::XSetSelectionOwner(xDisplay, xAtomPrimary, window, CurrentTime); // XA_PRIMARY
X11::XFlush(X11Impl::xDisplay);
}
else
{
if (files.Count() == 0)
return;
const char* uriList = "text/uri-list";
StringAnsi* buffer = New<StringAnsi>();
for (auto file : files)
{
buffer->Append("file://");
buffer->Append(StringAnsi(file));
buffer->Append("\n");
}
SDL_SetClipboardData([](void* userdata, const char* mime_type, size_t* size) -> const void*
{
// Clipboard data is requested
StringAnsi* buffer = (StringAnsi*)userdata;
if (StringUtils::Compare(mime_type, "text/uri-list") == 0)
{
*size = buffer->Length();
return buffer->Get();
}
*size = 0;
return nullptr;
},
[](void* userdata)
{
// Cleanup previous clipboard data
StringAnsi* buffer = (StringAnsi*)userdata;
Delete(buffer);
}, buffer, &uriList, 1);
}
}
String SDLClipboard::GetText()
@@ -1136,7 +1327,6 @@ String SDLClipboard::GetText()
if (X11Impl::xDisplay)
{
X11::Window window = reinterpret_cast<X11::Window>(mainWindow->GetNativePtr());
X11Impl::ClipboardGetText(result, X11Impl::xAtomClipboard, X11Impl::xAtomUTF8String, window);
if (result.HasChars())
return result;
@@ -1157,12 +1347,56 @@ String SDLClipboard::GetText()
Array<byte> SDLClipboard::GetRawData()
{
return Array<byte>();
auto mainWindow = Engine::MainWindow;
if (!mainWindow)
return Array<byte>();
if (X11Impl::xDisplay)
{
X11::Window window = reinterpret_cast<X11::Window>(mainWindow->GetNativePtr());
Array<byte> array;
X11Impl::ClipboardGetData(array, X11Impl::xAtomClipboard, X11Impl::xAtomFlaxRaw, window);
return array;
}
else
{
size_t length = 0;
byte* data = static_cast<byte*>(SDL_GetClipboardData("flaxengine/raw", &length));
Array<byte> rawData(data, length);
return rawData;
}
}
Array<String> SDLClipboard::GetFiles()
{
return Array<String>();
auto mainWindow = Engine::MainWindow;
if (!mainWindow)
return Array<String>();
if (X11Impl::xDisplay)
{
X11::Window window = reinterpret_cast<X11::Window>(mainWindow->GetNativePtr());
Array<String> array;
X11Impl::ClipboardGetFiles(array, X11Impl::xAtomClipboard, X11Impl::xAtomUriList, window);
if (array.Count() > 0)
return array;
return Array<String>();
}
else
{
size_t length = 0;
const char* data = static_cast<const char*>(SDL_GetClipboardData("text/uri-list", &length));
String stringBuffer = String(StringAnsi(data, length));
Array<String> files;
stringBuffer.Split('\n', files);
for (auto& file : files)
{
if (file.StartsWith(TEXT("file://")))
file = file.Substring(7);
file = file.TrimTrailing(); // Trim '\r'
}
return files;
}
}
bool SDLCALL SDLPlatform::X11EventHook(void* userdata, _XEvent* xevent)
@@ -1307,6 +1541,7 @@ bool SDLCALL SDLPlatform::X11EventHook(void* userdata, _XEvent* xevent)
}
else if (event.type == SelectionRequest)
{
// Clipboard request
if (event.xselectionrequest.selection != xAtomClipboard)
return false;
@@ -1323,15 +1558,35 @@ bool SDLCALL SDLPlatform::X11EventHook(void* userdata, _XEvent* xevent)
int result = 0;
if (ev.target == xAtomTargets)
{
// Request supported targets for clipboard content
Array<X11::Atom, FixedAllocation<2>> types(2);
types.Add(xAtomTargets);
types.Add(xAtomUTF8String);
if (X11Impl::ClipboardData.Count() > 0)
types.Add(xAtomFlaxRaw);
else if (X11Impl::ClipboardFiles.Count() > 0)
types.Add(xAtomUriList);
else
types.Add(xAtomUTF8String);
result = X11::XChangeProperty(xDisplay, ev.requestor, ev.property, xAtomAtom, 32, PropModeReplace, (unsigned char*)types.Get(), types.Count());
}
// Request target type
else if (ev.target == xAtomString || ev.target == xAtomText)
result = X11::XChangeProperty(xDisplay, ev.requestor, ev.property, xAtomString, 8, PropModeReplace, (unsigned char*)X11Impl::ClipboardText.Get(), X11Impl::ClipboardText.Length());
else if (ev.target == xAtomUTF8String)
result = X11::XChangeProperty(xDisplay, ev.requestor, ev.property, xAtomUTF8String, 8, PropModeReplace, (unsigned char*)X11Impl::ClipboardText.Get(), X11Impl::ClipboardText.Length());
else if (ev.target == xAtomFlaxRaw)
result = X11::XChangeProperty(xDisplay, ev.requestor, ev.property, xAtomFlaxRaw, 8, PropModeReplace, X11Impl::ClipboardData.Get(), X11Impl::ClipboardData.Count());
else if (ev.target == xAtomUriList)
{
StringAnsi fileString;
for (auto file : X11Impl::ClipboardFiles)
{
fileString.Append("file://");
fileString.Append(file);
fileString.Append("\n");
}
result = X11::XChangeProperty(xDisplay, ev.requestor, ev.property, xAtomUriList, 8, PropModeReplace, (unsigned char*)fileString.Get(), fileString.Length());
}
else
ev.property = 0;
if ((result & 2) == 0)
@@ -1389,7 +1644,6 @@ bool SDLPlatform::InitX11(void* display)
SDL_SetX11EventHook((SDL_X11EventHook)&X11EventHook, nullptr);
X11::XSetErrorHandler(X11ErrorHandler);
xDisplay = X11::XOpenDisplay(nullptr);
xAtomDeleteWindow = X11::XInternAtom(xDisplay, "WM_DELETE_WINDOW", 0);
xAtomXdndEnter = X11::XInternAtom(xDisplay, "XdndEnter", 0);
xAtomXdndPosition = X11::XInternAtom(xDisplay, "XdndPosition", 0);
@@ -1414,6 +1668,8 @@ bool SDLPlatform::InitX11(void* display)
xAtomUTF8String = X11::XInternAtom(xDisplay, "UTF8_STRING", 1);
if (xAtomUTF8String == 0)
xAtomUTF8String = xAtomString;
xAtomFlaxRaw = X11::XInternAtom(xDisplay, "flaxengine/raw", 0);
xAtomUriList = X11::XInternAtom(xDisplay, "text/uri-list", 0);
xAtomXselData = X11::XInternAtom(xDisplay, "XSEL_DATA", 0);
// We need to override handling of the XFixes selection tracking events from SDL

View File

@@ -750,6 +750,11 @@ Float2 SDLWindow::ClientToScreen(const Float2& clientPos) const
void SDLWindow::FlashWindow()
{
#if PLATFORM_LINUX
// Flashing brings the window on top of other windows, disable it for now
if (SDLPlatform::UsesWayland())
return;
#endif
SDL_FlashWindow(_window, SDL_FLASH_UNTIL_FOCUSED);
}

View File

@@ -43,17 +43,17 @@ void* WindowsPlatform::Instance = nullptr;
extern "C" {
static HANDLE dbgHelpLock;
void DbgHelpInit()
void FlaxDbgHelpInit()
{
dbgHelpLock = CreateMutexW(nullptr, FALSE, nullptr);
}
void DbgHelpLock()
void FlaxDbgHelpLock()
{
WaitForSingleObject(dbgHelpLock, INFINITE);
}
void DbgHelpUnlock()
void FlaxDbgHelpUnlock()
{
ReleaseMutex(dbgHelpLock);
}
@@ -552,7 +552,7 @@ void WindowsPlatform::PreInit(void* hInstance)
#if CRASH_LOG_ENABLE
TCHAR buffer[MAX_PATH] = { 0 };
DbgHelpLock();
FlaxDbgHelpLock();
if (::GetModuleFileNameW(::GetModuleHandleW(nullptr), buffer, MAX_PATH))
SymbolsPath.Add(StringUtils::GetDirectoryName(buffer));
if (::GetEnvironmentVariableW(TEXT("_NT_SYMBOL_PATH"), buffer, MAX_PATH))
@@ -561,7 +561,7 @@ void WindowsPlatform::PreInit(void* hInstance)
options |= SYMOPT_LOAD_LINES | SYMOPT_FAIL_CRITICAL_ERRORS | SYMOPT_DEFERRED_LOADS | SYMOPT_EXACT_SYMBOLS;
SymSetOptions(options);
OnSymbolsPathModified();
DbgHelpUnlock();
FlaxDbgHelpUnlock();
#endif
GetWindowsVersion(WindowsName, VersionMajor, VersionMinor, VersionBuild);
@@ -781,7 +781,7 @@ void WindowsPlatform::BeforeExit()
void WindowsPlatform::Exit()
{
#if CRASH_LOG_ENABLE
DbgHelpLock();
FlaxDbgHelpLock();
#if !TRACY_ENABLE
if (SymInitialized)
{
@@ -790,7 +790,7 @@ void WindowsPlatform::Exit()
}
#endif
SymbolsPath.Resize(0);
DbgHelpUnlock();
FlaxDbgHelpUnlock();
#endif
#if !PLATFORM_SDL
@@ -1298,14 +1298,14 @@ void* WindowsPlatform::LoadLibrary(const Char* filename)
#if CRASH_LOG_ENABLE
// Refresh modules info during next stack trace collecting to have valid debug symbols information
DbgHelpLock();
FlaxDbgHelpLock();
if (folder.HasChars() && !SymbolsPath.Contains(folder))
{
SymbolsPath.Add(folder);
SymbolsPath.Last().Replace('/', '\\');
OnSymbolsPathModified();
}
DbgHelpUnlock();
FlaxDbgHelpUnlock();
#endif
return handle;
@@ -1316,7 +1316,7 @@ void* WindowsPlatform::LoadLibrary(const Char* filename)
Array<PlatformBase::StackFrame> WindowsPlatform::GetStackFrames(int32 skipCount, int32 maxDepth, void* context)
{
Array<StackFrame> result;
DbgHelpLock();
FlaxDbgHelpLock();
// Initialize
HANDLE process = GetCurrentProcess();
@@ -1448,7 +1448,7 @@ Array<PlatformBase::StackFrame> WindowsPlatform::GetStackFrames(int32 skipCount,
}
}
DbgHelpUnlock();
FlaxDbgHelpUnlock();
return result;
}

View File

@@ -78,6 +78,32 @@ TEST_CASE("Array")
TEST_CASE("BitArray")
{
SECTION("Test Access")
{
BitArray<> a1;
CHECK(a1.Count() == 0);
for (int32 i = 0; i < 310; i++)
{
a1.Add(false);
}
CHECK(a1.Count() == 310);
a1.Resize(300);
CHECK(a1.Count() == 300);
CHECK(a1.Capacity() >= 300);
a1.SetAll(true);
a1.SetAll(false);
for (int32 i = 0; i < 300; i++)
{
a1.Set(i, true);
for (int32 j = 0; j < 300; j++)
{
bool expected = j == i;
CHECK(a1.Get(j) == expected);
}
a1.Set(i, false);
}
}
SECTION("Test Allocators")
{
BitArray<> a1;
@@ -142,7 +168,7 @@ TEST_CASE("BitArray")
// Generate some random data for testing
BitArray<> testData;
testData.Resize(32);
testData.Resize(128);
RandomStream rand(101);
for (int32 i = 0; i < testData.Count(); i++)
testData.Set(i, rand.GetBool());
@@ -151,8 +177,8 @@ TEST_CASE("BitArray")
{
const BitArray<> a1(testData);
const BitArray<InlinedAllocation<8>> a2(testData);
const BitArray<InlinedAllocation<64>> a3(testData);
const BitArray<FixedAllocation<64>> a4(testData);
const BitArray<InlinedAllocation<256>> a3(testData);
const BitArray<FixedAllocation<256>> a4(testData);
CHECK(a1 == testData);
CHECK(a2 == testData);
CHECK(a3 == testData);

View File

@@ -42,8 +42,6 @@ bool Task::Wait(double timeoutMilliseconds) const
PROFILE_CPU();
const double startTime = Platform::GetTimeSeconds();
// TODO: no active waiting! use a semaphore!
do
{
auto state = GetState();
@@ -209,7 +207,7 @@ void Task::OnCancel()
{
// Wait for it a little bit
constexpr double timeout = 10000.0; // 10s
LOG(Warning, "Cannot cancel \'{0}\' because it's still running, waiting for end with timeout: {1}ms", ToString(), timeout);
//LOG(Warning, "Cannot cancel \'{0}\' because it's still running, waiting for end with timeout: {1}ms", ToString(), timeout);
Wait(timeout);
}

View File

@@ -13,6 +13,7 @@
#include "Engine/Graphics/Textures/TextureData.h"
#include "Engine/Graphics/PixelFormatExtensions.h"
#if USE_EDITOR
#include "Engine/Platform/MessageBox.h"
#include "Engine/Graphics/GPUDevice.h"
#endif
#include "Engine/Utilities/AnsiPathTempFile.h"
@@ -358,6 +359,9 @@ HRESULT LoadFromEXRFile(const StringView& path, DirectX::ScratchImage& image)
free(pixels);
return result;
#else
#if USE_EDITOR
MessageBox::Show(TEXT("EXR format is not supported."), TEXT("Import warning"), MessageBoxButtons::OK, MessageBoxIcon::Warning);
#endif
LOG(Warning, "EXR format is not supported.");
return E_FAIL;
#endif

View File

@@ -13,6 +13,7 @@
#include "Engine/Graphics/PixelFormatExtensions.h"
#include "Engine/Utilities/AnsiPathTempFile.h"
#include "Engine/Platform/File.h"
#include "Engine/Platform/MessageBox.h"
#define STBI_ASSERT(x) ASSERT(x)
#define STBI_MALLOC(sz) Allocator::Allocate(sz)
@@ -286,21 +287,27 @@ bool TextureTool::ExportTextureStb(ImageType type, const StringView& path, const
break;
}
case ImageType::GIF:
MessageBox::Show(TEXT("GIF format is not supported."), TEXT("Export warning"), MessageBoxButtons::OK, MessageBoxIcon::Warning);
LOG(Warning, "GIF format is not supported.");
break;
case ImageType::TIFF:
MessageBox::Show(TEXT("TIFF format is not supported."), TEXT("Export warning"), MessageBoxButtons::OK, MessageBoxIcon::Warning);
LOG(Warning, "GIF format is not supported.");
break;
case ImageType::DDS:
MessageBox::Show(TEXT("DDS format is not supported."), TEXT("Export warning"), MessageBoxButtons::OK, MessageBoxIcon::Warning);
LOG(Warning, "DDS format is not supported.");
break;
case ImageType::RAW:
MessageBox::Show(TEXT("RAW format is not supported."), TEXT("Export warning"), MessageBoxButtons::OK, MessageBoxIcon::Warning);
LOG(Warning, "RAW format is not supported.");
break;
case ImageType::EXR:
MessageBox::Show(TEXT("EXR format is not supported."), TEXT("Export warning"), MessageBoxButtons::OK, MessageBoxIcon::Warning);
LOG(Warning, "EXR format is not supported.");
break;
default:
MessageBox::Show(TEXT("Unknown format."), TEXT("Export warning"), MessageBoxButtons::OK, MessageBoxIcon::Warning);
LOG(Warning, "Unknown format.");
break;
}
@@ -434,17 +441,21 @@ bool TextureTool::ImportTextureStb(ImageType type, const StringView& path, Textu
free(pixels);
#else
MessageBox::Show(TEXT("EXR format is not supported."), TEXT("Import warning"), MessageBoxButtons::OK, MessageBoxIcon::Warning);
LOG(Warning, "EXR format is not supported.");
#endif
break;
}
case ImageType::DDS:
MessageBox::Show(TEXT("DDS format is not supported."), TEXT("Import warning"), MessageBoxButtons::OK, MessageBoxIcon::Warning);
LOG(Warning, "DDS format is not supported.");
break;
case ImageType::TIFF:
MessageBox::Show(TEXT("TIFF format is not supported."), TEXT("Import warning"), MessageBoxButtons::OK, MessageBoxIcon::Warning);
LOG(Warning, "TIFF format is not supported.");
break;
default:
MessageBox::Show(TEXT("Unknown format."), TEXT("Import warning"), MessageBoxButtons::OK, MessageBoxIcon::Warning);
LOG(Warning, "Unknown format.");
return true;
}

View File

@@ -301,7 +301,7 @@ namespace FlaxEngine.GUI
else
{
text = _watermarkText;
if (text.Length > 0)
if (text?.Length > 0)
{
Render2D.DrawText(font, _watermarkText, WatermarkTextColor, ref _layout, TextMaterial);
}

View File

@@ -3,7 +3,7 @@
// Ben Golus
// https://bgolus.medium.com/the-best-darn-grid-shader-yet-727f9278b9d8#3e73
#define USE_FORWARD true;
#define MIN_DERIV 0.00001f
#include "./Flax/Common.hlsl"
@@ -61,11 +61,6 @@ float remap(float origFrom, float origTo, float targetFrom, float targetTo, floa
return lerp(targetFrom, targetTo, rel);
}
float ddLength(float a)
{
return length(float2(ddx(a), ddy(a)));
}
float GetLine(float pos, float scale, float thickness)
{
float lineWidth = thickness;
@@ -73,7 +68,7 @@ float GetLine(float pos, float scale, float thickness)
float2 uvDDXY = float2(ddx(coord), ddy(coord));
float deriv = float(length(uvDDXY.xy));
float deriv = max(float(length(uvDDXY.xy)), MIN_DERIV);
float drawWidth = clamp(lineWidth, deriv, 0.5);
float lineAA = deriv * 1.5;
float gridUV = abs(coord);
@@ -92,7 +87,7 @@ float GetGrid(float3 pos, float scale, float thickness)
float4 uvDDXY = float4(ddx(coord), ddy(coord));
float2 deriv = float2(length(uvDDXY.xz), length(uvDDXY.yw));
float2 deriv = max(float2(length(uvDDXY.xz), length(uvDDXY.yw)), float2(MIN_DERIV, MIN_DERIV));
float2 drawWidth = clamp(lineWidth, deriv, 0.5);
float2 lineAA = deriv * 1.5;
float2 gridUV = 1.0 - abs(frac(coord) * 2.0 - 1.0);

View File

@@ -20,7 +20,7 @@
*/
/**
* Main include header for the SDL library, version 3.2.16
* Main include header for the SDL library, version 3.3.0
*
* It is almost always best to include just this one header instead of
* picking out individual headers included here. There are exceptions to

View File

@@ -132,7 +132,7 @@ extern "C" {
#define SDL_TriggerBreakpoint() __debugbreak()
#elif defined(_MSC_VER) && defined(_M_IX86)
#define SDL_TriggerBreakpoint() { _asm { int 0x03 } }
#elif defined(ANDROID)
#elif defined(ANDROID) || defined(__SYMBIAN32__)
#include <assert.h>
#define SDL_TriggerBreakpoint() assert(0)
#elif SDL_HAS_BUILTIN(__builtin_debugtrap)

View File

@@ -1149,14 +1149,14 @@ extern SDL_DECLSPEC float SDLCALL SDL_GetAudioStreamFrequencyRatio(SDL_AudioStre
*
* The frequency ratio is used to adjust the rate at which input data is
* consumed. Changing this effectively modifies the speed and pitch of the
* audio. A value greater than 1.0 will play the audio faster, and at a higher
* pitch. A value less than 1.0 will play the audio slower, and at a lower
* pitch.
* audio. A value greater than 1.0f will play the audio faster, and at a
* higher pitch. A value less than 1.0f will play the audio slower, and at a
* lower pitch. 1.0f means play at normal speed.
*
* This is applied during SDL_GetAudioStreamData, and can be continuously
* changed to create various effects.
*
* \param stream the stream the frequency ratio is being changed.
* \param stream the stream on which the frequency ratio is being changed.
* \param ratio the frequency ratio. 1.0 is normal speed. Must be between 0.01
* and 100.
* \returns true on success or false on failure; call SDL_GetError() for more
@@ -1332,7 +1332,7 @@ extern SDL_DECLSPEC bool SDLCALL SDL_SetAudioStreamInputChannelMap(SDL_AudioStre
* Channel maps are optional; most things do not need them, instead passing
* data in the [order that SDL expects](CategoryAudio#channel-layouts).
*
* The output channel map reorders data that leaving a stream via
* The output channel map reorders data that is leaving a stream via
* SDL_GetAudioStreamData.
*
* Each item in the array represents an input channel, and its value is the
@@ -1414,6 +1414,136 @@ extern SDL_DECLSPEC bool SDLCALL SDL_SetAudioStreamOutputChannelMap(SDL_AudioStr
*/
extern SDL_DECLSPEC bool SDLCALL SDL_PutAudioStreamData(SDL_AudioStream *stream, const void *buf, int len);
/**
* A callback that fires for completed SDL_PutAudioStreamDataNoCopy() data.
*
* When using SDL_PutAudioStreamDataNoCopy() to provide data to an
* SDL_AudioStream, it's not safe to dispose of the data until the stream has
* completely consumed it. Often times it's difficult to know exactly when
* this has happened.
*
* This callback fires once when the stream no longer needs the buffer,
* allowing the app to easily free or reuse it.
*
* \param userdata an opaque pointer provided by the app for their personal
* use.
* \param buf the pointer provided to SDL_PutAudioStreamDataNoCopy().
* \param buflen the size of buffer, in bytes, provided to
* SDL_PutAudioStreamDataNoCopy().
*
* \threadsafety This callbacks may run from any thread, so if you need to
* protect shared data, you should use SDL_LockAudioStream to
* serialize access; this lock will be held before your callback
* is called, so your callback does not need to manage the lock
* explicitly.
*
* \since This datatype is available since SDL 3.4.0.
*
* \sa SDL_SetAudioStreamGetCallback
* \sa SDL_SetAudioStreamPutCallback
*/
typedef void (SDLCALL *SDL_AudioStreamDataCompleteCallback)(void *userdata, const void *buf, int buflen);
/**
* Add external data to an audio stream without copying it.
*
* Unlike SDL_PutAudioStreamData(), this function does not make a copy of the
* provided data, instead storing the provided pointer. This means that the
* put operation does not need to allocate and copy the data, but the original
* data must remain available until the stream is done with it, either by
* being read from the stream in its entirety, or a call to
* SDL_ClearAudioStream() or SDL_DestroyAudioStream().
*
* The data must match the format/channels/samplerate specified in the latest
* call to SDL_SetAudioStreamFormat, or the format specified when creating the
* stream if it hasn't been changed.
*
* An optional callback may be provided, which is called when the stream no
* longer needs the data. Once this callback fires, the stream will not access
* the data again. This callback will fire for any reason the data is no
* longer needed, including clearing or destroying the stream.
*
* Note that there is still an allocation to store tracking information, so
* this function is more efficient for larger blocks of data. If you're
* planning to put a few samples at a time, it will be more efficient to use
* SDL_PutAudioStreamData(), which allocates and buffers in blocks.
*
* \param stream the stream the audio data is being added to.
* \param buf a pointer to the audio data to add.
* \param len the number of bytes to add to the stream.
* \param callback the callback function to call when the data is no longer
* needed by the stream. May be NULL.
* \param userdata an opaque pointer provided to the callback for its own
* personal use.
* \returns true on success or false on failure; call SDL_GetError() for more
* information.
*
* \threadsafety It is safe to call this function from any thread, but if the
* stream has a callback set, the caller might need to manage
* extra locking.
*
* \since This function is available since SDL 3.4.0.
*
* \sa SDL_ClearAudioStream
* \sa SDL_FlushAudioStream
* \sa SDL_GetAudioStreamData
* \sa SDL_GetAudioStreamQueued
*/
extern SDL_DECLSPEC bool SDLCALL SDL_PutAudioStreamDataNoCopy(SDL_AudioStream *stream, const void *buf, int len, SDL_AudioStreamDataCompleteCallback callback, void *userdata);
/**
* Add data to the stream with each channel in a separate array.
*
* This data must match the format/channels/samplerate specified in the latest
* call to SDL_SetAudioStreamFormat, or the format specified when creating the
* stream if it hasn't been changed.
*
* The data will be interleaved and queued. Note that SDL_AudioStream only
* operates on interleaved data, so this is simply a convenience function for
* easily queueing data from sources that provide separate arrays. There is no
* equivalent function to retrieve planar data.
*
* The arrays in `channel_buffers` are ordered as they are to be interleaved;
* the first array will be the first sample in the interleaved data. Any
* individual array may be NULL; in this case, silence will be interleaved for
* that channel.
*
* `num_channels` specifies how many arrays are in `channel_buffers`. This can
* be used as a safety to prevent overflow, in case the stream format has
* changed elsewhere. If more channels are specified than the current input
* spec, they are ignored. If less channels are specified, the missing arrays
* are treated as if they are NULL (silence is written to those channels). If
* the count is -1, SDL will assume the array count matches the current input
* spec.
*
* Note that `num_samples` is the number of _samples per array_. This can also
* be thought of as the number of _sample frames_ to be queued. A value of 1
* with stereo arrays will queue two samples to the stream. This is different
* than SDL_PutAudioStreamData, which wants the size of a single array in
* bytes.
*
* \param stream the stream the audio data is being added to.
* \param channel_buffers a pointer to an array of arrays, one array per
* channel.
* \param num_channels the number of arrays in `channel_buffers` or -1.
* \param num_samples the number of _samples_ per array to write to the
* stream.
* \returns true on success or false on failure; call SDL_GetError() for more
* information.
*
* \threadsafety It is safe to call this function from any thread, but if the
* stream has a callback set, the caller might need to manage
* extra locking.
*
* \since This function is available since SDL 3.4.0.
*
* \sa SDL_ClearAudioStream
* \sa SDL_FlushAudioStream
* \sa SDL_GetAudioStreamData
* \sa SDL_GetAudioStreamQueued
*/
extern SDL_DECLSPEC bool SDLCALL SDL_PutAudioStreamPlanarData(SDL_AudioStream *stream, const void * const *channel_buffers, int num_channels, int num_samples);
/**
* Get converted/resampled data from the stream.
*
@@ -1583,8 +1713,8 @@ extern SDL_DECLSPEC bool SDLCALL SDL_PauseAudioStreamDevice(SDL_AudioStream *str
* previously been paused. Once unpaused, any bound audio streams will begin
* to progress again, and audio can be generated.
*
* Remember, SDL_OpenAudioDeviceStream opens device in a paused state, so this
* function call is required for audio playback to begin on such device.
* SDL_OpenAudioDeviceStream opens audio devices in a paused state, so this
* function call is required for audio playback to begin on such devices.
*
* \param stream the audio stream associated with the audio device to resume.
* \returns true on success or false on failure; call SDL_GetError() for more
@@ -1841,7 +1971,7 @@ extern SDL_DECLSPEC void SDLCALL SDL_DestroyAudioStream(SDL_AudioStream *stream)
* Also unlike other functions, the audio device begins paused. This is to map
* more closely to SDL2-style behavior, since there is no extra step here to
* bind a stream to begin audio flowing. The audio device should be resumed
* with `SDL_ResumeAudioStreamDevice(stream);`
* with SDL_ResumeAudioStreamDevice().
*
* This function works with both playback and recording devices.
*
@@ -1887,6 +2017,85 @@ extern SDL_DECLSPEC void SDLCALL SDL_DestroyAudioStream(SDL_AudioStream *stream)
*/
extern SDL_DECLSPEC SDL_AudioStream * SDLCALL SDL_OpenAudioDeviceStream(SDL_AudioDeviceID devid, const SDL_AudioSpec *spec, SDL_AudioStreamCallback callback, void *userdata);
/**
* A callback that fires around an audio device's processing work.
*
* This callback fires when a logical audio device is about to start accessing
* its bound audio streams, and fires again when it has finished accessing
* them. It covers the range of one "iteration" of the audio device.
*
* It can be useful to use this callback to update state that must apply to
* all bound audio streams atomically: to make sure state changes don't happen
* while half of the streams are already processed for the latest audio
* buffer.
*
* This callback should run as quickly as possible and not block for any
* significant time, as this callback delays submission of data to the audio
* device, which can cause audio playback problems. This callback delays all
* audio processing across a single physical audio device: all its logical
* devices and all bound audio streams. Use it carefully.
*
* \param userdata a pointer provided by the app through
* SDL_SetAudioPostmixCallback, for its own use.
* \param devid the audio device this callback is running for.
* \param start true if this is the start of the iteration, false if the end.
*
* \threadsafety This will run from a background thread owned by SDL. The
* application is responsible for locking resources the callback
* touches that need to be protected.
*
* \since This datatype is available since SDL 3.4.0.
*
* \sa SDL_SetAudioIterationCallbacks
*/
typedef void (SDLCALL *SDL_AudioIterationCallback)(void *userdata, SDL_AudioDeviceID devid, bool start);
/**
* Set callbacks that fire around a new iteration of audio device processing.
*
* Two callbacks are provided here: one that runs when a device is about to
* process its bound audio streams, and another that runs when the device has
* finished processing them.
*
* These callbacks can run at any time, and from any thread; if you need to
* serialize access to your app's data, you should provide and use a mutex or
* other synchronization device.
*
* Generally these callbacks are used to apply state that applies to multiple
* bound audio streams, with a guarantee that the audio device's thread isn't
* halfway through processing them. Generally a finer-grained lock through
* SDL_LockAudioStream() is more appropriate.
*
* The callbacks are extremely time-sensitive; the callback should do the
* least amount of work possible and return as quickly as it can. The longer
* the callback runs, the higher the risk of audio dropouts or other problems.
*
* This function will block until the audio device is in between iterations,
* so any existing callback that might be running will finish before this
* function sets the new callback and returns.
*
* Physical devices do not accept these callbacks, only logical devices
* created through SDL_OpenAudioDevice() can be.
*
* Setting a NULL callback function disables any previously-set callback.
* Either callback may be NULL, and the same callback is permitted to be used
* for both.
*
* \param devid the ID of an opened audio device.
* \param start a callback function to be called at the start of an iteration.
* Can be NULL.
* \param end a callback function to be called at the end of an iteration. Can
* be NULL.
* \param userdata app-controlled pointer passed to callback. Can be NULL.
* \returns true on success or false on failure; call SDL_GetError() for more
* information.
*
* \threadsafety It is safe to call this function from any thread.
*
* \since This function is available since SDL 3.4.0.
*/
extern SDL_DECLSPEC bool SDLCALL SDL_SetAudioIterationCallbacks(SDL_AudioDeviceID devid, SDL_AudioIterationCallback start, SDL_AudioIterationCallback end, void *userdata);
/**
* A callback that fires when data is about to be fed to an audio device.
*

View File

@@ -261,9 +261,9 @@
*
* On compilers without restrict support, this is defined to nothing.
*
* \since This macro is available since SDL 3.2.0.
* \since This macro is available since SDL 3.4.0.
*/
#define SDL_RESTRICT __restrict__
#define SDL_RESTRICT __restrict
/**
* Check if the compiler supports a given builtin functionality.
@@ -281,9 +281,61 @@
*/
#define SDL_HAS_BUILTIN(x) __has_builtin(x)
/**
* A macro to specify data alignment.
*
* This informs the compiler that a given datatype or variable must be aligned
* to a specific byte count.
*
* For example:
*
* ```c
* // make sure this is struct is aligned to 16 bytes for SIMD access.
* typedef struct {
* float x, y, z, w;
* } SDL_ALIGNED(16) MySIMDAlignedData;
*
* // make sure this one field in a struct is aligned to 16 bytes for SIMD access.
* typedef struct {
* SomeStuff stuff;
* float position[4] SDL_ALIGNED(16);
* SomeOtherStuff other_stuff;
* } MyStruct;
*
* // make sure this variable is aligned to 32 bytes.
* int SDL_ALIGNED(32) myval = 0;
* ```
*
* Alignment is only guaranteed for things the compiler places: local
* variables on the stack and global/static variables. To dynamically allocate
* something that respects this alignment, use SDL_aligned_alloc() or some
* other mechanism.
*
* On compilers without alignment support, this macro is defined to an invalid
* symbol, to make it clear that the current compiler is likely to generate
* incorrect code when it sees this macro.
*
* \param x the byte count to align to, so the data's address will be a
* multiple of this value.
*
* \since This macro is available since SDL 3.4.0.
*/
#define SDL_ALIGNED(x) __attribute__((aligned(x)))
/* end of wiki documentation section. */
#endif
/* `restrict` is from C99, but __restrict works with both Visual Studio and GCC. */
#ifndef SDL_RESTRICT
# if defined(restrict) || ((defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)))
# define SDL_RESTRICT restrict
# elif defined(_MSC_VER) || defined(__GNUC__) || defined(__clang__)
# define SDL_RESTRICT __restrict
# else
# define SDL_RESTRICT
# endif
#endif
#ifndef SDL_HAS_BUILTIN
#ifdef __has_builtin
#define SDL_HAS_BUILTIN(x) __has_builtin(x)
@@ -389,7 +441,7 @@
#endif /* SDL_FORCE_INLINE not defined */
#ifndef SDL_NORETURN
#ifdef __GNUC__
#if defined(__GNUC__)
#define SDL_NORETURN __attribute__((noreturn))
#elif defined(_MSC_VER)
#define SDL_NORETURN __declspec(noreturn)
@@ -484,3 +536,18 @@
#define SDL_ALLOC_SIZE2(p1, p2)
#endif
#endif /* SDL_ALLOC_SIZE2 not defined */
#ifndef SDL_ALIGNED
#if defined(__clang__) || defined(__GNUC__)
#define SDL_ALIGNED(x) __attribute__((aligned(x)))
#elif defined(_MSC_VER)
#define SDL_ALIGNED(x) __declspec(align(x))
#elif defined(__cplusplus) && (__cplusplus >= 201103L)
#define SDL_ALIGNED(x) alignas(x)
#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
#define SDL_ALIGNED(x) _Alignas(x)
#else
#define SDL_ALIGNED(x) PLEASE_DEFINE_SDL_ALIGNED
#endif
#endif /* SDL_ALIGNED not defined */

View File

@@ -781,7 +781,7 @@ typedef struct SDL_TouchFingerEvent
} SDL_TouchFingerEvent;
/**
* Pressure-sensitive pen proximity event structure (event.pmotion.*)
* Pressure-sensitive pen proximity event structure (event.pproximity.*)
*
* When a pen becomes visible to the system (it is close enough to a tablet,
* etc), SDL will send an SDL_EVENT_PEN_PROXIMITY_IN event with the new pen's
@@ -1567,6 +1567,38 @@ extern SDL_DECLSPEC Uint32 SDLCALL SDL_RegisterEvents(int numevents);
*/
extern SDL_DECLSPEC SDL_Window * SDLCALL SDL_GetWindowFromEvent(const SDL_Event *event);
/**
* Generate a human-readable description of an event.
*
* This will fill `buf` with a null-terminated string that might look
* something like this:
*
* ```
* SDL_EVENT_MOUSE_MOTION (timestamp=1140256324 windowid=2 which=0 state=0 x=492.99 y=139.09 xrel=52 yrel=6)
* ```
*
* The exact format of the string is not guaranteed; it is intended for
* logging purposes, to be read by a human, and not parsed by a computer.
*
* The returned value follows the same rules as SDL_snprintf(): `buf` will
* always be NULL-terminated (unless `buflen` is zero), and will be truncated
* if `buflen` is too small. The return code is the number of bytes needed for
* the complete string, not counting the NULL-terminator, whether the string
* was truncated or not. Unlike SDL_snprintf(), though, this function never
* returns -1.
*
* \param event an event to describe. May be NULL.
* \param buf the buffer to fill with the description string. May be NULL.
* \param buflen the maximum bytes that can be written to `buf`.
* \returns number of bytes needed for the full string, not counting the
* null-terminator byte.
*
* \threadsafety It is safe to call this function from any thread.
*
* \since This function is available since SDL 3.4.0.
*/
extern SDL_DECLSPEC int SDLCALL SDL_GetEventDescription(const SDL_Event *event, char *buf, int buflen);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}

View File

@@ -444,10 +444,10 @@ extern SDL_DECLSPEC bool SDLCALL SDL_GetPathInfo(const char *path, SDL_PathInfo
* Enumerate a directory tree, filtered by pattern, and return a list.
*
* Files are filtered out if they don't match the string in `pattern`, which
* may contain wildcard characters '\*' (match everything) and '?' (match one
* may contain wildcard characters `*` (match everything) and `?` (match one
* character). If pattern is NULL, no filtering is done and all results are
* returned. Subdirectories are permitted, and are specified with a path
* separator of '/'. Wildcard characters '\*' and '?' never match a path
* separator of `/`. Wildcard characters `*` and `?` never match a path
* separator.
*
* `flags` may be set to SDL_GLOB_CASEINSENSITIVE to make the pattern matching

View File

@@ -118,6 +118,7 @@ typedef enum SDL_GamepadType
SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_LEFT,
SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_RIGHT,
SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_PAIR,
SDL_GAMEPAD_TYPE_GAMECUBE,
SDL_GAMEPAD_TYPE_COUNT
} SDL_GamepadType;
@@ -127,8 +128,9 @@ typedef enum SDL_GamepadType
* For controllers that use a diamond pattern for the face buttons, the
* south/east/west/north buttons below correspond to the locations in the
* diamond pattern. For Xbox controllers, this would be A/B/X/Y, for Nintendo
* Switch controllers, this would be B/A/Y/X, for PlayStation controllers this
* would be Cross/Circle/Square/Triangle.
* Switch controllers, this would be B/A/Y/X, for GameCube controllers this
* would be A/X/B/Y, for PlayStation controllers this would be
* Cross/Circle/Square/Triangle.
*
* For controllers that don't use a diamond pattern for the face buttons, the
* south/east/west/north buttons indicate the buttons labeled A, B, C, D, or
@@ -1156,10 +1158,12 @@ extern SDL_DECLSPEC bool SDLCALL SDL_GamepadHasAxis(SDL_Gamepad *gamepad, SDL_Ga
* return a negative value. Note that this differs from the value reported by
* the lower-level SDL_GetJoystickAxis(), which normally uses the full range.
*
* Note that for invalid gamepads or axes, this will return 0. Zero is also a
* valid value in normal operation; usually it means a centered axis.
*
* \param gamepad a gamepad.
* \param axis an axis index (one of the SDL_GamepadAxis values).
* \returns axis state (including 0) on success or 0 (also) on failure; call
* SDL_GetError() for more information.
* \returns axis state.
*
* \since This function is available since SDL 3.2.0.
*

View File

@@ -206,14 +206,20 @@
* underlying graphics API. While it's possible that we have done something
* inefficiently, it's very unlikely especially if you are relatively
* inexperienced with GPU rendering. Please see the performance tips above and
* make sure you are following them. Additionally, tools like RenderDoc can be
* very helpful for diagnosing incorrect behavior and performance issues.
* make sure you are following them. Additionally, tools like
* [RenderDoc](https://renderdoc.org/)
* can be very helpful for diagnosing incorrect behavior and performance
* issues.
*
* ## System Requirements
*
* **Vulkan:** Supported on Windows, Linux, Nintendo Switch, and certain
* Android devices. Requires Vulkan 1.0 with the following extensions and
* device features:
* ### Vulkan
*
* SDL driver name: "vulkan" (for use in SDL_CreateGPUDevice() and
* SDL_PROP_GPU_DEVICE_CREATE_NAME_STRING)
*
* Supported on Windows, Linux, Nintendo Switch, and certain Android devices.
* Requires Vulkan 1.0 with the following extensions and device features:
*
* - `VK_KHR_swapchain`
* - `VK_KHR_maintenance1`
@@ -222,13 +228,21 @@
* - `depthClamp`
* - `shaderClipDistance`
* - `drawIndirectFirstInstance`
* - `sampleRateShading`
*
* **D3D12:** Supported on Windows 10 or newer, Xbox One (GDK), and Xbox
* Series X|S (GDK). Requires a GPU that supports DirectX 12 Feature Level
* 11_1.
* ### D3D12
*
* **Metal:** Supported on macOS 10.14+ and iOS/tvOS 13.0+. Hardware
* requirements vary by operating system:
* SDL driver name: "direct3d12"
*
* Supported on Windows 10 or newer, Xbox One (GDK), and Xbox Series X|S
* (GDK). Requires a GPU that supports DirectX 12 Feature Level 11_1.
*
* ### Metal
*
* SDL driver name: "metal"
*
* Supported on macOS 10.14+ and iOS/tvOS 13.0+. Hardware requirements vary by
* operating system:
*
* - macOS requires an Apple Silicon or
* [Intel Mac2 family](https://developer.apple.com/documentation/metal/mtlfeatureset/mtlfeatureset_macos_gpufamily2_v1?language=objc)
@@ -236,6 +250,26 @@
* - iOS/tvOS requires an A9 GPU or newer
* - iOS Simulator and tvOS Simulator are unsupported
*
* ## Coordinate System
*
* The GPU API uses a left-handed coordinate system, following the convention
* of D3D12 and Metal. Specifically:
*
* - **Normalized Device Coordinates:** The lower-left corner has an x,y
* coordinate of `(-1.0, -1.0)`. The upper-right corner is `(1.0, 1.0)`. Z
* values range from `[0.0, 1.0]` where 0 is the near plane.
* - **Viewport Coordinates:** The top-left corner has an x,y coordinate of
* `(0, 0)` and extends to the bottom-right corner at `(viewportWidth,
* viewportHeight)`. +Y is down.
* - **Texture Coordinates:** The top-left corner has an x,y coordinate of
* `(0, 0)` and extends to the bottom-right corner at `(1.0, 1.0)`. +Y is
* down.
*
* If the backend driver differs from this convention (e.g. Vulkan, which has
* an NDC that assumes +Y is down), SDL will automatically convert the
* coordinate system behind the scenes, so you don't need to perform any
* coordinate flipping logic in your shaders.
*
* ## Uniform Data
*
* Uniforms are for passing data to shaders. The uniform data will be constant
@@ -301,6 +335,39 @@
* unreferenced data in a bound resource without cycling, but overwriting a
* section of data that has already been referenced will produce unexpected
* results.
*
* ## Debugging
*
* At some point of your GPU journey, you will probably encounter issues that
* are not traceable with regular debugger - for example, your code compiles
* but you get an empty screen, or your shader fails in runtime.
*
* For debugging such cases, there are tools that allow visually inspecting
* the whole GPU frame, every drawcall, every bound resource, memory buffers,
* etc. They are the following, per platform:
*
* * For Windows/Linux, use
* [RenderDoc](https://renderdoc.org/)
* * For MacOS (Metal), use Xcode built-in debugger (Open XCode, go to Debug >
* Debug Executable..., select your application, set "GPU Frame Capture" to
* "Metal" in scheme "Options" window, run your app, and click the small
* Metal icon on the bottom to capture a frame)
*
* Aside from that, you may want to enable additional debug layers to receive
* more detailed error messages, based on your GPU backend:
*
* * For D3D12, the debug layer is an optional feature that can be installed
* via "Windows Settings -> System -> Optional features" and adding the
* "Graphics Tools" optional feature.
* * For Vulkan, you will need to install Vulkan SDK on Windows, and on Linux,
* you usually have some sort of `vulkan-validation-layers` system package
* that should be installed.
* * For Metal, it should be enough just to run the application from XCode to
* receive detailed errors or warnings in the output.
*
* Don't hesitate to use tools as RenderDoc when encountering runtime issues
* or unexpected output on screen, quick GPU frame inspection can usually help
* you fix the majority of such problems.
*/
#ifndef SDL_gpu_h_
@@ -1310,6 +1377,17 @@ typedef struct SDL_GPUViewport
* A structure specifying parameters related to transferring data to or from a
* texture.
*
* If either of `pixels_per_row` or `rows_per_layer` is zero, then width and
* height of passed SDL_GPUTextureRegion to SDL_UploadToGPUTexture or
* SDL_DownloadFromGPUTexture are used as default values respectively and data
* is considered to be tightly packed.
*
* **WARNING**: Direct3D 12 requires texture data row pitch to be 256 byte
* aligned, and offsets to be aligned to 512 bytes. If they are not, SDL will
* make a temporary copy of the data that is properly aligned, but this adds
* overhead to the transfer process. Apps can avoid this by aligning their
* data appropriately, or using a different GPU backend than Direct3D 12.
*
* \since This struct is available since SDL 3.2.0.
*
* \sa SDL_UploadToGPUTexture
@@ -1391,7 +1469,7 @@ typedef struct SDL_GPUTextureRegion
*/
typedef struct SDL_GPUBlitRegion
{
SDL_GPUTexture *texture; /**< The texture. */
SDL_GPUTexture *texture; /**< The texture. */
Uint32 mip_level; /**< The mip level index of the region. */
Uint32 layer_or_depth_plane; /**< The layer index or depth plane of the region. This value is treated as a layer index on 2D array and cube textures, and as a depth plane on 3D textures. */
Uint32 x; /**< The left offset of the region. */
@@ -1520,8 +1598,8 @@ typedef struct SDL_GPUSamplerCreateInfo
SDL_GPUCompareOp compare_op; /**< The comparison operator to apply to fetched data before filtering. */
float min_lod; /**< Clamps the minimum of the computed LOD value. */
float max_lod; /**< Clamps the maximum of the computed LOD value. */
bool enable_anisotropy; /**< true to enable anisotropic filtering. */
bool enable_compare; /**< true to enable comparison against a reference value during lookups. */
bool enable_anisotropy; /**< true to enable anisotropic filtering. */
bool enable_compare; /**< true to enable comparison against a reference value during lookups. */
Uint8 padding1;
Uint8 padding2;
@@ -1613,6 +1691,9 @@ typedef struct SDL_GPUStencilOpState
* \since This struct is available since SDL 3.2.0.
*
* \sa SDL_GPUColorTargetDescription
* \sa SDL_GPUBlendFactor
* \sa SDL_GPUBlendOp
* \sa SDL_GPUColorComponentFlags
*/
typedef struct SDL_GPUColorTargetBlendState
{
@@ -1623,8 +1704,8 @@ typedef struct SDL_GPUColorTargetBlendState
SDL_GPUBlendFactor dst_alpha_blendfactor; /**< The value to be multiplied by the destination alpha. */
SDL_GPUBlendOp alpha_blend_op; /**< The blend operation for the alpha component. */
SDL_GPUColorComponentFlags color_write_mask; /**< A bitmask specifying which of the RGBA components are enabled for writing. Writes to all channels if enable_color_write_mask is false. */
bool enable_blend; /**< Whether blending is enabled for the color target. */
bool enable_color_write_mask; /**< Whether the color write mask is enabled. */
bool enable_blend; /**< Whether blending is enabled for the color target. */
bool enable_color_write_mask; /**< Whether the color write mask is enabled. */
Uint8 padding1;
Uint8 padding2;
} SDL_GPUColorTargetBlendState;
@@ -1636,6 +1717,8 @@ typedef struct SDL_GPUColorTargetBlendState
* \since This struct is available since SDL 3.2.0.
*
* \sa SDL_CreateGPUShader
* \sa SDL_GPUShaderFormat
* \sa SDL_GPUShaderStage
*/
typedef struct SDL_GPUShaderCreateInfo
{
@@ -1741,8 +1824,8 @@ typedef struct SDL_GPURasterizerState
float depth_bias_constant_factor; /**< A scalar factor controlling the depth value added to each fragment. */
float depth_bias_clamp; /**< The maximum depth bias of a fragment. */
float depth_bias_slope_factor; /**< A scalar factor applied to a fragment's slope in depth calculations. */
bool enable_depth_bias; /**< true to bias fragment depth values. */
bool enable_depth_clip; /**< true to enable depth clip, false to enable depth clamp. */
bool enable_depth_bias; /**< true to bias fragment depth values. */
bool enable_depth_clip; /**< true to enable depth clip, false to enable depth clamp. */
Uint8 padding1;
Uint8 padding2;
} SDL_GPURasterizerState;
@@ -1759,8 +1842,8 @@ typedef struct SDL_GPUMultisampleState
{
SDL_GPUSampleCount sample_count; /**< The number of samples to be used in rasterization. */
Uint32 sample_mask; /**< Reserved for future use. Must be set to 0. */
bool enable_mask; /**< Reserved for future use. Must be set to false. */
Uint8 padding1;
bool enable_mask; /**< Reserved for future use. Must be set to false. */
bool enable_alpha_to_coverage; /**< true enables the alpha-to-coverage feature. */
Uint8 padding2;
Uint8 padding3;
} SDL_GPUMultisampleState;
@@ -1780,9 +1863,9 @@ typedef struct SDL_GPUDepthStencilState
SDL_GPUStencilOpState front_stencil_state; /**< The stencil op state for front-facing triangles. */
Uint8 compare_mask; /**< Selects the bits of the stencil values participating in the stencil test. */
Uint8 write_mask; /**< Selects the bits of the stencil values updated by the stencil test. */
bool enable_depth_test; /**< true enables the depth test. */
bool enable_depth_write; /**< true enables depth writes. Depth writes are always disabled when enable_depth_test is false. */
bool enable_stencil_test; /**< true enables the stencil test. */
bool enable_depth_test; /**< true enables the depth test. */
bool enable_depth_write; /**< true enables depth writes. Depth writes are always disabled when enable_depth_test is false. */
bool enable_stencil_test; /**< true enables the stencil test. */
Uint8 padding1;
Uint8 padding2;
Uint8 padding3;
@@ -1817,7 +1900,7 @@ typedef struct SDL_GPUGraphicsPipelineTargetInfo
const SDL_GPUColorTargetDescription *color_target_descriptions; /**< A pointer to an array of color target descriptions. */
Uint32 num_color_targets; /**< The number of color target descriptions in the above array. */
SDL_GPUTextureFormat depth_stencil_format; /**< The pixel format of the depth-stencil target. Ignored if has_depth_stencil_target is false. */
bool has_depth_stencil_target; /**< true specifies that the pipeline uses a depth-stencil target. */
bool has_depth_stencil_target; /**< true specifies that the pipeline uses a depth-stencil target. */
Uint8 padding1;
Uint8 padding2;
Uint8 padding3;
@@ -1924,8 +2007,8 @@ typedef struct SDL_GPUColorTargetInfo
SDL_GPUTexture *resolve_texture; /**< The texture that will receive the results of a multisample resolve operation. Ignored if a RESOLVE* store_op is not used. */
Uint32 resolve_mip_level; /**< The mip level of the resolve texture to use for the resolve operation. Ignored if a RESOLVE* store_op is not used. */
Uint32 resolve_layer; /**< The layer index of the resolve texture to use for the resolve operation. Ignored if a RESOLVE* store_op is not used. */
bool cycle; /**< true cycles the texture if the texture is bound and load_op is not LOAD */
bool cycle_resolve_texture; /**< true cycles the resolve texture if the resolve texture is bound. Ignored if a RESOLVE* store_op is not used. */
bool cycle; /**< true cycles the texture if the texture is bound and load_op is not LOAD */
bool cycle_resolve_texture; /**< true cycles the resolve texture if the resolve texture is bound. Ignored if a RESOLVE* store_op is not used. */
Uint8 padding1;
Uint8 padding2;
} SDL_GPUColorTargetInfo;
@@ -1982,7 +2065,7 @@ typedef struct SDL_GPUDepthStencilTargetInfo
SDL_GPUStoreOp store_op; /**< What is done with the depth results of the render pass. */
SDL_GPULoadOp stencil_load_op; /**< What is done with the stencil contents at the beginning of the render pass. */
SDL_GPUStoreOp stencil_store_op; /**< What is done with the stencil results of the render pass. */
bool cycle; /**< true cycles the texture if the texture is bound and any load ops are not LOAD */
bool cycle; /**< true cycles the texture if the texture is bound and any load ops are not LOAD */
Uint8 clear_stencil; /**< The value to clear the stencil component to at the beginning of the render pass. Ignored if SDL_GPU_LOADOP_CLEAR is not used. */
Uint8 padding1;
Uint8 padding2;
@@ -2002,7 +2085,7 @@ typedef struct SDL_GPUBlitInfo {
SDL_FColor clear_color; /**< The color to clear the destination region to before the blit. Ignored if load_op is not SDL_GPU_LOADOP_CLEAR. */
SDL_FlipMode flip_mode; /**< The flip mode for the source region. */
SDL_GPUFilter filter; /**< The filter mode used when blitting. */
bool cycle; /**< true cycles the destination texture if it is already bound. */
bool cycle; /**< true cycles the destination texture if it is already bound. */
Uint8 padding1;
Uint8 padding2;
Uint8 padding3;
@@ -2111,6 +2194,13 @@ extern SDL_DECLSPEC bool SDLCALL SDL_GPUSupportsProperties(
/**
* Creates a GPU context.
*
* The GPU driver name can be one of the following:
*
* - "vulkan": [Vulkan](CategoryGPU#vulkan)
* - "direct3d12": [D3D12](CategoryGPU#d3d12)
* - "metal": [Metal](CategoryGPU#metal)
* - NULL: let SDL pick the optimal driver
*
* \param format_flags a bitflag indicating which shader formats the app is
* able to provide.
* \param debug_mode enable debug mode properties and validations.
@@ -2121,6 +2211,7 @@ extern SDL_DECLSPEC bool SDLCALL SDL_GPUSupportsProperties(
*
* \since This function is available since SDL 3.2.0.
*
* \sa SDL_CreateGPUDeviceWithProperties
* \sa SDL_GetGPUShaderFormats
* \sa SDL_GetGPUDeviceDriver
* \sa SDL_DestroyGPUDevice
@@ -2140,6 +2231,8 @@ extern SDL_DECLSPEC SDL_GPUDevice * SDLCALL SDL_CreateGPUDevice(
* properties and validations, defaults to true.
* - `SDL_PROP_GPU_DEVICE_CREATE_PREFERLOWPOWER_BOOLEAN`: enable to prefer
* energy efficiency over maximum GPU performance, defaults to false.
* - `SDL_PROP_GPU_DEVICE_CREATE_VERBOSE_BOOLEAN`: enable to automatically log
* useful debug information on device creation, defaults to true.
* - `SDL_PROP_GPU_DEVICE_CREATE_NAME_STRING`: the name of the GPU driver to
* use, if a specific one is desired.
*
@@ -2163,6 +2256,25 @@ extern SDL_DECLSPEC SDL_GPUDevice * SDLCALL SDL_CreateGPUDevice(
* - `SDL_PROP_GPU_DEVICE_CREATE_D3D12_SEMANTIC_NAME_STRING`: the prefix to
* use for all vertex semantics, default is "TEXCOORD".
*
* With the Vulkan renderer:
*
* - `SDL_PROP_GPU_DEVICE_CREATE_VULKAN_SHADERCLIPDISTANCE_BOOLEAN`: Enable
* device feature shaderClipDistance. If disabled, clip distances are not
* supported in shader code: gl_ClipDistance[] built-ins of GLSL,
* SV_ClipDistance0/1 semantics of HLSL and [[clip_distance]] attribute of
* Metal. Defaults to true.
* - `SDL_PROP_GPU_DEVICE_CREATE_VULKAN_DEPTHCLAMP_BOOLEAN`: Enable device
* feature depthClamp. If disabled, there is no depth clamp support and
* enable_depth_clip in SDL_GPURasterizerState must always be set to true.
* Defaults to true.
* - `SDL_PROP_GPU_DEVICE_CREATE_VULKAN_DRAWINDIRECTFIRST_BOOLEAN`: Enable
* device feature drawIndirectFirstInstance. If disabled, the argument
* first_instance of SDL_GPUIndirectDrawCommand must be set to zero.
* Defaults to true.
* - `SDL_PROP_GPU_DEVICE_CREATE_VULKAN_SAMPLERANISOTROPY_BOOLEAN`: Enable
* device feature samplerAnisotropy. If disabled, enable_anisotropy of
* SDL_GPUSamplerCreateInfo must be set to false. Defaults to true.
*
* \param props the properties to use.
* \returns a GPU context on success or NULL on failure; call SDL_GetError()
* for more information.
@@ -2177,16 +2289,21 @@ extern SDL_DECLSPEC SDL_GPUDevice * SDLCALL SDL_CreateGPUDevice(
extern SDL_DECLSPEC SDL_GPUDevice * SDLCALL SDL_CreateGPUDeviceWithProperties(
SDL_PropertiesID props);
#define SDL_PROP_GPU_DEVICE_CREATE_DEBUGMODE_BOOLEAN "SDL.gpu.device.create.debugmode"
#define SDL_PROP_GPU_DEVICE_CREATE_PREFERLOWPOWER_BOOLEAN "SDL.gpu.device.create.preferlowpower"
#define SDL_PROP_GPU_DEVICE_CREATE_NAME_STRING "SDL.gpu.device.create.name"
#define SDL_PROP_GPU_DEVICE_CREATE_SHADERS_PRIVATE_BOOLEAN "SDL.gpu.device.create.shaders.private"
#define SDL_PROP_GPU_DEVICE_CREATE_SHADERS_SPIRV_BOOLEAN "SDL.gpu.device.create.shaders.spirv"
#define SDL_PROP_GPU_DEVICE_CREATE_SHADERS_DXBC_BOOLEAN "SDL.gpu.device.create.shaders.dxbc"
#define SDL_PROP_GPU_DEVICE_CREATE_SHADERS_DXIL_BOOLEAN "SDL.gpu.device.create.shaders.dxil"
#define SDL_PROP_GPU_DEVICE_CREATE_SHADERS_MSL_BOOLEAN "SDL.gpu.device.create.shaders.msl"
#define SDL_PROP_GPU_DEVICE_CREATE_SHADERS_METALLIB_BOOLEAN "SDL.gpu.device.create.shaders.metallib"
#define SDL_PROP_GPU_DEVICE_CREATE_D3D12_SEMANTIC_NAME_STRING "SDL.gpu.device.create.d3d12.semantic"
#define SDL_PROP_GPU_DEVICE_CREATE_DEBUGMODE_BOOLEAN "SDL.gpu.device.create.debugmode"
#define SDL_PROP_GPU_DEVICE_CREATE_PREFERLOWPOWER_BOOLEAN "SDL.gpu.device.create.preferlowpower"
#define SDL_PROP_GPU_DEVICE_CREATE_VERBOSE_BOOLEAN "SDL.gpu.device.create.verbose"
#define SDL_PROP_GPU_DEVICE_CREATE_NAME_STRING "SDL.gpu.device.create.name"
#define SDL_PROP_GPU_DEVICE_CREATE_SHADERS_PRIVATE_BOOLEAN "SDL.gpu.device.create.shaders.private"
#define SDL_PROP_GPU_DEVICE_CREATE_SHADERS_SPIRV_BOOLEAN "SDL.gpu.device.create.shaders.spirv"
#define SDL_PROP_GPU_DEVICE_CREATE_SHADERS_DXBC_BOOLEAN "SDL.gpu.device.create.shaders.dxbc"
#define SDL_PROP_GPU_DEVICE_CREATE_SHADERS_DXIL_BOOLEAN "SDL.gpu.device.create.shaders.dxil"
#define SDL_PROP_GPU_DEVICE_CREATE_SHADERS_MSL_BOOLEAN "SDL.gpu.device.create.shaders.msl"
#define SDL_PROP_GPU_DEVICE_CREATE_SHADERS_METALLIB_BOOLEAN "SDL.gpu.device.create.shaders.metallib"
#define SDL_PROP_GPU_DEVICE_CREATE_D3D12_SEMANTIC_NAME_STRING "SDL.gpu.device.create.d3d12.semantic"
#define SDL_PROP_GPU_DEVICE_CREATE_VULKAN_SHADERCLIPDISTANCE_BOOLEAN "SDL.gpu.device.create.vulkan.shaderclipdistance"
#define SDL_PROP_GPU_DEVICE_CREATE_VULKAN_DEPTHCLAMP_BOOLEAN "SDL.gpu.device.create.vulkan.depthclamp"
#define SDL_PROP_GPU_DEVICE_CREATE_VULKAN_DRAWINDIRECTFIRST_BOOLEAN "SDL.gpu.device.create.vulkan.drawindirectfirstinstance"
#define SDL_PROP_GPU_DEVICE_CREATE_VULKAN_SAMPLERANISOTROPY_BOOLEAN "SDL.gpu.device.create.vulkan.sampleranisotropy"
/**
* Destroys a GPU context previously returned by SDL_CreateGPUDevice.
@@ -2250,6 +2367,116 @@ extern SDL_DECLSPEC const char * SDLCALL SDL_GetGPUDeviceDriver(SDL_GPUDevice *d
*/
extern SDL_DECLSPEC SDL_GPUShaderFormat SDLCALL SDL_GetGPUShaderFormats(SDL_GPUDevice *device);
/**
* Get the properties associated with a GPU device.
*
* All properties are optional and may differ between GPU backends and SDL
* versions.
*
* The following properties are provided by SDL:
*
* `SDL_PROP_GPU_DEVICE_NAME_STRING`: Contains the name of the underlying
* device as reported by the system driver. This string has no standardized
* format, is highly inconsistent between hardware devices and drivers, and is
* able to change at any time. Do not attempt to parse this string as it is
* bound to fail at some point in the future when system drivers are updated,
* new hardware devices are introduced, or when SDL adds new GPU backends or
* modifies existing ones.
*
* Strings that have been found in the wild include:
*
* - GTX 970
* - GeForce GTX 970
* - NVIDIA GeForce GTX 970
* - Microsoft Direct3D12 (NVIDIA GeForce GTX 970)
* - NVIDIA Graphics Device
* - GeForce GPU
* - P106-100
* - AMD 15D8:C9
* - AMD Custom GPU 0405
* - AMD Radeon (TM) Graphics
* - ASUS Radeon RX 470 Series
* - Intel(R) Arc(tm) A380 Graphics (DG2)
* - Virtio-GPU Venus (NVIDIA TITAN V)
* - SwiftShader Device (LLVM 16.0.0)
* - llvmpipe (LLVM 15.0.4, 256 bits)
* - Microsoft Basic Render Driver
* - unknown device
*
* The above list shows that the same device can have different formats, the
* vendor name may or may not appear in the string, the included vendor name
* may not be the vendor of the chipset on the device, some manufacturers
* include pseudo-legal marks while others don't, some devices may not use a
* marketing name in the string, the device string may be wrapped by the name
* of a translation interface, the device may be emulated in software, or the
* string may contain generic text that does not identify the device at all.
*
* `SDL_PROP_GPU_DEVICE_DRIVER_NAME_STRING`: Contains the self-reported name
* of the underlying system driver.
*
* Strings that have been found in the wild include:
*
* - Intel Corporation
* - Intel open-source Mesa driver
* - Qualcomm Technologies Inc. Adreno Vulkan Driver
* - MoltenVK
* - Mali-G715
* - venus
*
* `SDL_PROP_GPU_DEVICE_DRIVER_VERSION_STRING`: Contains the self-reported
* version of the underlying system driver. This is a relatively short version
* string in an unspecified format. If SDL_PROP_GPU_DEVICE_DRIVER_INFO_STRING
* is available then that property should be preferred over this one as it may
* contain additional information that is useful for identifying the exact
* driver version used.
*
* Strings that have been found in the wild include:
*
* - 53.0.0
* - 0.405.2463
* - 32.0.15.6614
*
* `SDL_PROP_GPU_DEVICE_DRIVER_INFO_STRING`: Contains the detailed version
* information of the underlying system driver as reported by the driver. This
* is an arbitrary string with no standardized format and it may contain
* newlines. This property should be preferred over
* SDL_PROP_GPU_DEVICE_DRIVER_VERSION_STRING if it is available as it usually
* contains the same information but in a format that is easier to read.
*
* Strings that have been found in the wild include:
*
* - 101.6559
* - 1.2.11
* - Mesa 21.2.2 (LLVM 12.0.1)
* - Mesa 22.2.0-devel (git-f226222 2022-04-14 impish-oibaf-ppa)
* - v1.r53p0-00eac0.824c4f31403fb1fbf8ee1042422c2129
*
* This string has also been observed to be a multiline string (which has a
* trailing newline):
*
* ```
* Driver Build: 85da404, I46ff5fc46f, 1606794520
* Date: 11/30/20
* Compiler Version: EV031.31.04.01
* Driver Branch: promo490_3_Google
* ```
*
* \param device a GPU context to query.
* \returns a valid property ID on success or 0 on failure; call
* SDL_GetError() for more information.
*
* \threadsafety It is safe to call this function from any thread.
*
* \since This function is available since SDL 3.4.0.
*/
extern SDL_DECLSPEC SDL_PropertiesID SDLCALL SDL_GetGPUDeviceProperties(SDL_GPUDevice *device);
#define SDL_PROP_GPU_DEVICE_NAME_STRING "SDL.gpu.device.name"
#define SDL_PROP_GPU_DEVICE_DRIVER_NAME_STRING "SDL.gpu.device.driver_name"
#define SDL_PROP_GPU_DEVICE_DRIVER_VERSION_STRING "SDL.gpu.device.driver_version"
#define SDL_PROP_GPU_DEVICE_DRIVER_INFO_STRING "SDL.gpu.device.driver_info"
/* State Creation */
/**
@@ -2822,6 +3049,9 @@ extern SDL_DECLSPEC SDL_GPUCommandBuffer * SDLCALL SDL_AcquireGPUCommandBuffer(
* terms this means you must ensure that vec3 and vec4 fields are 16-byte
* aligned.
*
* For detailed information about accessing uniform data from a shader, please
* refer to SDL_CreateGPUShader.
*
* \param command_buffer a command buffer.
* \param slot_index the vertex uniform slot to push data to.
* \param data client data to write.
@@ -3775,7 +4005,7 @@ extern SDL_DECLSPEC void SDLCALL SDL_ReleaseWindowFromGPUDevice(
* supported via SDL_WindowSupportsGPUPresentMode /
* SDL_WindowSupportsGPUSwapchainComposition prior to calling this function.
*
* SDL_GPU_PRESENTMODE_VSYNC with SDL_GPU_SWAPCHAINCOMPOSITION_SDR are always
* SDL_GPU_PRESENTMODE_VSYNC with SDL_GPU_SWAPCHAINCOMPOSITION_SDR is always
* supported.
*
* \param device a GPU context.
@@ -3849,7 +4079,9 @@ extern SDL_DECLSPEC SDL_GPUTextureFormat SDLCALL SDL_GetGPUSwapchainTextureForma
* buffer used to acquire it.
*
* This function will fill the swapchain texture handle with NULL if too many
* frames are in flight. This is not an error.
* frames are in flight. This is not an error. This NULL pointer should not be
* passed back into SDL. Instead, it should be considered as an indication to
* wait until the swapchain is available.
*
* If you use this function, it is possible to create a situation where many
* command buffers are allocated while the rendering context waits for the GPU
@@ -4211,3 +4443,8 @@ extern SDL_DECLSPEC void SDLCALL SDL_GDKResumeGPU(SDL_GPUDevice *device);
#include <SDL3/SDL_close_code.h>
#endif /* SDL_gpu_h_ */

View File

@@ -70,7 +70,7 @@
* {
* SDL_Haptic *haptic;
* SDL_HapticEffect effect;
* int effect_id;
* SDL_HapticEffectID effect_id;
*
* // Open the device
* haptic = SDL_OpenHapticFromJoystick(joystick);
@@ -149,6 +149,19 @@ extern "C" {
*/
typedef struct SDL_Haptic SDL_Haptic;
/*
* Misc defines.
*/
/**
* Used to play a device an infinite number of times.
*
* \since This macro is available since SDL 3.2.0.
*
* \sa SDL_RunHapticEffect
*/
#define SDL_HAPTIC_INFINITY 4294967295U
/**
* \name Haptic features
@@ -162,6 +175,11 @@ typedef struct SDL_Haptic SDL_Haptic;
*/
/* @{ */
/**
* Type of haptic effect.
*/
typedef Uint16 SDL_HapticEffectType;
/**
* Constant effect supported.
*
@@ -383,6 +401,11 @@ typedef struct SDL_Haptic SDL_Haptic;
*/
/* @{ */
/**
* Type of coordinates used for haptic direction.
*/
typedef Uint8 SDL_HapticDirectionType;
/**
* Uses polar coordinates for the direction.
*
@@ -426,18 +449,15 @@ typedef struct SDL_Haptic SDL_Haptic;
/* @} *//* Haptic features */
/*
* Misc defines.
*/
/**
* Used to play a device an infinite number of times.
* ID for haptic effects.
*
* \since This macro is available since SDL 3.2.0.
* This is -1 if the ID is invalid.
*
* \sa SDL_RunHapticEffect
* \sa SDL_CreateHapticEffect
*/
#define SDL_HAPTIC_INFINITY 4294967295U
typedef int SDL_HapticEffectID;
/**
@@ -545,8 +565,8 @@ typedef struct SDL_Haptic SDL_Haptic;
*/
typedef struct SDL_HapticDirection
{
Uint8 type; /**< The type of encoding. */
Sint32 dir[3]; /**< The encoded direction. */
SDL_HapticDirectionType type; /**< The type of encoding. */
Sint32 dir[3]; /**< The encoded direction. */
} SDL_HapticDirection;
@@ -566,7 +586,7 @@ typedef struct SDL_HapticDirection
typedef struct SDL_HapticConstant
{
/* Header */
Uint16 type; /**< SDL_HAPTIC_CONSTANT */
SDL_HapticEffectType type; /**< SDL_HAPTIC_CONSTANT */
SDL_HapticDirection direction; /**< Direction of the effect. */
/* Replay */
@@ -652,9 +672,9 @@ typedef struct SDL_HapticConstant
typedef struct SDL_HapticPeriodic
{
/* Header */
Uint16 type; /**< SDL_HAPTIC_SINE, SDL_HAPTIC_SQUARE
SDL_HAPTIC_TRIANGLE, SDL_HAPTIC_SAWTOOTHUP or
SDL_HAPTIC_SAWTOOTHDOWN */
SDL_HapticEffectType type; /**< SDL_HAPTIC_SINE, SDL_HAPTIC_SQUARE
SDL_HAPTIC_TRIANGLE, SDL_HAPTIC_SAWTOOTHUP or
SDL_HAPTIC_SAWTOOTHDOWN */
SDL_HapticDirection direction; /**< Direction of the effect. */
/* Replay */
@@ -708,8 +728,8 @@ typedef struct SDL_HapticPeriodic
typedef struct SDL_HapticCondition
{
/* Header */
Uint16 type; /**< SDL_HAPTIC_SPRING, SDL_HAPTIC_DAMPER,
SDL_HAPTIC_INERTIA or SDL_HAPTIC_FRICTION */
SDL_HapticEffectType type; /**< SDL_HAPTIC_SPRING, SDL_HAPTIC_DAMPER,
SDL_HAPTIC_INERTIA or SDL_HAPTIC_FRICTION */
SDL_HapticDirection direction; /**< Direction of the effect. */
/* Replay */
@@ -747,7 +767,7 @@ typedef struct SDL_HapticCondition
typedef struct SDL_HapticRamp
{
/* Header */
Uint16 type; /**< SDL_HAPTIC_RAMP */
SDL_HapticEffectType type; /**< SDL_HAPTIC_RAMP */
SDL_HapticDirection direction; /**< Direction of the effect. */
/* Replay */
@@ -786,7 +806,7 @@ typedef struct SDL_HapticRamp
typedef struct SDL_HapticLeftRight
{
/* Header */
Uint16 type; /**< SDL_HAPTIC_LEFTRIGHT */
SDL_HapticEffectType type; /**< SDL_HAPTIC_LEFTRIGHT */
/* Replay */
Uint32 length; /**< Duration of the effect in milliseconds. */
@@ -816,7 +836,7 @@ typedef struct SDL_HapticLeftRight
typedef struct SDL_HapticCustom
{
/* Header */
Uint16 type; /**< SDL_HAPTIC_CUSTOM */
SDL_HapticEffectType type; /**< SDL_HAPTIC_CUSTOM */
SDL_HapticDirection direction; /**< Direction of the effect. */
/* Replay */
@@ -915,7 +935,7 @@ typedef struct SDL_HapticCustom
typedef union SDL_HapticEffect
{
/* Common for all force feedback effects */
Uint16 type; /**< Effect type. */
SDL_HapticEffectType type; /**< Effect type. */
SDL_HapticConstant constant; /**< Constant effect. */
SDL_HapticPeriodic periodic; /**< Periodic effect. */
SDL_HapticCondition condition; /**< Condition effect. */
@@ -1193,7 +1213,7 @@ extern SDL_DECLSPEC bool SDLCALL SDL_HapticEffectSupported(SDL_Haptic *haptic, c
* \sa SDL_RunHapticEffect
* \sa SDL_UpdateHapticEffect
*/
extern SDL_DECLSPEC int SDLCALL SDL_CreateHapticEffect(SDL_Haptic *haptic, const SDL_HapticEffect *effect);
extern SDL_DECLSPEC SDL_HapticEffectID SDLCALL SDL_CreateHapticEffect(SDL_Haptic *haptic, const SDL_HapticEffect *effect);
/**
* Update the properties of an effect.
@@ -1215,7 +1235,7 @@ extern SDL_DECLSPEC int SDLCALL SDL_CreateHapticEffect(SDL_Haptic *haptic, const
* \sa SDL_CreateHapticEffect
* \sa SDL_RunHapticEffect
*/
extern SDL_DECLSPEC bool SDLCALL SDL_UpdateHapticEffect(SDL_Haptic *haptic, int effect, const SDL_HapticEffect *data);
extern SDL_DECLSPEC bool SDLCALL SDL_UpdateHapticEffect(SDL_Haptic *haptic, SDL_HapticEffectID effect, const SDL_HapticEffect *data);
/**
* Run the haptic effect on its associated haptic device.
@@ -1239,7 +1259,7 @@ extern SDL_DECLSPEC bool SDLCALL SDL_UpdateHapticEffect(SDL_Haptic *haptic, int
* \sa SDL_StopHapticEffect
* \sa SDL_StopHapticEffects
*/
extern SDL_DECLSPEC bool SDLCALL SDL_RunHapticEffect(SDL_Haptic *haptic, int effect, Uint32 iterations);
extern SDL_DECLSPEC bool SDLCALL SDL_RunHapticEffect(SDL_Haptic *haptic, SDL_HapticEffectID effect, Uint32 iterations);
/**
* Stop the haptic effect on its associated haptic device.
@@ -1254,7 +1274,7 @@ extern SDL_DECLSPEC bool SDLCALL SDL_RunHapticEffect(SDL_Haptic *haptic, int eff
* \sa SDL_RunHapticEffect
* \sa SDL_StopHapticEffects
*/
extern SDL_DECLSPEC bool SDLCALL SDL_StopHapticEffect(SDL_Haptic *haptic, int effect);
extern SDL_DECLSPEC bool SDLCALL SDL_StopHapticEffect(SDL_Haptic *haptic, SDL_HapticEffectID effect);
/**
* Destroy a haptic effect on the device.
@@ -1269,7 +1289,7 @@ extern SDL_DECLSPEC bool SDLCALL SDL_StopHapticEffect(SDL_Haptic *haptic, int ef
*
* \sa SDL_CreateHapticEffect
*/
extern SDL_DECLSPEC void SDLCALL SDL_DestroyHapticEffect(SDL_Haptic *haptic, int effect);
extern SDL_DECLSPEC void SDLCALL SDL_DestroyHapticEffect(SDL_Haptic *haptic, SDL_HapticEffectID effect);
/**
* Get the status of the current effect on the specified haptic device.
@@ -1285,7 +1305,7 @@ extern SDL_DECLSPEC void SDLCALL SDL_DestroyHapticEffect(SDL_Haptic *haptic, int
*
* \sa SDL_GetHapticFeatures
*/
extern SDL_DECLSPEC bool SDLCALL SDL_GetHapticEffectStatus(SDL_Haptic *haptic, int effect);
extern SDL_DECLSPEC bool SDLCALL SDL_GetHapticEffectStatus(SDL_Haptic *haptic, SDL_HapticEffectID effect);
/**
* Set the global gain of the specified haptic device.

View File

@@ -711,8 +711,6 @@ extern "C" {
*
* This hint only applies to the emscripten platform.
*
* The default value is "#canvas"
*
* This hint should be set before creating a window.
*
* \since This hint is available since SDL 3.2.0.
@@ -726,7 +724,7 @@ extern "C" {
*
* The variable can be one of:
*
* - "#window": the javascript window object (default)
* - "#window": the javascript window object
* - "#document": the javascript document object
* - "#screen": the javascript window.screen object
* - "#canvas": the WebGL canvas element
@@ -1723,6 +1721,43 @@ extern "C" {
*/
#define SDL_HINT_JOYSTICK_HIDAPI_STEAM_HORI "SDL_JOYSTICK_HIDAPI_STEAM_HORI"
/**
* A variable controlling whether the HIDAPI driver for some Logitech wheels
* should be used.
*
* This variable can be set to the following values:
*
* - "0": HIDAPI driver is not used
* - "1": HIDAPI driver is used
*
* The default is the value of SDL_HINT_JOYSTICK_HIDAPI
*/
#define SDL_HINT_JOYSTICK_HIDAPI_LG4FF "SDL_JOYSTICK_HIDAPI_LG4FF"
/**
* A variable controlling whether the HIDAPI driver for 8BitDo controllers
* should be used.
*
* This variable can be set to the following values:
*
* "0" - HIDAPI driver is not used. "1" - HIDAPI driver is used.
*
* The default is the value of SDL_HINT_JOYSTICK_HIDAPI
*/
#define SDL_HINT_JOYSTICK_HIDAPI_8BITDO "SDL_JOYSTICK_HIDAPI_8BITDO"
/**
* A variable controlling whether the HIDAPI driver for Flydigi controllers
* should be used.
*
* This variable can be set to the following values:
*
* "0" - HIDAPI driver is not used. "1" - HIDAPI driver is used.
*
* The default is the value of SDL_HINT_JOYSTICK_HIDAPI
*/
#define SDL_HINT_JOYSTICK_HIDAPI_FLYDIGI "SDL_JOYSTICK_HIDAPI_FLYDIGI"
/**
* A variable controlling whether the HIDAPI driver for Nintendo Switch
* controllers should be used.
@@ -1926,6 +1961,41 @@ extern "C" {
*/
#define SDL_HINT_JOYSTICK_HIDAPI_XBOX_ONE_HOME_LED "SDL_JOYSTICK_HIDAPI_XBOX_ONE_HOME_LED"
/**
* A variable controlling whether the new HIDAPI driver for wired Xbox One
* (GIP) controllers should be used.
*
* The variable can be set to the following values:
*
* - "0": HIDAPI driver is not used.
* - "1": HIDAPI driver is used.
*
* The default is the value of SDL_HINT_JOYSTICK_HIDAPI_XBOX_ONE.
*
* This hint should be set before initializing joysticks and gamepads.
*
* \since This hint is available since SDL 3.4.0.
*/
#define SDL_HINT_JOYSTICK_HIDAPI_GIP "SDL_JOYSTICK_HIDAPI_GIP"
/**
* A variable controlling whether the new HIDAPI driver for wired Xbox One
* (GIP) controllers should reset the controller if it can't get the metadata
* from the controller.
*
* The variable can be set to the following values:
*
* - "0": Assume this is a generic controller.
* - "1": Reset the controller to get metadata.
*
* By default the controller is not reset.
*
* This hint should be set before initializing joysticks and gamepads.
*
* \since This hint is available since SDL 3.4.0.
*/
#define SDL_HINT_JOYSTICK_HIDAPI_GIP_RESET_FOR_METADATA "SDL_JOYSTICK_HIDAPI_GIP_RESET_FOR_METADATA"
/**
* A variable controlling whether IOKit should be used for controller
* handling.
@@ -3407,6 +3477,26 @@ extern "C" {
*/
#define SDL_HINT_VIDEO_MAC_FULLSCREEN_MENU_VISIBILITY "SDL_VIDEO_MAC_FULLSCREEN_MENU_VISIBILITY"
/**
* A variable controlling whether SDL will attempt to automatically set the
* destination display to a mode most closely matching that of the previous
* display if an exclusive fullscreen window is moved onto it.
*
* The variable can be set to the following values:
*
* - "0": SDL will not attempt to automatically set a matching mode on the
* destination display. If an exclusive fullscreen window is moved to a new
* display, the window will become fullscreen desktop.
* - "1": SDL will attempt to automatically set a mode on the destination
* display that most closely matches the mode of the display that the
* exclusive fullscreen window was previously on. (default)
*
* This hint can be set anytime.
*
* \since This hint is available since SDL 3.4.0.
*/
#define SDL_HINT_VIDEO_MATCH_EXCLUSIVE_MODE_ON_MOVE "SDL_VIDEO_MATCH_EXCLUSIVE_MODE_ON_MOVE"
/**
* A variable controlling whether fullscreen windows are minimized when they
* lose focus.

View File

@@ -101,7 +101,7 @@ typedef Uint32 SDL_InitFlags;
* to run.
*
* See
* [Main callbacks in SDL3](https://wiki.libsdl.org/SDL3/README/main-functions#main-callbacks-in-sdl3)
* [Main callbacks in SDL3](https://wiki.libsdl.org/SDL3/README-main-functions#main-callbacks-in-sdl3)
* for complete details.
*
* \since This enum is available since SDL 3.2.0.

View File

@@ -107,6 +107,10 @@ typedef Uint32 SDL_JoystickID;
* This is by no means a complete list of everything that can be plugged into
* a computer.
*
* You may refer to
* [XInput Controller Types](https://learn.microsoft.com/en-us/windows/win32/xinput/xinput-and-controller-subtypes)
* table for a general understanding of each joystick type.
*
* \since This enum is available since SDL 3.2.0.
*/
typedef enum SDL_JoystickType

View File

@@ -206,6 +206,9 @@ extern SDL_DECLSPEC void SDLCALL SDL_ResetLogPriorities(void);
* SDL_LOG_PRIORITY_WARN and higher have a prefix showing their priority, e.g.
* "WARNING: ".
*
* This function makes a copy of its string argument, **prefix**, so it is not
* necessary to keep the value of **prefix** alive after the call returns.
*
* \param priority the SDL_LogPriority to modify.
* \param prefix the prefix to use for that log priority, or NULL to use no
* prefix.

View File

@@ -47,7 +47,7 @@
*
* For more information, see:
*
* https://wiki.libsdl.org/SDL3/README/main-functions
* https://wiki.libsdl.org/SDL3/README-main-functions
*/
#ifndef SDL_main_h_
@@ -68,7 +68,7 @@
* proper entry point for the platform, and all the other magic details
* needed, like manually calling SDL_SetMainReady.
*
* Please see [README/main-functions](README/main-functions), (or
* Please see [README-main-functions](README-main-functions), (or
* docs/README-main-functions.md in the source tree) for a more detailed
* explanation.
*
@@ -85,7 +85,7 @@
* SDL_AppQuit. The app should not provide a `main` function in this case, and
* doing so will likely cause the build to fail.
*
* Please see [README/main-functions](README/main-functions), (or
* Please see [README-main-functions](README-main-functions), (or
* docs/README-main-functions.md in the source tree) for a more detailed
* explanation.
*
@@ -347,10 +347,10 @@ extern SDLMAIN_DECLSPEC SDL_AppResult SDLCALL SDL_AppInit(void **appstate, int a
* Apps implement this function when using SDL_MAIN_USE_CALLBACKS. If using a
* standard "main" function, you should not supply this.
*
* This function is called repeatedly by SDL after SDL_AppInit returns 0. The
* function should operate as a single iteration the program's primary loop;
* it should update whatever state it needs and draw a new frame of video,
* usually.
* This function is called repeatedly by SDL after SDL_AppInit returns
* SDL_APP_CONTINUE. The function should operate as a single iteration the
* program's primary loop; it should update whatever state it needs and draw a
* new frame of video, usually.
*
* On some platforms, this function will be called at the refresh rate of the
* display (which might change during the life of your app!). There are no
@@ -512,7 +512,7 @@ typedef int (SDLCALL *SDL_main_func)(int argc, char *argv[]);
* SDL_MAIN_USE_CALLBACKS.
*
* Program startup is a surprisingly complex topic. Please see
* [README/main-functions](README/main-functions), (or
* [README-main-functions](README-main-functions), (or
* docs/README-main-functions.md in the source tree) for a more detailed
* explanation.
*
@@ -618,8 +618,8 @@ extern SDL_DECLSPEC int SDLCALL SDL_EnterAppMainCallbacks(int argc, char *argv[]
* \param name the window class name, in UTF-8 encoding. If NULL, SDL
* currently uses "SDL_app" but this isn't guaranteed.
* \param style the value to use in WNDCLASSEX::style. If `name` is NULL, SDL
* currently uses `(CS_BYTEALIGNCLIENT | CS_OWNDC)` regardless of
* what is specified here.
* currently uses `(CS_BYTEALIGNCLIENT \| CS_OWNDC)` regardless
* of what is specified here.
* \param hInst the HINSTANCE to use in WNDCLASSEX::hInstance. If zero, SDL
* will use `GetModuleHandle(NULL)` instead.
* \returns true on success or false on failure; call SDL_GetError() for more

View File

@@ -160,6 +160,44 @@ typedef Uint32 SDL_MouseButtonFlags;
#define SDL_BUTTON_X1MASK SDL_BUTTON_MASK(SDL_BUTTON_X1)
#define SDL_BUTTON_X2MASK SDL_BUTTON_MASK(SDL_BUTTON_X2)
/**
* A callback used to transform mouse motion delta from raw values.
*
* This is called during SDL's handling of platform mouse events to scale the
* values of the resulting motion delta.
*
* \param userdata what was passed as `userdata` to
* SDL_SetRelativeMouseTransform().
* \param timestamp the associated time at which this mouse motion event was
* received.
* \param window the associated window to which this mouse motion event was
* addressed.
* \param mouseID the associated mouse from which this mouse motion event was
* emitted.
* \param x pointer to a variable that will be treated as the resulting x-axis
* motion.
* \param y pointer to a variable that will be treated as the resulting y-axis
* motion.
*
* \threadsafety This callback is called by SDL's internal mouse input
* processing procedure, which may be a thread separate from the
* main event loop that is run at realtime priority. Stalling
* this thread with too much work in the callback can therefore
* potentially freeze the entire system. Care should be taken
* with proper synchronization practices when adding other side
* effects beyond mutation of the x and y values.
*
* \since This datatype is available since SDL 3.4.0.
*
* \sa SDL_SetRelativeMouseTransform
*/
typedef void (SDLCALL *SDL_MouseMotionTransformCallback)(
void *userdata,
Uint64 timestamp,
SDL_Window *window,
SDL_MouseID mouseID,
float *x, float *y
);
/* Function prototypes */
@@ -380,6 +418,24 @@ extern SDL_DECLSPEC void SDLCALL SDL_WarpMouseInWindow(SDL_Window *window,
*/
extern SDL_DECLSPEC bool SDLCALL SDL_WarpMouseGlobal(float x, float y);
/**
* Set a user-defined function by which to transform relative mouse inputs.
*
* This overrides the relative system scale and relative speed scale hints.
* Should be called prior to enabling relative mouse mode, fails otherwise.
*
* \param callback a callback used to transform relative mouse motion, or NULL
* for default behavior.
* \param userdata a pointer that will be passed to `callback`.
* \returns true on success or false on failure; call SDL_GetError() for more
* information.
*
* \threadsafety This function should only be called on the main thread.
*
* \since This function is available since SDL 3.4.0.
*/
extern SDL_DECLSPEC bool SDLCALL SDL_SetRelativeMouseTransform(SDL_MouseMotionTransformCallback callback, void *userdata);
/**
* Set relative mouse mode for a window.
*
@@ -522,15 +578,16 @@ extern SDL_DECLSPEC SDL_Cursor * SDLCALL SDL_CreateCursor(const Uint8 *data,
/**
* Create a color cursor.
*
* If this function is passed a surface with alternate representations, the
* surface will be interpreted as the content to be used for 100% display
* scale, and the alternate representations will be used for high DPI
* situations. For example, if the original surface is 32x32, then on a 2x
* macOS display or 200% display scale on Windows, a 64x64 version of the
* image will be used, if available. If a matching version of the image isn't
* available, the closest larger size image will be downscaled to the
* appropriate size and be used instead, if available. Otherwise, the closest
* smaller image will be upscaled and be used instead.
* If this function is passed a surface with alternate representations added
* with SDL_AddSurfaceAlternateImage(), the surface will be interpreted as the
* content to be used for 100% display scale, and the alternate
* representations will be used for high DPI situations. For example, if the
* original surface is 32x32, then on a 2x macOS display or 200% display scale
* on Windows, a 64x64 version of the image will be used, if available. If a
* matching version of the image isn't available, the closest larger size
* image will be downscaled to the appropriate size and be used instead, if
* available. Otherwise, the closest smaller image will be upscaled and be
* used instead.
*
* \param surface an SDL_Surface structure representing the cursor image.
* \param hot_x the x position of the cursor hot spot.
@@ -542,6 +599,7 @@ extern SDL_DECLSPEC SDL_Cursor * SDLCALL SDL_CreateCursor(const Uint8 *data,
*
* \since This function is available since SDL 3.2.0.
*
* \sa SDL_AddSurfaceAlternateImage
* \sa SDL_CreateCursor
* \sa SDL_CreateSystemCursor
* \sa SDL_DestroyCursor

View File

@@ -942,7 +942,7 @@ typedef enum SDL_InitStatus
* Here is an example of using this:
*
* ```c
* static SDL_AtomicInitState init;
* static SDL_InitState init;
*
* bool InitSystem(void)
* {

View File

@@ -1379,7 +1379,7 @@ extern SDL_DECLSPEC Uint32 SDLCALL SDL_MapRGBA(const SDL_PixelFormatDetails *for
* (e.g., a completely white pixel in 16-bit RGB565 format would return [0xff,
* 0xff, 0xff] not [0xf8, 0xfc, 0xf8]).
*
* \param pixel a pixel value.
* \param pixelvalue a pixel value.
* \param format a pointer to SDL_PixelFormatDetails describing the pixel
* format.
* \param palette an optional palette for indexed formats, may be NULL.
@@ -1397,7 +1397,7 @@ extern SDL_DECLSPEC Uint32 SDLCALL SDL_MapRGBA(const SDL_PixelFormatDetails *for
* \sa SDL_MapRGB
* \sa SDL_MapRGBA
*/
extern SDL_DECLSPEC void SDLCALL SDL_GetRGB(Uint32 pixel, const SDL_PixelFormatDetails *format, const SDL_Palette *palette, Uint8 *r, Uint8 *g, Uint8 *b);
extern SDL_DECLSPEC void SDLCALL SDL_GetRGB(Uint32 pixelvalue, const SDL_PixelFormatDetails *format, const SDL_Palette *palette, Uint8 *r, Uint8 *g, Uint8 *b);
/**
* Get RGBA values from a pixel in the specified format.
@@ -1410,7 +1410,7 @@ extern SDL_DECLSPEC void SDLCALL SDL_GetRGB(Uint32 pixel, const SDL_PixelFormatD
* If the surface has no alpha component, the alpha will be returned as 0xff
* (100% opaque).
*
* \param pixel a pixel value.
* \param pixelvalue a pixel value.
* \param format a pointer to SDL_PixelFormatDetails describing the pixel
* format.
* \param palette an optional palette for indexed formats, may be NULL.
@@ -1429,7 +1429,7 @@ extern SDL_DECLSPEC void SDLCALL SDL_GetRGB(Uint32 pixel, const SDL_PixelFormatD
* \sa SDL_MapRGB
* \sa SDL_MapRGBA
*/
extern SDL_DECLSPEC void SDLCALL SDL_GetRGBA(Uint32 pixel, const SDL_PixelFormatDetails *format, const SDL_Palette *palette, Uint8 *r, Uint8 *g, Uint8 *b, Uint8 *a);
extern SDL_DECLSPEC void SDLCALL SDL_GetRGBA(Uint32 pixelvalue, const SDL_PixelFormatDetails *format, const SDL_Palette *palette, Uint8 *r, Uint8 *g, Uint8 *b, Uint8 *a);
/* Ends C function definitions when using C++ */

View File

@@ -317,7 +317,7 @@
#define SDL_PLATFORM_CYGWIN 1
#endif
#if defined(_WIN32) || defined(SDL_PLATFORM_CYGWIN)
#if (defined(_WIN32) || defined(SDL_PLATFORM_CYGWIN)) && !defined(__NGAGE__)
/**
* A preprocessor macro that is only defined if compiling for Windows.
@@ -473,4 +473,15 @@
#define SDL_PLATFORM_3DS 1
#endif
#ifdef __NGAGE__
/**
* A preprocessor macro that is only defined if compiling for the Nokia
* N-Gage.
*
* \since This macro is available since SDL 3.4.0.
*/
#define SDL_PLATFORM_NGAGE 1
#endif
#endif /* SDL_platform_defines_h_ */

View File

@@ -166,6 +166,9 @@ typedef enum SDL_ProcessIO
* - `SDL_PROP_PROCESS_CREATE_ENVIRONMENT_POINTER`: an SDL_Environment
* pointer. If this property is set, it will be the entire environment for
* the process, otherwise the current environment is used.
* - `SDL_PROP_PROCESS_CREATE_WORKING_DIRECTORY_STRING`: a UTF-8 encoded
* string representing the working directory for the process, defaults to
* the current working directory.
* - `SDL_PROP_PROCESS_CREATE_STDIN_NUMBER`: an SDL_ProcessIO value describing
* where standard input for the process comes from, defaults to
* `SDL_PROCESS_STDIO_NULL`.
@@ -192,6 +195,12 @@ typedef enum SDL_ProcessIO
* run in the background. In this case the default input and output is
* `SDL_PROCESS_STDIO_NULL` and the exitcode of the process is not
* available, and will always be 0.
* - `SDL_PROP_PROCESS_CREATE_CMDLINE_STRING`: a string containing the program
* to run and any parameters. This string is passed directly to
* `CreateProcess` on Windows, and does nothing on other platforms. This
* property is only important if you want to start programs that does
* non-standard command-line processing, and in most cases using
* `SDL_PROP_PROCESS_CREATE_ARGS_POINTER` is sufficient.
*
* On POSIX platforms, wait() and waitpid(-1, ...) should not be called, and
* SIGCHLD should not be ignored or handled because those would prevent SDL
@@ -219,6 +228,7 @@ extern SDL_DECLSPEC SDL_Process * SDLCALL SDL_CreateProcessWithProperties(SDL_Pr
#define SDL_PROP_PROCESS_CREATE_ARGS_POINTER "SDL.process.create.args"
#define SDL_PROP_PROCESS_CREATE_ENVIRONMENT_POINTER "SDL.process.create.environment"
#define SDL_PROP_PROCESS_CREATE_WORKING_DIRECTORY_STRING "SDL.process.create.working_directory"
#define SDL_PROP_PROCESS_CREATE_STDIN_NUMBER "SDL.process.create.stdin_option"
#define SDL_PROP_PROCESS_CREATE_STDIN_POINTER "SDL.process.create.stdin_source"
#define SDL_PROP_PROCESS_CREATE_STDOUT_NUMBER "SDL.process.create.stdout_option"
@@ -227,6 +237,7 @@ extern SDL_DECLSPEC SDL_Process * SDLCALL SDL_CreateProcessWithProperties(SDL_Pr
#define SDL_PROP_PROCESS_CREATE_STDERR_POINTER "SDL.process.create.stderr_source"
#define SDL_PROP_PROCESS_CREATE_STDERR_TO_STDOUT_BOOLEAN "SDL.process.create.stderr_to_stdout"
#define SDL_PROP_PROCESS_CREATE_BACKGROUND_BOOLEAN "SDL.process.create.background"
#define SDL_PROP_PROCESS_CREATE_CMDLINE_STRING "SDL.process.create.cmdline"
/**
* Get the properties associated with a process.

View File

@@ -324,7 +324,7 @@ SDL_FORCE_INLINE bool SDL_PointInRectFloat(const SDL_FPoint *p, const SDL_FRect
}
/**
* Determine whether a floating point rectangle can contain any point.
* Determine whether a floating point rectangle takes no space.
*
* A rectangle is considered "empty" for this function if `r` is NULL, or if
* `r`'s width and/or height are < 0.0f.

View File

@@ -59,6 +59,7 @@
#include <SDL3/SDL_rect.h>
#include <SDL3/SDL_surface.h>
#include <SDL3/SDL_video.h>
#include <SDL3/SDL_gpu.h>
#include <SDL3/SDL_begin_code.h>
/* Set up for C function definitions, even when using C++ */
@@ -97,6 +98,21 @@ typedef enum SDL_TextureAccess
SDL_TEXTUREACCESS_TARGET /**< Texture can be used as a render target */
} SDL_TextureAccess;
/**
* The addressing mode for a texture when used in SDL_RenderGeometry().
*
* This affects how texture coordinates are interpreted outside of [0, 1]
*
* \since This enum is available since SDL 3.4.0.
*/
typedef enum SDL_TextureAddressMode
{
SDL_TEXTURE_ADDRESS_INVALID = -1,
SDL_TEXTURE_ADDRESS_AUTO, /**< Wrapping is enabled if texture coordinates are outside [0, 1], this is the default */
SDL_TEXTURE_ADDRESS_CLAMP, /**< Texture coordinates are clamped to the [0, 1] range */
SDL_TEXTURE_ADDRESS_WRAP, /**< The texture is repeated (tiled) */
} SDL_TextureAddressMode;
/**
* How the logical size is mapped to the output.
*
@@ -267,6 +283,15 @@ extern SDL_DECLSPEC SDL_Renderer * SDLCALL SDL_CreateRenderer(SDL_Window *window
* present synchronized with the refresh rate. This property can take any
* value that is supported by SDL_SetRenderVSync() for the renderer.
*
* With the SDL GPU renderer:
*
* - `SDL_PROP_RENDERER_CREATE_GPU_SHADERS_SPIRV_BOOLEAN`: the app is able to
* provide SPIR-V shaders to SDL_GPURenderState, optional.
* - `SDL_PROP_RENDERER_CREATE_GPU_SHADERS_DXIL_BOOLEAN`: the app is able to
* provide DXIL shaders to SDL_GPURenderState, optional.
* - `SDL_PROP_RENDERER_CREATE_GPU_SHADERS_MSL_BOOLEAN`: the app is able to
* provide MSL shaders to SDL_GPURenderState, optional.
*
* With the vulkan renderer:
*
* - `SDL_PROP_RENDERER_CREATE_VULKAN_INSTANCE_POINTER`: the VkInstance to use
@@ -303,6 +328,9 @@ extern SDL_DECLSPEC SDL_Renderer * SDLCALL SDL_CreateRendererWithProperties(SDL_
#define SDL_PROP_RENDERER_CREATE_SURFACE_POINTER "SDL.renderer.create.surface"
#define SDL_PROP_RENDERER_CREATE_OUTPUT_COLORSPACE_NUMBER "SDL.renderer.create.output_colorspace"
#define SDL_PROP_RENDERER_CREATE_PRESENT_VSYNC_NUMBER "SDL.renderer.create.present_vsync"
#define SDL_PROP_RENDERER_CREATE_GPU_SHADERS_SPIRV_BOOLEAN "SDL.renderer.create.gpu.shaders_spirv"
#define SDL_PROP_RENDERER_CREATE_GPU_SHADERS_DXIL_BOOLEAN "SDL.renderer.create.gpu.shaders_dxil"
#define SDL_PROP_RENDERER_CREATE_GPU_SHADERS_MSL_BOOLEAN "SDL.renderer.create.gpu.shaders_msl"
#define SDL_PROP_RENDERER_CREATE_VULKAN_INSTANCE_POINTER "SDL.renderer.create.vulkan.instance"
#define SDL_PROP_RENDERER_CREATE_VULKAN_SURFACE_NUMBER "SDL.renderer.create.vulkan.surface"
#define SDL_PROP_RENDERER_CREATE_VULKAN_PHYSICAL_DEVICE_POINTER "SDL.renderer.create.vulkan.physical_device"
@@ -310,6 +338,37 @@ extern SDL_DECLSPEC SDL_Renderer * SDLCALL SDL_CreateRendererWithProperties(SDL_
#define SDL_PROP_RENDERER_CREATE_VULKAN_GRAPHICS_QUEUE_FAMILY_INDEX_NUMBER "SDL.renderer.create.vulkan.graphics_queue_family_index"
#define SDL_PROP_RENDERER_CREATE_VULKAN_PRESENT_QUEUE_FAMILY_INDEX_NUMBER "SDL.renderer.create.vulkan.present_queue_family_index"
/**
* Create a 2D GPU rendering context for a window, with support for the
* specified shader format.
*
* This is a convenience function to create a SDL GPU backed renderer,
* intended to be used with SDL_GPURenderState. The resulting renderer will
* support shaders in one of the specified shader formats.
*
* If no available GPU driver supports any of the specified shader formats,
* this function will fail.
*
* \param window the window where rendering is displayed.
* \param format_flags a bitflag indicating which shader formats the app is
* able to provide.
* \param device a pointer filled with the associated GPU device, or NULL on
* error.
* \returns a valid rendering context or NULL if there was an error; call
* SDL_GetError() for more information.
*
* \threadsafety This function should only be called on the main thread.
*
* \since This function is available since SDL 3.4.0.
*
* \sa SDL_CreateRendererWithProperties
* \sa SDL_GetGPUShaderFormats
* \sa SDL_CreateGPUShader
* \sa SDL_CreateGPURenderState
* \sa SDL_SetRenderGPUState
*/
extern SDL_DECLSPEC SDL_Renderer * SDLCALL SDL_CreateGPURenderer(SDL_Window *window, SDL_GPUShaderFormat format_flags, SDL_GPUDevice **device);
/**
* Create a 2D software rendering context for a surface.
*
@@ -2234,6 +2293,43 @@ extern SDL_DECLSPEC bool SDLCALL SDL_RenderTextureTiled(SDL_Renderer *renderer,
*/
extern SDL_DECLSPEC bool SDLCALL SDL_RenderTexture9Grid(SDL_Renderer *renderer, SDL_Texture *texture, const SDL_FRect *srcrect, float left_width, float right_width, float top_height, float bottom_height, float scale, const SDL_FRect *dstrect);
/**
* Perform a scaled copy using the 9-grid algorithm to the current rendering
* target at subpixel precision.
*
* The pixels in the texture are split into a 3x3 grid, using the different
* corner sizes for each corner, and the sides and center making up the
* remaining pixels. The corners are then scaled using `scale` and fit into
* the corners of the destination rectangle. The sides and center are then
* tiled into place to cover the remaining destination rectangle.
*
* \param renderer the renderer which should copy parts of a texture.
* \param texture the source texture.
* \param srcrect the SDL_Rect structure representing the rectangle to be used
* for the 9-grid, or NULL to use the entire texture.
* \param left_width the width, in pixels, of the left corners in `srcrect`.
* \param right_width the width, in pixels, of the right corners in `srcrect`.
* \param top_height the height, in pixels, of the top corners in `srcrect`.
* \param bottom_height the height, in pixels, of the bottom corners in
* `srcrect`.
* \param scale the scale used to transform the corner of `srcrect` into the
* corner of `dstrect`, or 0.0f for an unscaled copy.
* \param dstrect a pointer to the destination rectangle, or NULL for the
* entire rendering target.
* \param tileScale the scale used to transform the borders and center of
* `srcrect` into the borders and middle of `dstrect`, or
* 1.0f for an unscaled copy.
* \returns true on success or false on failure; call SDL_GetError() for more
* information.
*
* \threadsafety This function should only be called on the main thread.
*
* \since This function is available since SDL 3.4.0.
*
* \sa SDL_RenderTexture
*/
extern SDL_DECLSPEC bool SDLCALL SDL_RenderTexture9GridTiled(SDL_Renderer *renderer, SDL_Texture *texture, const SDL_FRect *srcrect, float left_width, float right_width, float top_height, float bottom_height, float scale, const SDL_FRect *dstrect, float tileScale);
/**
* Render a list of triangles, optionally using a texture and indices into the
* vertex array Color and alpha modulation is done per vertex
@@ -2255,6 +2351,7 @@ extern SDL_DECLSPEC bool SDLCALL SDL_RenderTexture9Grid(SDL_Renderer *renderer,
* \since This function is available since SDL 3.2.0.
*
* \sa SDL_RenderGeometryRaw
* \sa SDL_SetRenderTextureAddressMode
*/
extern SDL_DECLSPEC bool SDLCALL SDL_RenderGeometry(SDL_Renderer *renderer,
SDL_Texture *texture,
@@ -2287,6 +2384,7 @@ extern SDL_DECLSPEC bool SDLCALL SDL_RenderGeometry(SDL_Renderer *renderer,
* \since This function is available since SDL 3.2.0.
*
* \sa SDL_RenderGeometry
* \sa SDL_SetRenderTextureAddressMode
*/
extern SDL_DECLSPEC bool SDLCALL SDL_RenderGeometryRaw(SDL_Renderer *renderer,
SDL_Texture *texture,
@@ -2296,6 +2394,44 @@ extern SDL_DECLSPEC bool SDLCALL SDL_RenderGeometryRaw(SDL_Renderer *renderer,
int num_vertices,
const void *indices, int num_indices, int size_indices);
/**
* Set the texture addressing mode used in SDL_RenderGeometry().
*
* \param renderer the rendering context.
* \param u_mode the SDL_TextureAddressMode to use for horizontal texture
* coordinates in SDL_RenderGeometry().
* \param v_mode the SDL_TextureAddressMode to use for vertical texture
* coordinates in SDL_RenderGeometry().
* \returns true on success or false on failure; call SDL_GetError() for more
* information.
*
* \since This function is available since SDL 3.4.0.
*
* \sa SDL_RenderGeometry
* \sa SDL_RenderGeometryRaw
* \sa SDL_GetRenderTextureAddressMode
*/
extern SDL_DECLSPEC bool SDLCALL SDL_SetRenderTextureAddressMode(SDL_Renderer *renderer, SDL_TextureAddressMode u_mode, SDL_TextureAddressMode v_mode);
/**
* Get the texture addressing mode used in SDL_RenderGeometry().
*
* \param renderer the rendering context.
* \param u_mode a pointer filled in with the SDL_TextureAddressMode to use
* for horizontal texture coordinates in SDL_RenderGeometry(),
* may be NULL.
* \param v_mode a pointer filled in with the SDL_TextureAddressMode to use
* for vertical texture coordinates in SDL_RenderGeometry(), may
* be NULL.
* \returns true on success or false on failure; call SDL_GetError() for more
* information.
*
* \since This function is available since SDL 3.4.0.
*
* \sa SDL_SetRenderTextureAddressMode
*/
extern SDL_DECLSPEC bool SDLCALL SDL_GetRenderTextureAddressMode(SDL_Renderer *renderer, SDL_TextureAddressMode *u_mode, SDL_TextureAddressMode *v_mode);
/**
* Read pixels from the current rendering target.
*
@@ -2347,8 +2483,7 @@ extern SDL_DECLSPEC SDL_Surface * SDLCALL SDL_RenderReadPixels(SDL_Renderer *ren
* should not be done; you are only required to change back the rendering
* target to default via `SDL_SetRenderTarget(renderer, NULL)` afterwards, as
* textures by themselves do not have a concept of backbuffers. Calling
* SDL_RenderPresent while rendering to a texture will still update the screen
* with any current drawing that has been done _to the window itself_.
* SDL_RenderPresent while rendering to a texture will fail.
*
* \param renderer the rendering context.
* \returns true on success or false on failure; call SDL_GetError() for more
@@ -2636,6 +2771,161 @@ extern SDL_DECLSPEC bool SDLCALL SDL_RenderDebugText(SDL_Renderer *renderer, flo
*/
extern SDL_DECLSPEC bool SDLCALL SDL_RenderDebugTextFormat(SDL_Renderer *renderer, float x, float y, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(4);
/**
* Set default scale mode for new textures for given renderer.
*
* When a renderer is created, scale_mode defaults to SDL_SCALEMODE_LINEAR.
*
* \param renderer the renderer to update.
* \param scale_mode the scale mode to change to for new textures.
* \returns true on success or false on failure; call SDL_GetError() for more
* information.
*
* \threadsafety This function should only be called on the main thread.
*
* \since This function is available since SDL 3.4.0.
*
* \sa SDL_GetDefaultTextureScaleMode
*/
extern SDL_DECLSPEC bool SDLCALL SDL_SetDefaultTextureScaleMode(SDL_Renderer *renderer, SDL_ScaleMode scale_mode);
/**
* Get default texture scale mode of the given renderer.
*
* \param renderer the renderer to get data from.
* \param scale_mode a SDL_ScaleMode filled with current default scale mode.
* See SDL_SetDefaultTextureScaleMode() for the meaning of
* the value.
* \returns true on success or false on failure; call SDL_GetError() for more
* information.
*
* \threadsafety This function should only be called on the main thread.
*
* \since This function is available since SDL 3.4.0.
*
* \sa SDL_SetDefaultTextureScaleMode
*/
extern SDL_DECLSPEC bool SDLCALL SDL_GetDefaultTextureScaleMode(SDL_Renderer *renderer, SDL_ScaleMode *scale_mode);
/**
* GPU render state description.
*
* This structure should be initialized using SDL_INIT_INTERFACE().
*
* \since This struct is available since SDL 3.4.0.
*
* \sa SDL_CreateGPURenderState
*/
typedef struct SDL_GPURenderStateDesc
{
Uint32 version; /**< the version of this interface */
SDL_GPUShader *fragment_shader; /**< The fragment shader to use when this render state is active */
Sint32 num_sampler_bindings; /**< The number of additional fragment samplers to bind when this render state is active */
const SDL_GPUTextureSamplerBinding *sampler_bindings; /**< Additional fragment samplers to bind when this render state is active */
Sint32 num_storage_textures; /**< The number of storage textures to bind when this render state is active */
SDL_GPUTexture *const *storage_textures; /**< Storage textures to bind when this render state is active */
Sint32 num_storage_buffers; /**< The number of storage buffers to bind when this render state is active */
SDL_GPUBuffer *const *storage_buffers; /**< Storage buffers to bind when this render state is active */
} SDL_GPURenderStateDesc;
/* Check the size of SDL_GPURenderStateDesc
*
* If this assert fails, either the compiler is padding to an unexpected size,
* or the interface has been updated and this should be updated to match and
* the code using this interface should be updated to handle the old version.
*/
SDL_COMPILE_TIME_ASSERT(SDL_GPURenderStateDesc_SIZE,
(sizeof(void *) == 4 && sizeof(SDL_GPURenderStateDesc) == 32) ||
(sizeof(void *) == 8 && sizeof(SDL_GPURenderStateDesc) == 64));
/**
* A custom GPU render state.
*
* \since This struct is available since SDL 3.4.0.
*
* \sa SDL_CreateGPURenderState
* \sa SDL_SetGPURenderStateFragmentUniforms
* \sa SDL_SetRenderGPUState
* \sa SDL_DestroyGPURenderState
*/
typedef struct SDL_GPURenderState SDL_GPURenderState;
/**
* Create custom GPU render state.
*
* \param renderer the renderer to use.
* \param desc GPU render state description, initialized using
* SDL_INIT_INTERFACE().
* \returns a custom GPU render state or NULL on failure; call SDL_GetError()
* for more information.
*
* \threadsafety This function should be called on the thread that created the
* renderer.
*
* \since This function is available since SDL 3.4.0.
*
* \sa SDL_SetGPURenderStateFragmentUniforms
* \sa SDL_SetRenderGPUState
* \sa SDL_DestroyGPURenderState
*/
extern SDL_DECLSPEC SDL_GPURenderState * SDLCALL SDL_CreateGPURenderState(SDL_Renderer *renderer, SDL_GPURenderStateDesc *desc);
/**
* Set fragment shader uniform variables in a custom GPU render state.
*
* The data is copied and will be pushed using
* SDL_PushGPUFragmentUniformData() during draw call execution.
*
* \param state the state to modify.
* \param slot_index the fragment uniform slot to push data to.
* \param data client data to write.
* \param length the length of the data to write.
* \returns true on success or false on failure; call SDL_GetError() for more
* information.
*
* \threadsafety This function should be called on the thread that created the
* renderer.
*
* \since This function is available since SDL 3.4.0.
*/
extern SDL_DECLSPEC bool SDLCALL SDL_SetGPURenderStateFragmentUniforms(SDL_GPURenderState *state, Uint32 slot_index, const void *data, Uint32 length);
/**
* Set custom GPU render state.
*
* This function sets custom GPU render state for subsequent draw calls. This
* allows using custom shaders with the GPU renderer.
*
* \param renderer the renderer to use.
* \param state the state to to use, or NULL to clear custom GPU render state.
* \returns true on success or false on failure; call SDL_GetError() for more
* information.
*
* \threadsafety This function should be called on the thread that created the
* renderer.
*
* \since This function is available since SDL 3.4.0.
*/
extern SDL_DECLSPEC bool SDLCALL SDL_SetRenderGPUState(SDL_Renderer *renderer, SDL_GPURenderState *state);
/**
* Destroy custom GPU render state.
*
* \param state the state to destroy.
*
* \threadsafety This function should be called on the thread that created the
* renderer.
*
* \since This function is available since SDL 3.4.0.
*
* \sa SDL_CreateGPURenderState
*/
extern SDL_DECLSPEC void SDLCALL SDL_DestroyGPURenderState(SDL_GPURenderState *state);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}

View File

@@ -31,9 +31,9 @@
/* #undef SDL_VENDOR_INFO */
#ifdef SDL_VENDOR_INFO
#define SDL_REVISION "SDL3-3.2.16-release-3.2.14-53-g59693c899 (" SDL_VENDOR_INFO ")"
#define SDL_REVISION "SDL3-3.3.0-release-3.2.6-664-g0e262dfd4 (" SDL_VENDOR_INFO ")"
#else
#define SDL_REVISION "SDL3-3.2.16-release-3.2.14-53-g59693c899"
#define SDL_REVISION "SDL3-3.3.0-release-3.2.6-664-g0e262dfd4"
#endif
#endif /* SDL_revision_h_ */

View File

@@ -2119,7 +2119,7 @@ extern SDL_DECLSPEC int SDLCALL SDL_abs(int x);
*
* \param x the first value to compare.
* \param y the second value to compare.
* \returns the lesser of `x` and `y`.
* \returns the greater of `x` and `y`.
*
* \threadsafety It is safe to call this macro from any thread.
*

View File

@@ -334,6 +334,10 @@ typedef struct SDL_Storage SDL_Storage;
/**
* Opens up a read-only container for the application's filesystem.
*
* By default, SDL_OpenTitleStorage uses the generic storage implementation.
* When the path override is not provided, the generic implementation will use
* the output of SDL_GetBasePath as the base path.
*
* \param override a path to override the backend's default title root.
* \param props a property list that may contain backend-specific information.
* \returns a title storage container on success or NULL on failure; call

View File

@@ -32,7 +32,8 @@
* There is also a simple .bmp loader, SDL_LoadBMP(). SDL itself does not
* provide loaders for various other file formats, but there are several
* excellent external libraries that do, including its own satellite library,
* SDL_image:
* [SDL_image](https://wiki.libsdl.org/SDL3_image)
* :
*
* https://github.com/libsdl-org/SDL_image
*/
@@ -83,8 +84,9 @@ typedef Uint32 SDL_SurfaceFlags;
typedef enum SDL_ScaleMode
{
SDL_SCALEMODE_INVALID = -1,
SDL_SCALEMODE_NEAREST, /**< nearest pixel sampling */
SDL_SCALEMODE_LINEAR /**< linear filtering */
SDL_SCALEMODE_NEAREST, /**< nearest pixel sampling */
SDL_SCALEMODE_LINEAR, /**< linear filtering */
SDL_SCALEMODE_PIXELART /**< nearest pixel sampling with improved scaling for pixel art */
} SDL_ScaleMode;
/**

View File

@@ -247,14 +247,14 @@ typedef void (SDLCALL *SDL_iOSAnimationCallback)(void *userdata);
*
* For more information see:
*
* https://wiki.libsdl.org/SDL3/README/ios
* https://wiki.libsdl.org/SDL3/README-ios
*
* Note that if you use the "main callbacks" instead of a standard C `main`
* function, you don't have to use this API, as SDL will manage this for you.
*
* Details on main callbacks are here:
*
* https://wiki.libsdl.org/SDL3/README/main-functions
* https://wiki.libsdl.org/SDL3/README-main-functions
*
* \param window the window for which the animation callback should be set.
* \param interval the number of frames after which **callback** will be

View File

@@ -185,10 +185,12 @@ extern "C" {
#define SDL_NS_TO_US(NS) ((NS) / SDL_NS_PER_US)
/**
* Get the number of milliseconds since SDL library initialization.
* Get the number of milliseconds that have elapsed since the SDL library
* initialization.
*
* \returns an unsigned 64-bit value representing the number of milliseconds
* since the SDL library initialized.
* \returns an unsigned 64bit integer that represents the number of
* milliseconds that have elapsed since the SDL library was
* initialized (typically via a call to SDL_Init).
*
* \threadsafety It is safe to call this function from any thread.
*

View File

@@ -53,7 +53,7 @@ extern "C" {
*
* \since This macro is available since SDL 3.2.0.
*/
#define SDL_MINOR_VERSION 2
#define SDL_MINOR_VERSION 3
/**
* The current micro (or patchlevel) version of the SDL headers.
@@ -62,7 +62,7 @@ extern "C" {
*
* \since This macro is available since SDL 3.2.0.
*/
#define SDL_MICRO_VERSION 16
#define SDL_MICRO_VERSION 0
/**
* This macro turns the version numbers into a numeric value.
@@ -148,13 +148,14 @@ extern "C" {
extern SDL_DECLSPEC int SDLCALL SDL_GetVersion(void);
/**
* Get the code revision of SDL that is linked against your program.
* Get the code revision of the SDL library that is linked against your
* program.
*
* This value is the revision of the code you are linked with and may be
* This value is the revision of the code you are linking against and may be
* different from the code you are compiling with, which is found in the
* constant SDL_REVISION.
*
* The revision is arbitrary string (a hash value) uniquely identifying the
* The revision is an arbitrary string (a hash value) uniquely identifying the
* exact revision of the SDL library in use, and is only useful in comparing
* against other revisions. It is NOT an incrementing number.
*

View File

@@ -307,6 +307,21 @@ typedef enum SDL_FlashOperation
SDL_FLASH_UNTIL_FOCUSED /**< Flash the window until it gets focus */
} SDL_FlashOperation;
/**
* Window progress state
*
* \since This enum is available since SDL 3.2.8.
*/
typedef enum SDL_ProgressState
{
SDL_PROGRESS_STATE_INVALID = -1, /**< An invalid progress state indicating an error; check SDL_GetError() */
SDL_PROGRESS_STATE_NONE, /**< No progress bar is shown */
SDL_PROGRESS_STATE_INDETERMINATE, /**< The progress bar is shown in a indeterminate state */
SDL_PROGRESS_STATE_NORMAL, /**< The progress bar is shown in a normal state */
SDL_PROGRESS_STATE_PAUSED, /**< The progress bar is shown in a paused state */
SDL_PROGRESS_STATE_ERROR /**< The progress bar is shown in a state indicating the application had an error */
} SDL_ProgressState;
/**
* An opaque handle to an OpenGL context.
*
@@ -617,6 +632,11 @@ extern SDL_DECLSPEC SDL_DisplayID SDLCALL SDL_GetPrimaryDisplay(void);
* responsible for any coordinate transformations needed to conform to the
* requested display orientation.
*
* On Wayland:
*
* - `SDL_PROP_DISPLAY_WAYLAND_WL_OUTPUT_POINTER`: the wl_output associated
* with the display
*
* \param displayID the instance ID of the display to query.
* \returns a valid property ID on success or 0 on failure; call
* SDL_GetError() for more information.
@@ -629,6 +649,7 @@ extern SDL_DECLSPEC SDL_PropertiesID SDLCALL SDL_GetDisplayProperties(SDL_Displa
#define SDL_PROP_DISPLAY_HDR_ENABLED_BOOLEAN "SDL.display.HDR_enabled"
#define SDL_PROP_DISPLAY_KMSDRM_PANEL_ORIENTATION_NUMBER "SDL.display.KMSDRM.panel_orientation"
#define SDL_PROP_DISPLAY_WAYLAND_WL_OUTPUT_POINTER "SDL.display.wayland.wl_output"
/**
* Get the name of a display in UTF-8 encoding.
@@ -1167,6 +1188,16 @@ extern SDL_DECLSPEC SDL_Window * SDLCALL SDL_CreateWindow(const char *title, int
* Popup windows implicitly do not have a border/decorations and do not appear
* on the taskbar/dock or in lists of windows such as alt-tab menus.
*
* By default, popup window positions will automatically be constrained to
* keep the entire window within display bounds. This can be overridden with
* the `SDL_PROP_WINDOW_CREATE_CONSTRAIN_POPUP_BOOLEAN` property.
*
* By default, popup menus will automatically grab keyboard focus from the
* parent when shown. This behavior can be overridden by setting the
* `SDL_WINDOW_NOT_FOCUSABLE` flag, setting the
* `SDL_PROP_WINDOW_CREATE_FOCUSABLE_BOOLEAN` property to false, or toggling
* it after creation via the `SDL_SetWindowFocusable()` function.
*
* If a parent window is hidden or destroyed, any child popup windows will be
* recursively hidden or destroyed as well. Child popup windows not explicitly
* hidden will be restored when the parent is shown.
@@ -1207,6 +1238,10 @@ extern SDL_DECLSPEC SDL_Window * SDLCALL SDL_CreatePopupWindow(SDL_Window *paren
* be always on top
* - `SDL_PROP_WINDOW_CREATE_BORDERLESS_BOOLEAN`: true if the window has no
* window decoration
* - `SDL_PROP_WINDOW_CREATE_CONSTRAIN_POPUP_BOOLEAN`: true if the "tooltip"
* and "menu" window types should be automatically constrained to be
* entirely within display bounds (default), false if no constraints on the
* position are desired.
* - `SDL_PROP_WINDOW_CREATE_EXTERNAL_GRAPHICS_CONTEXT_BOOLEAN`: true if the
* window will be used with an externally managed graphics context.
* - `SDL_PROP_WINDOW_CREATE_FOCUSABLE_BOOLEAN`: true if the window should
@@ -1268,7 +1303,7 @@ extern SDL_DECLSPEC SDL_Window * SDLCALL SDL_CreatePopupWindow(SDL_Window *paren
* - `SDL_PROP_WINDOW_CREATE_WAYLAND_SURFACE_ROLE_CUSTOM_BOOLEAN` - true if
* the application wants to use the Wayland surface for a custom role and
* does not want it attached to an XDG toplevel window. See
* [README/wayland](README/wayland) for more information on using custom
* [README-wayland](README-wayland) for more information on using custom
* surfaces.
* - `SDL_PROP_WINDOW_CREATE_WAYLAND_CREATE_EGL_WINDOW_BOOLEAN` - true if the
* application wants an associated `wl_egl_window` object to be created and
@@ -1276,7 +1311,7 @@ extern SDL_DECLSPEC SDL_Window * SDLCALL SDL_CreatePopupWindow(SDL_Window *paren
* property or `SDL_WINDOW_OPENGL` flag set.
* - `SDL_PROP_WINDOW_CREATE_WAYLAND_WL_SURFACE_POINTER` - the wl_surface
* associated with the window, if you want to wrap an existing window. See
* [README/wayland](README/wayland) for more information.
* [README-wayland](README-wayland) for more information.
*
* These are additional supported properties on Windows:
*
@@ -1292,8 +1327,22 @@ extern SDL_DECLSPEC SDL_Window * SDLCALL SDL_CreatePopupWindow(SDL_Window *paren
*
* The window is implicitly shown if the "hidden" property is not set.
*
* Windows with the "tooltip" and "menu" properties are popup windows and have
* the behaviors and guidelines outlined in SDL_CreatePopupWindow().
* These are additional supported properties with Emscripten:
*
* - `SDL_PROP_WINDOW_CREATE_EMSCRIPTEN_CANVAS_ID_STRING`: the id given to the
* canvas element. This should start with a '#' sign
* - `SDL_PROP_WINDOW_CREATE_EMSCRIPTEN_KEYBOARD_ELEMENT_STRING`: override the
* binding element for keyboard inputs for this canvas. The variable can be
* one of:
* - "#window": the javascript window object (default)
* - "#document": the javascript document object
* - "#screen": the javascript window.screen object
* - "#canvas": the WebGL canvas element
* - "#none": Don't bind anything at all
* - any other string without a leading # sign applies to the element on the
* page with that ID. Windows with the "tooltip" and "menu" properties are
* popup windows and have the behaviors and guidelines outlined in
* SDL_CreatePopupWindow().
*
* If this window is being created to be used with an SDL_Renderer, you should
* not add a graphics API specific property
@@ -1321,6 +1370,7 @@ extern SDL_DECLSPEC SDL_Window * SDLCALL SDL_CreateWindowWithProperties(SDL_Prop
#define SDL_PROP_WINDOW_CREATE_ALWAYS_ON_TOP_BOOLEAN "SDL.window.create.always_on_top"
#define SDL_PROP_WINDOW_CREATE_BORDERLESS_BOOLEAN "SDL.window.create.borderless"
#define SDL_PROP_WINDOW_CREATE_CONSTRAIN_POPUP_BOOLEAN "SDL.window.create.constrain_popup"
#define SDL_PROP_WINDOW_CREATE_FOCUSABLE_BOOLEAN "SDL.window.create.focusable"
#define SDL_PROP_WINDOW_CREATE_EXTERNAL_GRAPHICS_CONTEXT_BOOLEAN "SDL.window.create.external_graphics_context"
#define SDL_PROP_WINDOW_CREATE_FLAGS_NUMBER "SDL.window.create.flags"
@@ -1353,6 +1403,8 @@ extern SDL_DECLSPEC SDL_Window * SDLCALL SDL_CreateWindowWithProperties(SDL_Prop
#define SDL_PROP_WINDOW_CREATE_WIN32_HWND_POINTER "SDL.window.create.win32.hwnd"
#define SDL_PROP_WINDOW_CREATE_WIN32_PIXEL_FORMAT_HWND_POINTER "SDL.window.create.win32.pixel_format_hwnd"
#define SDL_PROP_WINDOW_CREATE_X11_WINDOW_NUMBER "SDL.window.create.x11.window"
#define SDL_PROP_WINDOW_CREATE_EMSCRIPTEN_CANVAS_ID_STRING "SDL.window.create.emscripten.canvas_id"
#define SDL_PROP_WINDOW_CREATE_EMSCRIPTEN_KEYBOARD_ELEMENT_STRING "SDL.window.create.emscripten.keyboard_element"
/**
* Get the numeric ID of a window.
@@ -1464,8 +1516,8 @@ extern SDL_DECLSPEC SDL_Window * SDLCALL SDL_GetWindowParent(SDL_Window *window)
*
* On OpenVR:
*
* - `SDL_PROP_WINDOW_OPENVR_OVERLAY_ID`: the OpenVR Overlay Handle ID for the
* associated overlay window.
* - `SDL_PROP_WINDOW_OPENVR_OVERLAY_ID_NUMBER`: the OpenVR Overlay Handle ID
* for the associated overlay window.
*
* On Vivante:
*
@@ -1517,6 +1569,13 @@ extern SDL_DECLSPEC SDL_Window * SDLCALL SDL_GetWindowParent(SDL_Window *window)
* - `SDL_PROP_WINDOW_X11_WINDOW_NUMBER`: the X11 Window associated with the
* window
*
* On Emscripten:
*
* - `SDL_PROP_WINDOW_EMSCRIPTEN_CANVAS_ID_STRING`: the id the canvas element
* will have
* - `SDL_PROP_WINDOW_EMSCRIPTEN_KEYBOARD_ELEMENT_STRING`: the keyboard
* element that associates keyboard events to this window
*
* \param window the window to query.
* \returns a valid property ID on success or 0 on failure; call
* SDL_GetError() for more information.
@@ -1543,7 +1602,7 @@ extern SDL_DECLSPEC SDL_PropertiesID SDLCALL SDL_GetWindowProperties(SDL_Window
#define SDL_PROP_WINDOW_KMSDRM_GBM_DEVICE_POINTER "SDL.window.kmsdrm.gbm_dev"
#define SDL_PROP_WINDOW_COCOA_WINDOW_POINTER "SDL.window.cocoa.window"
#define SDL_PROP_WINDOW_COCOA_METAL_VIEW_TAG_NUMBER "SDL.window.cocoa.metal_view_tag"
#define SDL_PROP_WINDOW_OPENVR_OVERLAY_ID "SDL.window.openvr.overlay_id"
#define SDL_PROP_WINDOW_OPENVR_OVERLAY_ID_NUMBER "SDL.window.openvr.overlay_id"
#define SDL_PROP_WINDOW_VIVANTE_DISPLAY_POINTER "SDL.window.vivante.display"
#define SDL_PROP_WINDOW_VIVANTE_WINDOW_POINTER "SDL.window.vivante.window"
#define SDL_PROP_WINDOW_VIVANTE_SURFACE_POINTER "SDL.window.vivante.surface"
@@ -1562,6 +1621,8 @@ extern SDL_DECLSPEC SDL_PropertiesID SDLCALL SDL_GetWindowProperties(SDL_Window
#define SDL_PROP_WINDOW_X11_DISPLAY_POINTER "SDL.window.x11.display"
#define SDL_PROP_WINDOW_X11_SCREEN_NUMBER "SDL.window.x11.screen"
#define SDL_PROP_WINDOW_X11_WINDOW_NUMBER "SDL.window.x11.window"
#define SDL_PROP_WINDOW_EMSCRIPTEN_CANVAS_ID_STRING "SDL.window.emscripten.canvas_id"
#define SDL_PROP_WINDOW_EMSCRIPTEN_KEYBOARD_ELEMENT_STRING "SDL.window.emscripten.keyboard_element"
/**
* Get the window flags.
@@ -1619,15 +1680,16 @@ extern SDL_DECLSPEC const char * SDLCALL SDL_GetWindowTitle(SDL_Window *window);
/**
* Set the icon for a window.
*
* If this function is passed a surface with alternate representations, the
* surface will be interpreted as the content to be used for 100% display
* scale, and the alternate representations will be used for high DPI
* situations. For example, if the original surface is 32x32, then on a 2x
* macOS display or 200% display scale on Windows, a 64x64 version of the
* image will be used, if available. If a matching version of the image isn't
* available, the closest larger size image will be downscaled to the
* appropriate size and be used instead, if available. Otherwise, the closest
* smaller image will be upscaled and be used instead.
* If this function is passed a surface with alternate representations added
* using SDL_AddSurfaceAlternateImage(), the surface will be interpreted as
* the content to be used for 100% display scale, and the alternate
* representations will be used for high DPI situations. For example, if the
* original surface is 32x32, then on a 2x macOS display or 200% display scale
* on Windows, a 64x64 version of the image will be used, if available. If a
* matching version of the image isn't available, the closest larger size
* image will be downscaled to the appropriate size and be used instead, if
* available. Otherwise, the closest smaller image will be upscaled and be
* used instead.
*
* \param window the window to change.
* \param icon an SDL_Surface structure containing the icon for the window.
@@ -1637,6 +1699,8 @@ extern SDL_DECLSPEC const char * SDLCALL SDL_GetWindowTitle(SDL_Window *window);
* \threadsafety This function should only be called on the main thread.
*
* \since This function is available since SDL 3.2.0.
*
* \sa SDL_AddSurfaceAlternateImage
*/
extern SDL_DECLSPEC bool SDLCALL SDL_SetWindowIcon(SDL_Window *window, SDL_Surface *icon);
@@ -1830,7 +1894,7 @@ extern SDL_DECLSPEC bool SDLCALL SDL_GetWindowSafeArea(SDL_Window *window, SDL_R
extern SDL_DECLSPEC bool SDLCALL SDL_SetWindowAspectRatio(SDL_Window *window, float min_aspect, float max_aspect);
/**
* Get the size of a window's client area.
* Get the aspect ratio of a window's client area.
*
* \param window the window to query the width and height from.
* \param min_aspect a pointer filled in with the minimum aspect ratio of the
@@ -2457,7 +2521,6 @@ extern SDL_DECLSPEC bool SDLCALL SDL_SetWindowKeyboardGrab(SDL_Window *window, b
*
* \sa SDL_GetWindowMouseRect
* \sa SDL_SetWindowMouseRect
* \sa SDL_SetWindowMouseGrab
* \sa SDL_SetWindowKeyboardGrab
*/
extern SDL_DECLSPEC bool SDLCALL SDL_SetWindowMouseGrab(SDL_Window *window, bool grabbed);
@@ -2802,6 +2865,62 @@ extern SDL_DECLSPEC bool SDLCALL SDL_SetWindowShape(SDL_Window *window, SDL_Surf
*/
extern SDL_DECLSPEC bool SDLCALL SDL_FlashWindow(SDL_Window *window, SDL_FlashOperation operation);
/**
* Sets the state of the progress bar for the given windows taskbar icon.
*
* \param window the window whose progress state is to be modified.
* \param state the progress state. `SDL_PROGRESS_STATE_NONE` stops displaying
* the progress bar.
* \returns true on success or false on failure; call SDL_GetError() for more
* information.
*
* \threadsafety This function should only be called on the main thread.
*
* \since This function is available since SDL 3.4.0.
*/
extern SDL_DECLSPEC bool SDLCALL SDL_SetWindowProgressState(SDL_Window *window, SDL_ProgressState state);
/**
* Get the state of the progress bar for the given windows taskbar icon.
*
* \param window the window to get the current progress state from.
* \returns the progress state, or `SDL_PROGRESS_STATE_INVALID` on failure;
* call SDL_GetError() for more information.
*
* \threadsafety This function should only be called on the main thread.
*
* \since This function is available since SDL 3.4.0.
*/
extern SDL_DECLSPEC SDL_ProgressState SDLCALL SDL_GetWindowProgressState(SDL_Window *window);
/**
* Sets the value of the progress bar for the given windows taskbar icon.
*
* \param window the window whose progress value is to be modified.
* \param value the progress value in the range of [0.0f - 1.0f]. If the value
* is outside the valid range, it gets clamped.
* \returns true on success or false on failure; call SDL_GetError() for more
* information.
*
* \threadsafety This function should only be called on the main thread.
*
* \since This function is available since SDL 3.4.0.
*/
extern SDL_DECLSPEC bool SDLCALL SDL_SetWindowProgressValue(SDL_Window *window, float value);
/**
* Get the value of the progress bar for the given windows taskbar icon.
*
* \param window the window to get the current progress value from.
* \returns the progress value in the range of [0.0f - 1.0f], or -1.0f on
* failure; call SDL_GetError() for more information.
*
* \threadsafety This function should only be called on the main thread.
*
* \since This function is available since SDL 3.4.0.
*/
extern SDL_DECLSPEC float SDLCALL SDL_GetWindowProgressValue(SDL_Window *window);
/**
* Destroy a window.
*

View File

@@ -51,14 +51,14 @@
extern "C" {
#endif
/* Avoid including vulkan.h, don't define VkInstance if it's already included */
#ifdef VULKAN_H_
/* Avoid including vulkan_core.h, don't define VkInstance if it's already included */
#ifdef VULKAN_CORE_H_
#define NO_SDL_VULKAN_TYPEDEFS
#endif
#ifndef NO_SDL_VULKAN_TYPEDEFS
#define VK_DEFINE_HANDLE(object) typedef struct object##_T* object;
#if defined(__LP64__) || defined(_WIN64) || defined(__x86_64__) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(__powerpc64__)
#if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__)) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(__powerpc64__) || (defined(__riscv) && __riscv_xlen == 64)
#define VK_DEFINE_NON_DISPATCHABLE_HANDLE(object) typedef struct object##_T *object;
#else
#define VK_DEFINE_NON_DISPATCHABLE_HANDLE(object) typedef uint64_t object;

View File

@@ -29,21 +29,24 @@
#include "client/tracy_rpmalloc.cpp"
#include "client/TracyAlloc.cpp"
#include "client/TracyOverride.cpp"
#include "client/TracyKCore.cpp"
#if TRACY_HAS_CALLSTACK == 2 || TRACY_HAS_CALLSTACK == 3 || TRACY_HAS_CALLSTACK == 4 || TRACY_HAS_CALLSTACK == 6
# include "libbacktrace/alloc.cpp"
# include "libbacktrace/dwarf.cpp"
# include "libbacktrace/fileline.cpp"
# include "libbacktrace/mmapio.cpp"
# include "libbacktrace/posix.cpp"
# include "libbacktrace/sort.cpp"
# include "libbacktrace/state.cpp"
# if TRACY_HAS_CALLSTACK == 4
# include "libbacktrace/macho.cpp"
# else
# include "libbacktrace/elf.cpp"
#if defined(TRACY_HAS_CALLSTACK)
# if TRACY_HAS_CALLSTACK == 2 || TRACY_HAS_CALLSTACK == 3 || TRACY_HAS_CALLSTACK == 4 || TRACY_HAS_CALLSTACK == 6
# include "libbacktrace/alloc.cpp"
# include "libbacktrace/dwarf.cpp"
# include "libbacktrace/fileline.cpp"
# include "libbacktrace/mmapio.cpp"
# include "libbacktrace/posix.cpp"
# include "libbacktrace/sort.cpp"
# include "libbacktrace/state.cpp"
# if TRACY_HAS_CALLSTACK == 4
# include "libbacktrace/macho.cpp"
# else
# include "libbacktrace/elf.cpp"
# endif
# include "common/TracyStackFrames.cpp"
# endif
# include "common/TracyStackFrames.cpp"
#endif
#ifdef _MSC_VER

View File

@@ -305,6 +305,14 @@ static const char* DecodeIosDevice( const char* id )
"iPhone14,4", "iPhone 13 Mini",
"iPhone14,5", "iPhone 13",
"iPhone14,6", "iPhone SE 3rd Gen",
"iPhone14,7", "iPhone 14",
"iPhone14,8", "iPhone 14 Plus",
"iPhone15,2", "iPhone 14 Pro",
"iPhone15,3", "iPhone 14 Pro Max",
"iPhone15,4", "iPhone 15",
"iPhone15,5", "iPhone 15 Plus",
"iPhone16,1", "iPhone 15 Pro",
"iPhone16,2", "iPhone 15 Pro Max",
"iPad1,1", "iPad (A1219/A1337)",
"iPad2,1", "iPad 2 (A1395)",
"iPad2,2", "iPad 2 (A1396)",
@@ -365,6 +373,8 @@ static const char* DecodeIosDevice( const char* id )
"iPad11,4", "iPad Air 3rd gen (A2123/A2153/A2154)",
"iPad11,6", "iPad 8th gen (WiFi)",
"iPad11,7", "iPad 8th gen (WiFi+Cellular)",
"iPad12,1", "iPad 9th Gen (WiFi)",
"iPad12,2", "iPad 9th Gen (WiFi+Cellular)",
"iPad13,1", "iPad Air 4th gen (WiFi)",
"iPad13,2", "iPad Air 4th gen (WiFi+Cellular)",
"iPad13,4", "iPad Pro 11\" 3rd gen",
@@ -377,6 +387,14 @@ static const char* DecodeIosDevice( const char* id )
"iPad13,11", "iPad Pro 12.9\" 5th gen",
"iPad13,16", "iPad Air 5th Gen (WiFi)",
"iPad13,17", "iPad Air 5th Gen (WiFi+Cellular)",
"iPad13,18", "iPad 10th Gen",
"iPad13,19", "iPad 10th Gen",
"iPad14,1", "iPad mini 6th Gen (WiFi)",
"iPad14,2", "iPad mini 6th Gen (WiFi+Cellular)",
"iPad14,3", "iPad Pro 11\" 4th Gen",
"iPad14,4", "iPad Pro 11\" 4th Gen",
"iPad14,5", "iPad Pro 12.9\" 6th Gen",
"iPad14,6", "iPad Pro 12.9\" 6th Gen",
"iPod1,1", "iPod Touch",
"iPod2,1", "iPod Touch 2nd gen",
"iPod3,1", "iPod Touch 3rd gen",

View File

@@ -3,10 +3,12 @@
#include <stdio.h>
#include <string.h>
#include "TracyCallstack.hpp"
#include "TracyDebug.hpp"
#include "TracyFastVector.hpp"
#include "TracyStringHelpers.hpp"
#include "../common/TracyAlloc.hpp"
#include "TracyDebug.hpp"
#include "../common/TracySystem.hpp"
#ifdef TRACY_HAS_CALLSTACK
@@ -31,7 +33,6 @@
# include <dlfcn.h>
# include <cxxabi.h>
# include <stdlib.h>
# include "TracyFastVector.hpp"
#elif TRACY_HAS_CALLSTACK == 5
# include <dlfcn.h>
# include <cxxabi.h>
@@ -66,7 +67,7 @@ extern "C"
extern "C" const char* ___tracy_demangle( const char* mangled );
#ifndef TRACY_DEMANGLE
constexpr size_t ___tracy_demangle_buffer_len = 1024*1024;
constexpr size_t ___tracy_demangle_buffer_len = 1024*1024;
char* ___tracy_demangle_buffer;
void ___tracy_init_demangle_buffer()
@@ -90,9 +91,177 @@ extern "C" const char* ___tracy_demangle( const char* mangled )
#endif
#endif
#if TRACY_HAS_CALLSTACK == 3
# define TRACY_USE_IMAGE_CACHE
# include <link.h>
#endif
namespace tracy
{
#ifdef TRACY_USE_IMAGE_CACHE
// when we have access to dl_iterate_phdr(), we can build a cache of address ranges to image paths
// so we can quickly determine which image an address falls into.
// We refresh this cache only when we hit an address that doesn't fall into any known range.
class ImageCache
{
public:
struct ImageEntry
{
void* m_startAddress = nullptr;
void* m_endAddress = nullptr;
char* m_name = nullptr;
};
ImageCache()
: m_images( 512 )
{
Refresh();
}
~ImageCache()
{
Clear();
}
const ImageEntry* GetImageForAddress( void* address )
{
const ImageEntry* entry = GetImageForAddressImpl( address );
if( !entry )
{
Refresh();
return GetImageForAddressImpl( address );
}
return entry;
}
private:
tracy::FastVector<ImageEntry> m_images;
bool m_updated = false;
bool m_haveMainImageName = false;
static int Callback( struct dl_phdr_info* info, size_t size, void* data )
{
ImageCache* cache = reinterpret_cast<ImageCache*>( data );
const auto startAddress = reinterpret_cast<void*>( info->dlpi_addr );
if( cache->Contains( startAddress ) ) return 0;
const uint32_t headerCount = info->dlpi_phnum;
assert( headerCount > 0);
const auto endAddress = reinterpret_cast<void*>( info->dlpi_addr +
info->dlpi_phdr[info->dlpi_phnum - 1].p_vaddr + info->dlpi_phdr[info->dlpi_phnum - 1].p_memsz);
ImageEntry* image = cache->m_images.push_next();
image->m_startAddress = startAddress;
image->m_endAddress = endAddress;
// the base executable name isn't provided when iterating with dl_iterate_phdr,
// we will have to patch the executable image name outside this callback
if( info->dlpi_name && info->dlpi_name[0] != '\0' )
{
size_t sz = strlen( info->dlpi_name ) + 1;
image->m_name = (char*)tracy_malloc( sz );
memcpy( image->m_name, info->dlpi_name, sz );
}
else
{
image->m_name = nullptr;
}
cache->m_updated = true;
return 0;
}
bool Contains( void* startAddress ) const
{
return std::any_of( m_images.begin(), m_images.end(), [startAddress]( const ImageEntry& entry ) { return startAddress == entry.m_startAddress; } );
}
void Refresh()
{
m_updated = false;
dl_iterate_phdr( Callback, this );
if( m_updated )
{
std::sort( m_images.begin(), m_images.end(),
[]( const ImageEntry& lhs, const ImageEntry& rhs ) { return lhs.m_startAddress > rhs.m_startAddress; } );
// patch the main executable image name here, as calling dl_* functions inside the dl_iterate_phdr callback might cause deadlocks
UpdateMainImageName();
}
}
void UpdateMainImageName()
{
if( m_haveMainImageName )
{
return;
}
for( ImageEntry& entry : m_images )
{
if( entry.m_name == nullptr )
{
Dl_info dlInfo;
if( dladdr( (void *)entry.m_startAddress, &dlInfo ) )
{
if( dlInfo.dli_fname )
{
size_t sz = strlen( dlInfo.dli_fname ) + 1;
entry.m_name = (char*)tracy_malloc( sz );
memcpy( entry.m_name, dlInfo.dli_fname, sz );
}
}
// we only expect one entry to be null for the main executable entry
break;
}
}
m_haveMainImageName = true;
}
const ImageEntry* GetImageForAddressImpl( void* address ) const
{
auto it = std::lower_bound( m_images.begin(), m_images.end(), address,
[]( const ImageEntry& lhs, const void* rhs ) { return lhs.m_startAddress > rhs; } );
if( it != m_images.end() && address < it->m_endAddress )
{
return it;
}
return nullptr;
}
void Clear()
{
for( ImageEntry& entry : m_images )
{
tracy_free( entry.m_name );
}
m_images.clear();
m_haveMainImageName = false;
}
};
#endif //#ifdef TRACY_USE_IMAGE_CACHE
// when "TRACY_SYMBOL_OFFLINE_RESOLVE" is set, instead of fully resolving symbols at runtime,
// simply resolve the offset and image name (which will be enough the resolving to be done offline)
#ifdef TRACY_SYMBOL_OFFLINE_RESOLVE
constexpr bool s_shouldResolveSymbolsOffline = true;
#else
static bool s_shouldResolveSymbolsOffline = false;
bool ShouldResolveSymbolsOffline()
{
const char* symbolOfflineResolve = GetEnvVar( "TRACY_SYMBOL_OFFLINE_RESOLVE" );
return (symbolOfflineResolve && symbolOfflineResolve[0] == '1');
}
#endif // #ifdef TRACY_SYMBOL_OFFLINE_RESOLVE
#if TRACY_HAS_CALLSTACK == 1
enum { MaxCbTrace = 64 };
@@ -108,13 +277,18 @@ extern "C"
typedef BOOL (__stdcall *t_SymFromInlineContext)( HANDLE hProcess, DWORD64 Address, ULONG InlineContext, PDWORD64 Displacement, PSYMBOL_INFO Symbol );
typedef BOOL (__stdcall *t_SymGetLineFromInlineContext)( HANDLE hProcess, DWORD64 qwAddr, ULONG InlineContext, DWORD64 qwModuleBaseAddress, PDWORD pdwDisplacement, PIMAGEHLP_LINE64 Line64 );
TRACY_API ___tracy_t_RtlWalkFrameChain ___tracy_RtlWalkFrameChain = 0;
t_SymAddrIncludeInlineTrace _SymAddrIncludeInlineTrace = 0;
t_SymQueryInlineTrace _SymQueryInlineTrace = 0;
t_SymFromInlineContext _SymFromInlineContext = 0;
t_SymGetLineFromInlineContext _SymGetLineFromInlineContext = 0;
}
typedef unsigned long (__stdcall *___tracy_t_RtlWalkFrameChain)( void**, unsigned long, unsigned long );
___tracy_t_RtlWalkFrameChain ___tracy_RtlWalkFrameChainPtr = nullptr;
TRACY_API unsigned long ___tracy_RtlWalkFrameChain( void** callers, unsigned long count, unsigned long flags)
{
return ___tracy_RtlWalkFrameChainPtr(callers, count, flags);
}
}
struct ModuleCache
{
@@ -136,18 +310,19 @@ struct KernelDriver
KernelDriver* s_krnlCache = nullptr;
size_t s_krnlCacheCnt;
void InitCallstackCritical()
{
___tracy_RtlWalkFrameChain = (___tracy_t_RtlWalkFrameChain)GetProcAddress( GetModuleHandleA( "ntdll.dll" ), "RtlWalkFrameChain" );
___tracy_RtlWalkFrameChainPtr = (___tracy_t_RtlWalkFrameChain)GetProcAddress( GetModuleHandleA( "ntdll.dll" ), "RtlWalkFrameChain" );
}
void InitCallstack()
void DbgHelpInit()
{
_SymAddrIncludeInlineTrace = (t_SymAddrIncludeInlineTrace)GetProcAddress( GetModuleHandleA( "dbghelp.dll" ), "SymAddrIncludeInlineTrace" );
_SymQueryInlineTrace = (t_SymQueryInlineTrace)GetProcAddress( GetModuleHandleA( "dbghelp.dll" ), "SymQueryInlineTrace" );
_SymFromInlineContext = (t_SymFromInlineContext)GetProcAddress( GetModuleHandleA( "dbghelp.dll" ), "SymFromInlineContext" );
_SymGetLineFromInlineContext = (t_SymGetLineFromInlineContext)GetProcAddress( GetModuleHandleA( "dbghelp.dll" ), "SymGetLineFromInlineContext" );
if( s_shouldResolveSymbolsOffline ) return;
_SymAddrIncludeInlineTrace = (t_SymAddrIncludeInlineTrace)GetProcAddress(GetModuleHandleA("dbghelp.dll"), "SymAddrIncludeInlineTrace");
_SymQueryInlineTrace = (t_SymQueryInlineTrace)GetProcAddress(GetModuleHandleA("dbghelp.dll"), "SymQueryInlineTrace");
_SymFromInlineContext = (t_SymFromInlineContext)GetProcAddress(GetModuleHandleA("dbghelp.dll"), "SymFromInlineContext");
_SymGetLineFromInlineContext = (t_SymGetLineFromInlineContext)GetProcAddress(GetModuleHandleA("dbghelp.dll"), "SymGetLineFromInlineContext");
#ifdef TRACY_DBGHELP_LOCK
DBGHELP_INIT;
@@ -157,9 +332,78 @@ void InitCallstack()
SymInitialize( GetCurrentProcess(), nullptr, true );
SymSetOptions( SYMOPT_LOAD_LINES );
#ifdef TRACY_DBGHELP_LOCK
DBGHELP_UNLOCK;
#endif
}
DWORD64 DbgHelpLoadSymbolsForModule( const char* imageName, uint64_t baseOfDll, uint32_t bllSize )
{
if( s_shouldResolveSymbolsOffline ) return 0;
return SymLoadModuleEx( GetCurrentProcess(), nullptr, imageName, nullptr, baseOfDll, bllSize, nullptr, 0 );
}
ModuleCache* LoadSymbolsForModuleAndCache( const char* imageName, uint32_t imageNameLength, uint64_t baseOfDll, uint32_t dllSize )
{
DbgHelpLoadSymbolsForModule( imageName, baseOfDll, dllSize );
ModuleCache* cachedModule = s_modCache->push_next();
cachedModule->start = baseOfDll;
cachedModule->end = baseOfDll + dllSize;
// when doing offline symbol resolution, we must store the full path of the dll for the resolving to work
if( s_shouldResolveSymbolsOffline )
{
cachedModule->name = (char*)tracy_malloc_fast(imageNameLength + 1);
memcpy(cachedModule->name, imageName, imageNameLength);
cachedModule->name[imageNameLength] = '\0';
}
else
{
auto ptr = imageName + imageNameLength;
while (ptr > imageName && *ptr != '\\' && *ptr != '/') ptr--;
if (ptr > imageName) ptr++;
const auto namelen = imageName + imageNameLength - ptr;
cachedModule->name = (char*)tracy_malloc_fast(namelen + 3);
cachedModule->name[0] = '[';
memcpy(cachedModule->name + 1, ptr, namelen);
cachedModule->name[namelen + 1] = ']';
cachedModule->name[namelen + 2] = '\0';
}
return cachedModule;
}
void InitCallstack()
{
#ifndef TRACY_SYMBOL_OFFLINE_RESOLVE
s_shouldResolveSymbolsOffline = ShouldResolveSymbolsOffline();
#endif //#ifndef TRACY_SYMBOL_OFFLINE_RESOLVE
if( s_shouldResolveSymbolsOffline )
{
TracyDebug("TRACY: enabling offline symbol resolving!\n");
}
DbgHelpInit();
#ifdef TRACY_DBGHELP_LOCK
DBGHELP_LOCK;
#endif
// use TRACY_NO_DBGHELP_INIT_LOAD=1 to disable preloading of driver
// and process module symbol loading at startup time - they will be loaded on demand later
// Sometimes this process can take a very long time and prevent resolving callstack frames
// symbols during that time.
const char* noInitLoadEnv = GetEnvVar( "TRACY_NO_DBGHELP_INIT_LOAD" );
const bool initTimeModuleLoad = !( noInitLoadEnv && noInitLoadEnv[0] == '1' );
if ( !initTimeModuleLoad )
{
TracyDebug("TRACY: skipping init time dbghelper module load\n");
}
DWORD needed;
LPVOID dev[4096];
if( EnumDeviceDrivers( dev, sizeof(dev), &needed ) != 0 )
if( initTimeModuleLoad && EnumDeviceDrivers( dev, sizeof(dev), &needed ) != 0 )
{
char windir[MAX_PATH];
if( !GetWindowsDirectoryA( windir, sizeof( windir ) ) ) memcpy( windir, "c:\\windows", 11 );
@@ -193,7 +437,7 @@ void InitCallstack()
path = full;
}
SymLoadModuleEx( GetCurrentProcess(), nullptr, path, nullptr, (DWORD64)dev[i], 0, nullptr, 0 );
DbgHelpLoadSymbolsForModule( path, (DWORD64)dev[i], 0 );
const auto psz = strlen( path );
auto pptr = (char*)tracy_malloc_fast( psz+1 );
@@ -214,7 +458,7 @@ void InitCallstack()
HANDLE proc = GetCurrentProcess();
HMODULE mod[1024];
if( EnumProcessModules( proc, mod, sizeof( mod ), &needed ) != 0 )
if( initTimeModuleLoad && EnumProcessModules( proc, mod, sizeof( mod ), &needed ) != 0 )
{
const auto sz = needed / sizeof( HMODULE );
for( size_t i=0; i<sz; i++ )
@@ -222,27 +466,13 @@ void InitCallstack()
MODULEINFO info;
if( GetModuleInformation( proc, mod[i], &info, sizeof( info ) ) != 0 )
{
const auto base = uint64_t( info.lpBaseOfDll );
char name[1024];
const auto res = GetModuleFileNameA( mod[i], name, 1021 );
if( res > 0 )
const auto nameLength = GetModuleFileNameA( mod[i], name, 1021 );
if( nameLength > 0 )
{
// This may be a new module loaded since our call to SymInitialize.
// Just in case, force DbgHelp to load its pdb !
SymLoadModuleEx(proc, NULL, name, NULL, (DWORD64)info.lpBaseOfDll, info.SizeOfImage, NULL, 0);
auto ptr = name + res;
while( ptr > name && *ptr != '\\' && *ptr != '/' ) ptr--;
if( ptr > name ) ptr++;
const auto namelen = name + res - ptr;
auto cache = s_modCache->push_next();
cache->start = base;
cache->end = base + info.SizeOfImage;
cache->name = (char*)tracy_malloc_fast( namelen+3 );
cache->name[0] = '[';
memcpy( cache->name+1, ptr, namelen );
cache->name[namelen+1] = ']';
cache->name[namelen+2] = '\0';
LoadSymbolsForModuleAndCache( name, nameLength, (DWORD64)info.lpBaseOfDll, info.SizeOfImage );
}
}
}
@@ -259,6 +489,8 @@ void EndCallstack()
const char* DecodeCallstackPtrFast( uint64_t ptr )
{
if( s_shouldResolveSymbolsOffline ) return "[unresolved]";
static char ret[MaxNameSize];
const auto proc = GetCurrentProcess();
@@ -294,7 +526,13 @@ const char* GetKernelModulePath( uint64_t addr )
return it->path;
}
static const char* GetModuleNameAndPrepareSymbols( uint64_t addr )
struct ModuleNameAndBaseAddress
{
const char* name;
uint64_t baseAddr;
};
ModuleNameAndBaseAddress GetModuleNameAndPrepareSymbols( uint64_t addr )
{
if( ( addr >> 63 ) != 0 )
{
@@ -303,17 +541,17 @@ static const char* GetModuleNameAndPrepareSymbols( uint64_t addr )
auto it = std::lower_bound( s_krnlCache, s_krnlCache + s_krnlCacheCnt, addr, []( const KernelDriver& lhs, const uint64_t& rhs ) { return lhs.addr > rhs; } );
if( it != s_krnlCache + s_krnlCacheCnt )
{
return it->mod;
return ModuleNameAndBaseAddress{ it->mod, it->addr };
}
}
return "<kernel>";
return ModuleNameAndBaseAddress{ "<kernel>", addr };
}
for( auto& v : *s_modCache )
{
if( addr >= v.start && addr < v.end )
{
return v.name;
return ModuleNameAndBaseAddress{ v.name, v.start };
}
}
@@ -334,35 +572,33 @@ static const char* GetModuleNameAndPrepareSymbols( uint64_t addr )
if( addr >= base && addr < base + info.SizeOfImage )
{
char name[1024];
const auto res = GetModuleFileNameA( mod[i], name, 1021 );
if( res > 0 )
const auto nameLength = GetModuleFileNameA( mod[i], name, 1021 );
if( nameLength > 0 )
{
// since this is the first time we encounter this module, load its symbols (needed for modules loaded after SymInitialize)
SymLoadModuleEx(proc, NULL, name, NULL, (DWORD64)info.lpBaseOfDll, info.SizeOfImage, NULL, 0);
auto ptr = name + res;
while( ptr > name && *ptr != '\\' && *ptr != '/' ) ptr--;
if( ptr > name ) ptr++;
const auto namelen = name + res - ptr;
auto cache = s_modCache->push_next();
cache->start = base;
cache->end = base + info.SizeOfImage;
cache->name = (char*)tracy_malloc_fast( namelen+3 );
cache->name[0] = '[';
memcpy( cache->name+1, ptr, namelen );
cache->name[namelen+1] = ']';
cache->name[namelen+2] = '\0';
return cache->name;
ModuleCache* cachedModule = LoadSymbolsForModuleAndCache( name, nameLength, (DWORD64)info.lpBaseOfDll, info.SizeOfImage );
return ModuleNameAndBaseAddress{ cachedModule->name, cachedModule->start };
}
}
}
}
}
return "[unknown]";
return ModuleNameAndBaseAddress{ "[unknown]", 0x0 };
}
CallstackSymbolData DecodeSymbolAddress( uint64_t ptr )
{
CallstackSymbolData sym;
if( s_shouldResolveSymbolsOffline )
{
sym.file = "[unknown]";
sym.line = 0;
sym.needFree = false;
return sym;
}
IMAGEHLP_LINE64 line;
DWORD displacement = 0;
line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
@@ -390,15 +626,32 @@ CallstackSymbolData DecodeSymbolAddress( uint64_t ptr )
CallstackEntryData DecodeCallstackPtr( uint64_t ptr )
{
int write;
const auto proc = GetCurrentProcess();
InitRpmalloc();
#ifdef TRACY_DBGHELP_LOCK
DBGHELP_LOCK;
#endif
const auto moduleName = GetModuleNameAndPrepareSymbols(ptr);
InitRpmalloc();
const ModuleNameAndBaseAddress moduleNameAndAddress = GetModuleNameAndPrepareSymbols( ptr );
if( s_shouldResolveSymbolsOffline )
{
#ifdef TRACY_DBGHELP_LOCK
DBGHELP_UNLOCK;
#endif
cb_data[0].symAddr = ptr - moduleNameAndAddress.baseAddr;
cb_data[0].symLen = 0;
cb_data[0].name = CopyStringFast("[unresolved]");
cb_data[0].file = CopyStringFast("[unknown]");
cb_data[0].line = 0;
return { cb_data, 1, moduleNameAndAddress.name };
}
int write;
const auto proc = GetCurrentProcess();
#if !defined TRACY_NO_CALLSTACK_INLINES
BOOL doInline = FALSE;
@@ -448,7 +701,7 @@ CallstackEntryData DecodeCallstackPtr( uint64_t ptr )
cb_data[write].line = line.LineNumber;
}
cb_data[write].name = symValid ? CopyStringFast( si->Name, si->NameLen ) : CopyStringFast( moduleName );
cb_data[write].name = symValid ? CopyStringFast( si->Name, si->NameLen ) : CopyStringFast( moduleNameAndAddress.name );
cb_data[write].file = CopyStringFast( filename );
if( symValid )
{
@@ -481,7 +734,7 @@ CallstackEntryData DecodeCallstackPtr( uint64_t ptr )
cb.line = line.LineNumber;
}
cb.name = symInlineValid ? CopyStringFast( si->Name, si->NameLen ) : CopyStringFast( moduleName );
cb.name = symInlineValid ? CopyStringFast( si->Name, si->NameLen ) : CopyStringFast( moduleNameAndAddress.name );
cb.file = CopyStringFast( filename );
if( symInlineValid )
{
@@ -502,17 +755,21 @@ CallstackEntryData DecodeCallstackPtr( uint64_t ptr )
DBGHELP_UNLOCK;
#endif
return { cb_data, uint8_t( cb_num ), moduleName };
return { cb_data, uint8_t( cb_num ), moduleNameAndAddress.name };
}
#elif TRACY_HAS_CALLSTACK == 2 || TRACY_HAS_CALLSTACK == 3 || TRACY_HAS_CALLSTACK == 4 || TRACY_HAS_CALLSTACK == 6
enum { MaxCbTrace = 64 };
struct backtrace_state* cb_bts;
struct backtrace_state* cb_bts = nullptr;
int cb_num;
CallstackEntry cb_data[MaxCbTrace];
int cb_fixup;
#ifdef TRACY_USE_IMAGE_CACHE
static ImageCache* s_imageCache = nullptr;
#endif //#ifdef TRACY_USE_IMAGE_CACHE
#ifdef TRACY_DEBUGINFOD
debuginfod_client* s_debuginfod;
@@ -525,13 +782,14 @@ struct DebugInfo
int fd;
};
FastVector<DebugInfo> s_di_known( 16 );
static FastVector<DebugInfo>* s_di_known;
#endif
#ifdef __linux
struct KernelSymbol
{
uint64_t addr;
uint32_t size;
const char* name;
const char* mod;
};
@@ -543,10 +801,11 @@ static void InitKernelSymbols()
{
FILE* f = fopen( "/proc/kallsyms", "rb" );
if( !f ) return;
tracy::FastVector<KernelSymbol> tmpSym( 1024 );
tracy::FastVector<KernelSymbol> tmpSym( 512 * 1024 );
size_t linelen = 16 * 1024; // linelen must be big enough to prevent reallocs in getline()
auto linebuf = (char*)tracy_malloc( linelen );
ssize_t sz;
size_t validCnt = 0;
while( ( sz = getline( &linebuf, &linelen, f ) ) != -1 )
{
auto ptr = linebuf;
@@ -579,7 +838,7 @@ static void InitKernelSymbols()
}
if( addr == 0 ) continue;
ptr++;
if( *ptr != 'T' && *ptr != 't' ) continue;
const bool valid = *ptr == 'T' || *ptr == 't';
ptr += 2;
const auto namestart = ptr;
while( *ptr != '\t' && *ptr != '\n' ) ptr++;
@@ -594,20 +853,28 @@ static void InitKernelSymbols()
modend = ptr;
}
auto strname = (char*)tracy_malloc_fast( nameend - namestart + 1 );
memcpy( strname, namestart, nameend - namestart );
strname[nameend-namestart] = '\0';
char* strname = nullptr;
char* strmod = nullptr;
if( modstart )
if( valid )
{
strmod = (char*)tracy_malloc_fast( modend - modstart + 1 );
memcpy( strmod, modstart, modend - modstart );
strmod[modend-modstart] = '\0';
validCnt++;
strname = (char*)tracy_malloc_fast( nameend - namestart + 1 );
memcpy( strname, namestart, nameend - namestart );
strname[nameend-namestart] = '\0';
if( modstart )
{
strmod = (char*)tracy_malloc_fast( modend - modstart + 1 );
memcpy( strmod, modstart, modend - modstart );
strmod[modend-modstart] = '\0';
}
}
auto sym = tmpSym.push_next();
sym->addr = addr;
sym->size = 0;
sym->name = strname;
sym->mod = strmod;
}
@@ -615,11 +882,22 @@ static void InitKernelSymbols()
fclose( f );
if( tmpSym.empty() ) return;
std::sort( tmpSym.begin(), tmpSym.end(), []( const KernelSymbol& lhs, const KernelSymbol& rhs ) { return lhs.addr > rhs.addr; } );
s_kernelSymCnt = tmpSym.size();
s_kernelSym = (KernelSymbol*)tracy_malloc_fast( sizeof( KernelSymbol ) * s_kernelSymCnt );
memcpy( s_kernelSym, tmpSym.data(), sizeof( KernelSymbol ) * s_kernelSymCnt );
TracyDebug( "Loaded %zu kernel symbols\n", s_kernelSymCnt );
std::sort( tmpSym.begin(), tmpSym.end(), []( const KernelSymbol& lhs, const KernelSymbol& rhs ) { return lhs.addr < rhs.addr; } );
for( size_t i=0; i<tmpSym.size()-1; i++ )
{
if( tmpSym[i].name ) tmpSym[i].size = tmpSym[i+1].addr - tmpSym[i].addr;
}
s_kernelSymCnt = validCnt;
s_kernelSym = (KernelSymbol*)tracy_malloc_fast( sizeof( KernelSymbol ) * validCnt );
auto dst = s_kernelSym;
for( auto& v : tmpSym )
{
if( v.name ) *dst++ = v;
}
assert( dst == s_kernelSym + validCnt );
TracyDebug( "Loaded %zu kernel symbols (%zu code sections)\n", tmpSym.size(), validCnt );
}
#endif
@@ -628,8 +906,7 @@ char* NormalizePath( const char* path )
if( path[0] != '/' ) return nullptr;
const char* ptr = path;
const char* end = path;
while( *end ) end++;
const char* end = path + strlen( path );
char* res = (char*)tracy_malloc( end - ptr + 1 );
size_t rsz = 0;
@@ -685,7 +962,26 @@ void InitCallstackCritical()
void InitCallstack()
{
cb_bts = backtrace_create_state( nullptr, 0, nullptr, nullptr );
InitRpmalloc();
#ifdef TRACY_USE_IMAGE_CACHE
s_imageCache = (ImageCache*)tracy_malloc( sizeof( ImageCache ) );
new(s_imageCache) ImageCache();
#endif //#ifdef TRACY_USE_IMAGE_CACHE
#ifndef TRACY_SYMBOL_OFFLINE_RESOLVE
s_shouldResolveSymbolsOffline = ShouldResolveSymbolsOffline();
#endif //#ifndef TRACY_SYMBOL_OFFLINE_RESOLVE
if( s_shouldResolveSymbolsOffline )
{
cb_bts = nullptr; // disable use of libbacktrace calls
TracyDebug("TRACY: enabling offline symbol resolving!\n");
}
else
{
cb_bts = backtrace_create_state( nullptr, 0, nullptr, nullptr );
}
#ifndef TRACY_DEMANGLE
___tracy_init_demangle_buffer();
#endif
@@ -695,6 +991,8 @@ void InitCallstack()
#endif
#ifdef TRACY_DEBUGINFOD
s_debuginfod = debuginfod_begin();
s_di_known = (FastVector<DebugInfo>*)tracy_malloc( sizeof( FastVector<DebugInfo> ) );
new (s_di_known) FastVector<DebugInfo>( 16 );
#endif
}
@@ -725,11 +1023,11 @@ DebugInfo* FindDebugInfo( FastVector<DebugInfo>& vec, const uint8_t* buildid_dat
int GetDebugInfoDescriptor( const char* buildid_data, size_t buildid_size, const char* filename )
{
auto buildid = (uint8_t*)buildid_data;
auto it = FindDebugInfo( s_di_known, buildid, buildid_size );
auto it = FindDebugInfo( *s_di_known, buildid, buildid_size );
if( it ) return it->fd >= 0 ? dup( it->fd ) : -1;
int fd = debuginfod_find_debuginfo( s_debuginfod, buildid, buildid_size, nullptr );
it = s_di_known.push_next();
it = s_di_known->push_next();
it->buildid_size = buildid_size;
it->buildid = (uint8_t*)tracy_malloc( buildid_size );
memcpy( it->buildid, buildid, buildid_size );
@@ -744,7 +1042,7 @@ int GetDebugInfoDescriptor( const char* buildid_data, size_t buildid_size, const
const uint8_t* GetBuildIdForImage( const char* image, size_t& size )
{
assert( image );
for( auto& v : s_di_known )
for( auto& v : *s_di_known )
{
if( strcmp( image, v.filename ) == 0 )
{
@@ -763,11 +1061,21 @@ debuginfod_client* GetDebuginfodClient()
void EndCallstack()
{
#ifdef TRACY_USE_IMAGE_CACHE
if( s_imageCache )
{
s_imageCache->~ImageCache();
tracy_free( s_imageCache );
}
#endif //#ifdef TRACY_USE_IMAGE_CACHE
#ifndef TRACY_DEMANGLE
___tracy_free_demangle_buffer();
#endif
#ifdef TRACY_DEBUGINFOD
ClearDebugInfoVector( s_di_known );
ClearDebugInfoVector( *s_di_known );
s_di_known->~FastVector<DebugInfo>();
tracy_free( s_di_known );
debuginfod_end( s_debuginfod );
#endif
}
@@ -824,7 +1132,15 @@ static void SymbolAddressErrorCb( void* data, const char* /*msg*/, int /*errnum*
CallstackSymbolData DecodeSymbolAddress( uint64_t ptr )
{
CallstackSymbolData sym;
backtrace_pcinfo( cb_bts, ptr, SymbolAddressDataCb, SymbolAddressErrorCb, &sym );
if( cb_bts )
{
backtrace_pcinfo( cb_bts, ptr, SymbolAddressDataCb, SymbolAddressErrorCb, &sym );
}
else
{
SymbolAddressErrorCb(&sym, nullptr, 0);
}
return sym;
}
@@ -927,33 +1243,67 @@ void SymInfoError( void* /*data*/, const char* /*msg*/, int /*errnum*/ )
cb_data[cb_num-1].symAddr = 0;
}
void GetSymbolForOfflineResolve(void* address, uint64_t imageBaseAddress, CallstackEntry& cbEntry)
{
// tagged with a string that we can identify as an unresolved symbol
cbEntry.name = CopyStringFast( "[unresolved]" );
// set .so relative offset so it can be resolved offline
cbEntry.symAddr = (uint64_t)address - imageBaseAddress;
cbEntry.symLen = 0x0;
cbEntry.file = CopyStringFast( "[unknown]" );
cbEntry.line = 0;
}
CallstackEntryData DecodeCallstackPtr( uint64_t ptr )
{
InitRpmalloc();
if( ptr >> 63 == 0 )
{
cb_num = 0;
backtrace_pcinfo( cb_bts, ptr, CallstackDataCb, CallstackErrorCb, nullptr );
assert( cb_num > 0 );
const char* imageName = nullptr;
uint64_t imageBaseAddress = 0x0;
backtrace_syminfo( cb_bts, ptr, SymInfoCallback, SymInfoError, nullptr );
const char* symloc = nullptr;
#ifdef TRACY_USE_IMAGE_CACHE
const auto* image = s_imageCache->GetImageForAddress((void*)ptr);
if( image )
{
imageName = image->m_name;
imageBaseAddress = uint64_t(image->m_startAddress);
}
#else
Dl_info dlinfo;
if( dladdr( (void*)ptr, &dlinfo ) ) symloc = dlinfo.dli_fname;
if( dladdr( (void*)ptr, &dlinfo ) )
{
imageName = dlinfo.dli_fname;
imageBaseAddress = uint64_t( dlinfo.dli_fbase );
}
#endif
return { cb_data, uint8_t( cb_num ), symloc ? symloc : "[unknown]" };
if( s_shouldResolveSymbolsOffline )
{
cb_num = 1;
GetSymbolForOfflineResolve( (void*)ptr, imageBaseAddress, cb_data[0] );
}
else
{
cb_num = 0;
backtrace_pcinfo( cb_bts, ptr, CallstackDataCb, CallstackErrorCb, nullptr );
assert( cb_num > 0 );
backtrace_syminfo( cb_bts, ptr, SymInfoCallback, SymInfoError, nullptr );
}
return { cb_data, uint8_t( cb_num ), imageName ? imageName : "[unknown]" };
}
#ifdef __linux
else if( s_kernelSym )
{
auto it = std::lower_bound( s_kernelSym, s_kernelSym + s_kernelSymCnt, ptr, []( const KernelSymbol& lhs, const uint64_t& rhs ) { return lhs.addr > rhs; } );
auto it = std::lower_bound( s_kernelSym, s_kernelSym + s_kernelSymCnt, ptr, []( const KernelSymbol& lhs, const uint64_t& rhs ) { return lhs.addr + lhs.size < rhs; } );
if( it != s_kernelSym + s_kernelSymCnt )
{
cb_data[0].name = CopyStringFast( it->name );
cb_data[0].file = CopyStringFast( "<kernel>" );
cb_data[0].line = 0;
cb_data[0].symLen = 0;
cb_data[0].symLen = it->size;
cb_data[0].symAddr = it->addr;
return { cb_data, 1, it->mod ? it->mod : "<kernel>" };
}

View File

@@ -3,22 +3,28 @@
#include "TracyCallstack.h"
#if TRACY_HAS_CALLSTACK == 2 || TRACY_HAS_CALLSTACK == 5
# include <unwind.h>
#elif TRACY_HAS_CALLSTACK >= 3
# include <execinfo.h>
#endif
#ifndef TRACY_HAS_CALLSTACK
namespace tracy
{
static tracy_force_inline void* Callstack( int depth ) { return nullptr; }
static constexpr bool has_callstack() { return false; }
static tracy_force_inline void* Callstack( int32_t /*depth*/ ) { return nullptr; }
}
#else
#if TRACY_HAS_CALLSTACK == 2 || TRACY_HAS_CALLSTACK == 5
# include <unwind.h>
#elif TRACY_HAS_CALLSTACK >= 3
# ifdef TRACY_LIBUNWIND_BACKTRACE
// libunwind is, in general, significantly faster than execinfo based backtraces
# define UNW_LOCAL_ONLY
# include <libunwind.h>
# else
# include <execinfo.h>
# endif
#endif
#ifdef TRACY_DEBUGINFOD
# include <elfutils/debuginfod.h>
#endif
@@ -31,6 +37,8 @@ static tracy_force_inline void* Callstack( int depth ) { return nullptr; }
namespace tracy
{
static constexpr bool has_callstack() { return true; }
struct CallstackSymbolData
{
const char* file;
@@ -72,11 +80,10 @@ debuginfod_client* GetDebuginfodClient();
extern "C"
{
typedef unsigned long (__stdcall *___tracy_t_RtlWalkFrameChain)( void**, unsigned long, unsigned long );
TRACY_API extern ___tracy_t_RtlWalkFrameChain ___tracy_RtlWalkFrameChain;
TRACY_API unsigned long ___tracy_RtlWalkFrameChain( void**, unsigned long, unsigned long );
}
static tracy_force_inline void* Callstack( int depth )
static tracy_force_inline void* Callstack( int32_t depth )
{
assert( depth >= 1 && depth < 63 );
auto trace = (uintptr_t*)tracy_malloc( ( 1 + depth ) * sizeof( uintptr_t ) );
@@ -105,7 +112,7 @@ static _Unwind_Reason_Code tracy_unwind_callback( struct _Unwind_Context* ctx, v
return _URC_NO_REASON;
}
static tracy_force_inline void* Callstack( int depth )
static tracy_force_inline void* Callstack( int32_t depth )
{
assert( depth >= 1 && depth < 63 );
@@ -120,12 +127,18 @@ static tracy_force_inline void* Callstack( int depth )
#elif TRACY_HAS_CALLSTACK == 3 || TRACY_HAS_CALLSTACK == 4 || TRACY_HAS_CALLSTACK == 6
static tracy_force_inline void* Callstack( int depth )
static tracy_force_inline void* Callstack( int32_t depth )
{
assert( depth >= 1 );
auto trace = (uintptr_t*)tracy_malloc( ( 1 + (size_t)depth ) * sizeof( uintptr_t ) );
#ifdef TRACY_LIBUNWIND_BACKTRACE
size_t num = unw_backtrace( (void**)(trace+1), depth );
#else
const auto num = (size_t)backtrace( (void**)(trace+1), depth );
#endif
*trace = num;
return trace;

View File

@@ -0,0 +1,121 @@
#ifdef __linux__
#include <algorithm>
#include <assert.h>
#include <fcntl.h>
#include <limits.h>
#include <unistd.h>
#include "TracyDebug.hpp"
#include "TracyKCore.hpp"
#include "../common/TracyAlloc.hpp"
#if !defined(__GLIBC__) && !defined(__WORDSIZE)
// include __WORDSIZE headers for musl
# include <bits/reg.h>
#endif
namespace tracy
{
using elf_half = uint16_t;
using elf_word = uint32_t;
using elf_sword = int32_t;
#if __WORDSIZE == 32
using elf_addr = uint32_t;
using elf_off = uint32_t;
using elf_xword = uint32_t;
#else
using elf_addr = uint64_t;
using elf_off = uint64_t;
using elf_xword = uint64_t;
#endif
struct elf_ehdr
{
unsigned char e_ident[16];
elf_half e_type;
elf_half e_machine;
elf_word e_version;
elf_addr e_entry;
elf_off e_phoff;
elf_off e_shoff;
elf_word e_flags;
elf_half e_ehsize;
elf_half e_phentsize;
elf_half e_phnum;
elf_half e_shentsize;
elf_half e_shnum;
elf_half e_shstrndx;
};
struct elf_phdr
{
elf_word p_type;
elf_word p_flags;
elf_off p_offset;
elf_addr p_vaddr;
elf_addr p_paddr;
elf_xword p_filesz;
elf_xword p_memsz;
uint64_t p_align; // include 32-bit-only flags field for 32-bit compatibility
};
KCore::KCore()
: m_offsets( 16 )
{
m_fd = open( "/proc/kcore", O_RDONLY );
if( m_fd == -1 ) return;
elf_ehdr ehdr;
if( read( m_fd, &ehdr, sizeof( ehdr ) ) != sizeof( ehdr ) ) goto err;
assert( ehdr.e_phentsize == sizeof( elf_phdr ) );
for( elf_half i=0; i<ehdr.e_phnum; i++ )
{
elf_phdr phdr;
if( lseek( m_fd, ehdr.e_phoff + i * ehdr.e_phentsize, SEEK_SET ) == -1 ) goto err;
if( read( m_fd, &phdr, sizeof( phdr ) ) != sizeof( phdr ) ) goto err;
if( phdr.p_type != 1 ) continue;
auto ptr = m_offsets.push_next();
ptr->start = phdr.p_vaddr;
ptr->size = phdr.p_memsz;
ptr->offset = phdr.p_offset;
}
std::sort( m_offsets.begin(), m_offsets.end(), []( const Offset& lhs, const Offset& rhs ) { return lhs.start < rhs.start; } );
TracyDebug( "KCore: %zu segments found\n", m_offsets.size() );
return;
err:
close( m_fd );
m_fd = -1;
}
KCore::~KCore()
{
if( m_fd != -1 ) close( m_fd );
}
void* KCore::Retrieve( uint64_t addr, uint64_t size ) const
{
if( m_fd == -1 ) return nullptr;
auto it = std::lower_bound( m_offsets.begin(), m_offsets.end(), addr, []( const Offset& lhs, uint64_t rhs ) { return lhs.start + lhs.size < rhs; } );
if( it == m_offsets.end() ) return nullptr;
if( addr + size > it->start + it->size ) return nullptr;
if( lseek( m_fd, it->offset + addr - it->start, SEEK_SET ) == -1 ) return nullptr;
auto ptr = tracy_malloc( size );
if( read( m_fd, ptr, size ) != ssize_t( size ) )
{
tracy_free( ptr );
return nullptr;
}
return ptr;
}
}
#endif

View File

@@ -0,0 +1,37 @@
#ifndef __TRACYKCORE_HPP__
#define __TRACYKCORE_HPP__
#ifdef __linux__
#include <stdint.h>
#include "TracyFastVector.hpp"
namespace tracy
{
class KCore
{
struct Offset
{
uint64_t start;
uint64_t size;
uint64_t offset;
};
public:
KCore();
~KCore();
void* Retrieve( uint64_t addr, uint64_t size ) const;
private:
int m_fd;
FastVector<Offset> m_offsets;
};
}
#endif
#endif

Some files were not shown because too many files have changed in this diff Show More