mirror of
https://github.com/nicbarker/clay.git
synced 2025-05-12 13:28:07 +00:00
Compare commits
6 Commits
c3fcf6ce12
...
951d785deb
Author | SHA1 | Date | |
---|---|---|---|
|
951d785deb | ||
|
4612481d25 | ||
|
0a703de69a | ||
|
cb62db77e3 | ||
|
ea6109bd0b | ||
|
c0dac38c87 |
@ -3,17 +3,38 @@ project(clay)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
|
||||
|
||||
option(CLAY_INCLUDE_ALL_EXAMPLES "Build all examples" ON)
|
||||
option(CLAY_INCLUDE_DEMOS "Build video demo and website" OFF)
|
||||
option(CLAY_INCLUDE_CPP_EXAMPLE "Build C++ example" OFF)
|
||||
option(CLAY_INCLUDE_RAYLIB_EXAMPLES "Build raylib examples" OFF)
|
||||
option(CLAY_INCLUDE_SDL2_EXAMPLES "Build SDL 2 examples" OFF)
|
||||
option(CLAY_INCLUDE_SDL3_EXAMPLES "Build SDL 3 examples" OFF)
|
||||
|
||||
message(STATUS "CLAY_INCLUDE_DEMOS: ${CLAY_INCLUDE_DEMOS}")
|
||||
|
||||
if(APPLE)
|
||||
enable_language(OBJC)
|
||||
endif()
|
||||
|
||||
add_subdirectory("examples/cpp-project-example")
|
||||
add_subdirectory("examples/raylib-multi-context")
|
||||
add_subdirectory("examples/raylib-sidebar-scrolling-container")
|
||||
# add_subdirectory("examples/cairo-pdf-rendering") Some issue with github actions populating cairo, disable for now
|
||||
if(NOT MSVC)
|
||||
add_subdirectory("examples/clay-official-website")
|
||||
add_subdirectory("examples/SDL3-simple-demo")
|
||||
if(CLAY_INCLUDE_ALL_EXAMPLES OR CLAY_INCLUDE_CPP_EXAMPLE)
|
||||
add_subdirectory("examples/cpp-project-example")
|
||||
endif()
|
||||
add_subdirectory("examples/introducing-clay-video-demo")
|
||||
add_subdirectory("examples/SDL2-video-demo")
|
||||
if(CLAY_INCLUDE_ALL_EXAMPLES OR CLAY_INCLUDE_DEMOS)
|
||||
if(NOT MSVC)
|
||||
add_subdirectory("examples/clay-official-website")
|
||||
endif()
|
||||
add_subdirectory("examples/introducing-clay-video-demo")
|
||||
endif ()
|
||||
|
||||
if(CLAY_INCLUDE_ALL_EXAMPLES OR CLAY_INCLUDE_RAYLIB_EXAMPLES)
|
||||
add_subdirectory("examples/raylib-multi-context")
|
||||
add_subdirectory("examples/raylib-sidebar-scrolling-container")
|
||||
endif ()
|
||||
if(CLAY_INCLUDE_ALL_EXAMPLES OR CLAY_INCLUDE_SDL2_EXAMPLES)
|
||||
add_subdirectory("examples/SDL2-video-demo")
|
||||
endif ()
|
||||
if(NOT MSVC AND (CLAY_INCLUDE_ALL_EXAMPLES OR CLAY_INCLUDE_SDL3_EXAMPLES))
|
||||
add_subdirectory("examples/SDL3-simple-demo")
|
||||
endif()
|
||||
|
||||
# add_subdirectory("examples/cairo-pdf-rendering") Some issue with github actions populating cairo, disable for now
|
||||
|
155
README.md
155
README.md
@ -20,26 +20,17 @@ _An example GUI application built with clay_
|
||||
|
||||
## Quick Start
|
||||
|
||||
1. Download or clone clay.h and include it after defining `CLAY_IMPLEMENTATION` in one file.
|
||||
Download or clone clay.h and include it after defining `CLAY_IMPLEMENTATION` in one file.
|
||||
|
||||
```C
|
||||
// Must be defined in one file, _before_ #include "clay.h"
|
||||
#define CLAY_IMPLEMENTATION
|
||||
#include "clay.h"
|
||||
```
|
||||
#include "../../clay.h"
|
||||
|
||||
2. Ask clay for how much static memory it needs using [Clay_MinMemorySize()](#clay_minmemorysize), create an Arena for it to use with [Clay_CreateArenaWithCapacityAndMemory(size, void *memory)](#clay_createarenawithcapacityandmemory).
|
||||
const Clay_Color COLOR_LIGHT = (Clay_Color) {224, 215, 210, 255};
|
||||
const Clay_Color COLOR_RED = (Clay_Color) {168, 66, 28, 255};
|
||||
const Clay_Color COLOR_ORANGE = (Clay_Color) {225, 138, 50, 255};
|
||||
|
||||
```C
|
||||
// Note: malloc is only used here as an example, any allocator that provides
|
||||
// a pointer to addressable memory of at least totalMemorySize will work
|
||||
uint64_t totalMemorySize = Clay_MinMemorySize();
|
||||
Clay_Arena arena = Clay_CreateArenaWithCapacityAndMemory(totalMemorySize, malloc(totalMemorySize));
|
||||
```
|
||||
|
||||
3. Create an [ErrorHandler](#clay_errorhandler) for Clay to call when an internal error occurs, and initialize Clay with the Arena and handler by calling [Clay_Initialize(arena, dimensions, errorHandler)](#clay_initialize).
|
||||
|
||||
```C
|
||||
void HandleClayErrors(Clay_ErrorData errorData) {
|
||||
// See the Clay_ErrorData struct for more information
|
||||
printf("%s", errorData.errorText.chars);
|
||||
@ -48,51 +39,16 @@ void HandleClayErrors(Clay_ErrorData errorData) {
|
||||
}
|
||||
}
|
||||
|
||||
// In your startup function
|
||||
Clay_Initialize(arena, (Clay_Dimensions) { screenWidth, screenHeight }, (Clay_ErrorHandler) { HandleClayErrors });
|
||||
```
|
||||
|
||||
4. Provide a `MeasureText(text, config)` function pointer with [Clay_SetMeasureTextFunction(function)](#clay_setmeasuretextfunction) so that clay can measure and wrap text.
|
||||
|
||||
```C
|
||||
// Example measure text function
|
||||
static inline Clay_Dimensions MeasureText(Clay_String *text, Clay_TextElementConfig *config) {
|
||||
static inline Clay_Dimensions MeasureText(Clay_StringSlice text, Clay_TextElementConfig *config, uintptr_t userData) {
|
||||
// Clay_TextElementConfig contains members such as fontId, fontSize, letterSpacing etc
|
||||
// Note: Clay_String->chars is not guaranteed to be null terminated
|
||||
return (Clay_Dimensions) {
|
||||
.width = text.length * config->fontSize, // <- this will only work for monospace fonts, see the renderers/ directory for more advanced text measurement
|
||||
.height = config->fontSize
|
||||
};
|
||||
}
|
||||
|
||||
// Tell clay how to measure text
|
||||
Clay_SetMeasureTextFunction(MeasureText);
|
||||
```
|
||||
|
||||
4. **Optional** - Call [Clay_SetLayoutDimensions(dimensions)](#clay_setlayoutdimensions) if the window size of your application has changed.
|
||||
|
||||
```C
|
||||
// Update internal layout dimensions
|
||||
Clay_SetLayoutDimensions((Clay_Dimensions) { screenWidth, screenHeight });
|
||||
```
|
||||
|
||||
5. **Optional** - Call [Clay_SetPointerState(pointerPosition, isPointerDown)](#clay_setpointerstate) if you want to use mouse interactions.
|
||||
|
||||
```C
|
||||
// Update internal pointer position for handling mouseover / click / touch events
|
||||
Clay_SetPointerState((Clay_Vector2) { mousePositionX, mousePositionY }, isMouseDown);
|
||||
```
|
||||
|
||||
6. **Optional** - Call [Clay_UpdateScrollContainers(enableDragScrolling, scrollDelta, deltaTime)](#clay_updatescrollcontainers) if you want to use clay's built in scrolling containers.
|
||||
|
||||
```C
|
||||
// Update internal pointer position for handling mouseover / click / touch events
|
||||
Clay_UpdateScrollContainers(true, (Clay_Vector2) { mouseWheelX, mouseWheelY }, deltaTime);
|
||||
```
|
||||
|
||||
7. Call [Clay_BeginLayout()](#clay_beginlayout) and declare your layout using the provided macros.
|
||||
|
||||
```C
|
||||
const Clay_Color COLOR_LIGHT = (Clay_Color) {224, 215, 210, 255};
|
||||
const Clay_Color COLOR_RED = (Clay_Color) {168, 66, 28, 255};
|
||||
const Clay_Color COLOR_ORANGE = (Clay_Color) {225, 138, 50, 255};
|
||||
|
||||
// Layout config is just a struct that can be declared statically, or inline
|
||||
Clay_LayoutConfig sidebarItemLayout = (Clay_LayoutConfig) {
|
||||
.sizing = { .width = CLAY_SIZING_GROW(0), .height = CLAY_SIZING_FIXED(50) },
|
||||
@ -103,48 +59,61 @@ void SidebarItemComponent() {
|
||||
CLAY(CLAY_LAYOUT(sidebarItemLayout), CLAY_RECTANGLE({ .color = COLOR_ORANGE })) {}
|
||||
}
|
||||
|
||||
// An example function to begin the "root" of your layout tree
|
||||
Clay_RenderCommandArray CreateLayout() {
|
||||
Clay_BeginLayout();
|
||||
int main() {
|
||||
// Note: malloc is only used here as an example, any allocator that provides
|
||||
// a pointer to addressable memory of at least totalMemorySize will work
|
||||
uint64_t totalMemorySize = Clay_MinMemorySize();
|
||||
Clay_Arena arena = Clay_CreateArenaWithCapacityAndMemory(totalMemorySize, malloc(totalMemorySize));
|
||||
|
||||
// An example of laying out a UI with a fixed width sidebar and flexible width main content
|
||||
CLAY(CLAY_ID("OuterContainer"), CLAY_LAYOUT({ .sizing = {CLAY_SIZING_GROW(0), CLAY_SIZING_GROW(0)}, .padding = CLAY_PADDING_ALL(16), .childGap = 16 }), CLAY_RECTANGLE({ .color = {250,250,255,255} })) {
|
||||
CLAY(CLAY_ID("SideBar"),
|
||||
CLAY_LAYOUT({ .layoutDirection = CLAY_TOP_TO_BOTTOM, .sizing = { .width = CLAY_SIZING_FIXED(300), .height = CLAY_SIZING_GROW(0) }, .padding = CLAY_PADDING_ALL(16), .childGap = 16 }),
|
||||
CLAY_RECTANGLE({ .color = COLOR_LIGHT })
|
||||
) {
|
||||
CLAY(CLAY_ID("ProfilePictureOuter"), CLAY_LAYOUT({ .sizing = { .width = CLAY_SIZING_GROW(0) }, .padding = CLAY_PADDING_ALL(16, .childGap = 16, .childAlignment = { .y = CLAY_ALIGN_Y_CENTER }), CLAY_RECTANGLE({ .color = COLOR_RED })) {
|
||||
CLAY(CLAY_ID("ProfilePicture"), CLAY_LAYOUT({ .sizing = { .width = CLAY_SIZING_FIXED(60), .height = CLAY_SIZING_FIXED(60) }}), CLAY_IMAGE({ .imageData = &profilePicture, .sourceDimensions = {60, 60} })) {}
|
||||
CLAY_TEXT(CLAY_STRING("Clay - UI Library"), CLAY_TEXT_CONFIG({ .fontSize = 24, .textColor = {255, 255, 255, 255} }));
|
||||
Clay_Initialize(arena, (Clay_Dimensions) { screenWidth, screenHeight }, (Clay_ErrorHandler) { HandleClayErrors });
|
||||
|
||||
while(renderLoop()) { // Will be different for each renderer / environment
|
||||
// Optional: Update internal layout dimensions to support resizing
|
||||
Clay_SetLayoutDimensions((Clay_Dimensions) { screenWidth, screenHeight });
|
||||
// Optional: Update internal pointer position for handling mouseover / click / touch events - needed for scrolling & debug tools
|
||||
Clay_SetPointerState((Clay_Vector2) { mousePositionX, mousePositionY }, isMouseDown);
|
||||
// Optional: Update internal pointer position for handling mouseover / click / touch events - needed for scrolling and debug tools
|
||||
Clay_UpdateScrollContainers(true, (Clay_Vector2) { mouseWheelX, mouseWheelY }, deltaTime);
|
||||
|
||||
// All clay layouts are declared between Clay_BeginLayout and Clay_EndLayout
|
||||
Clay_BeginLayout();
|
||||
|
||||
// An example of laying out a UI with a fixed width sidebar and flexible width main content
|
||||
CLAY(CLAY_ID("OuterContainer"), CLAY_LAYOUT({ .sizing = {CLAY_SIZING_GROW(0), CLAY_SIZING_GROW(0)}, .padding = CLAY_PADDING_ALL(16), .childGap = 16 }), CLAY_RECTANGLE({ .color = {250,250,255,255} })) {
|
||||
CLAY(CLAY_ID("SideBar"),
|
||||
CLAY_LAYOUT({ .layoutDirection = CLAY_TOP_TO_BOTTOM, .sizing = { .width = CLAY_SIZING_FIXED(300), .height = CLAY_SIZING_GROW(0) }, .padding = CLAY_PADDING_ALL(16), .childGap = 16 }),
|
||||
CLAY_RECTANGLE({ .color = COLOR_LIGHT })
|
||||
) {
|
||||
CLAY(CLAY_ID("ProfilePictureOuter"), CLAY_LAYOUT({ .sizing = { .width = CLAY_SIZING_GROW(0) }, .padding = CLAY_PADDING_ALL(16), .childGap = 16, .childAlignment = { .y = CLAY_ALIGN_Y_CENTER } }), CLAY_RECTANGLE({ .color = COLOR_RED })) {
|
||||
CLAY(CLAY_ID("ProfilePicture"), CLAY_LAYOUT({ .sizing = { .width = CLAY_SIZING_FIXED(60), .height = CLAY_SIZING_FIXED(60) }}), CLAY_IMAGE({ .imageData = &profilePicture, .sourceDimensions = {60, 60} })) {}
|
||||
CLAY_TEXT(CLAY_STRING("Clay - UI Library"), CLAY_TEXT_CONFIG({ .fontSize = 24, .textColor = {255, 255, 255, 255} }));
|
||||
}
|
||||
|
||||
// Standard C code like loops etc work inside components
|
||||
for (int i = 0; i < 5; i++) {
|
||||
SidebarItemComponent();
|
||||
}
|
||||
|
||||
CLAY(CLAY_ID("MainContent"), CLAY_LAYOUT({ .sizing = { .width = CLAY_SIZING_GROW(0), .height = CLAY_SIZING_GROW(0) }}), CLAY_RECTANGLE({ .color = COLOR_LIGHT })) {}
|
||||
}
|
||||
|
||||
// Standard C code like loops etc work inside components
|
||||
for (int i = 0; i < 5; i++) {
|
||||
SidebarItemComponent();
|
||||
// All clay layouts are declared between Clay_BeginLayout and Clay_EndLayout
|
||||
Clay_RenderCommandArray renderCommands = Clay_EndLayout();
|
||||
|
||||
// More comprehensive rendering examples can be found in the renderers/ directory
|
||||
for (int i = 0; i < renderCommands.length; i++) {
|
||||
Clay_RenderCommand *renderCommand = &renderCommands.internalArray[i];
|
||||
|
||||
switch (renderCommand->commandType) {
|
||||
case CLAY_RENDER_COMMAND_TYPE_RECTANGLE: {
|
||||
DrawRectangle(
|
||||
renderCommand->boundingBox,
|
||||
renderCommand->config.rectangleElementConfig->color);
|
||||
}
|
||||
// ... Implement handling of other command types
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
CLAY(CLAY_ID("MainContent"), CLAY_LAYOUT({ .sizing = { .width = CLAY_SIZING_GROW(0), .height = CLAY_SIZING_GROW(0) }}), CLAY_RECTANGLE({ .color = COLOR_LIGHT })) {}
|
||||
}
|
||||
// ...
|
||||
});
|
||||
```
|
||||
|
||||
8. Call [Clay_EndLayout()](#clay_endlayout) and process the resulting [Clay_RenderCommandArray](#clay_rendercommandarray) in your choice of renderer.
|
||||
|
||||
```C
|
||||
Clay_RenderCommandArray renderCommands = Clay_EndLayout();
|
||||
|
||||
for (int i = 0; i < renderCommands.length; i++) {
|
||||
Clay_RenderCommand *renderCommand = &renderCommands.internalArray[i];
|
||||
|
||||
switch (renderCommand->commandType) {
|
||||
case CLAY_RENDER_COMMAND_TYPE_RECTANGLE: {
|
||||
DrawRectangle(
|
||||
renderCommand->boundingBox,
|
||||
renderCommand->config.rectangleElementConfig->color);
|
||||
}
|
||||
// ... Implement handling of other command types
|
||||
}
|
||||
}
|
||||
```
|
||||
@ -819,7 +788,7 @@ if (buttonIsHovered && leftMouseButtonPressed) {
|
||||
|
||||
### CLAY_IDI()
|
||||
|
||||
`Clay_ElementId CLAY_IDI(char *label, int index)`
|
||||
`Clay_ElementId CLAY_IDI(char *label, int32_t index)`
|
||||
|
||||
An offset version of [CLAY_ID](#clay_id). Generates a [Clay_ElementId](#clay_elementid) string id from the provided `char *label`, combined with the `int index`. Used for generating ids for sequential elements (such as in a `for` loop) without having to construct dynamic strings at runtime.
|
||||
|
||||
@ -866,7 +835,7 @@ for (int i = 0; i < headerButtons.length; i++) {
|
||||
|
||||
### CLAY_IDI_LOCAL()
|
||||
|
||||
`Clay_ElementId CLAY_IDI_LOCAL(char *label, int index)`
|
||||
`Clay_ElementId CLAY_IDI_LOCAL(char *label, int32_t index)`
|
||||
|
||||
An offset version of [CLAY_ID_LOCAL](#clay_local_id). Generates a [Clay_ElementId](#clay_elementid) string id from the provided `char *label`, combined with the `int index`. Used for generating ids for sequential elements (such as in a `for` loop) without having to construct dynamic strings at runtime.
|
||||
|
||||
|
@ -184,7 +184,8 @@ ElementConfigUnion :: struct #raw_union {
|
||||
RenderCommand :: struct {
|
||||
boundingBox: BoundingBox,
|
||||
config: ElementConfigUnion,
|
||||
text: String,
|
||||
text: StringSlice,
|
||||
zIndex: i32,
|
||||
id: u32,
|
||||
commandType: RenderCommandType,
|
||||
}
|
||||
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
10
clay.h
10
clay.h
@ -471,7 +471,8 @@ CLAY__TYPEDEF(Clay_RenderCommandType, CLAY_PACKED_ENUM {
|
||||
CLAY__TYPEDEF(Clay_RenderCommand, struct {
|
||||
Clay_BoundingBox boundingBox;
|
||||
Clay_ElementConfigUnion config;
|
||||
Clay_String text; // TODO I wish there was a way to avoid having to have this on every render command
|
||||
Clay_StringSlice text; // TODO I wish there was a way to avoid having to have this on every render command
|
||||
int32_t zIndex;
|
||||
uint32_t id;
|
||||
Clay_RenderCommandType commandType;
|
||||
});
|
||||
@ -2600,6 +2601,7 @@ void Clay__CalculateFinalLayout() {
|
||||
Clay__AddRenderCommand(CLAY__INIT(Clay_RenderCommand) {
|
||||
.boundingBox = clipHashMapItem->boundingBox,
|
||||
.config = { .scrollElementConfig = Clay__StoreScrollElementConfig(CLAY__INIT(Clay_ScrollElementConfig)CLAY__DEFAULT_STRUCT) },
|
||||
.zIndex = root->zIndex,
|
||||
.id = Clay__RehashWithNumber(rootElement->id, 10), // TODO need a better strategy for managing derived ids
|
||||
.commandType = CLAY_RENDER_COMMAND_TYPE_SCISSOR_START,
|
||||
});
|
||||
@ -2732,7 +2734,8 @@ void Clay__CalculateFinalLayout() {
|
||||
Clay__AddRenderCommand(CLAY__INIT(Clay_RenderCommand) {
|
||||
.boundingBox = { currentElementBoundingBox.x, currentElementBoundingBox.y + yPosition, wrappedLine.dimensions.width, wrappedLine.dimensions.height }, // TODO width
|
||||
.config = configUnion,
|
||||
.text = wrappedLine.line,
|
||||
.text = CLAY__INIT(Clay_StringSlice) { .length = wrappedLine.line.length, .chars = wrappedLine.line.chars, .baseChars = currentElement->childrenOrTextContent.textElementData->text.chars },
|
||||
.zIndex = root->zIndex,
|
||||
.id = Clay__HashNumber(lineIndex, currentElement->id).id,
|
||||
.commandType = CLAY_RENDER_COMMAND_TYPE_TEXT,
|
||||
});
|
||||
@ -3945,7 +3948,8 @@ Clay_RenderCommandArray Clay_EndLayout() {
|
||||
context->warningsEnabled = true;
|
||||
}
|
||||
if (context->booleanWarnings.maxElementsExceeded) {
|
||||
Clay__AddRenderCommand(CLAY__INIT(Clay_RenderCommand ) { .boundingBox = { context->layoutDimensions.width / 2 - 59 * 4, context->layoutDimensions.height / 2, 0, 0 }, .config = { .textElementConfig = &Clay__DebugView_ErrorTextConfig }, .text = CLAY_STRING("Clay Error: Layout elements exceeded Clay__maxElementCount"), .commandType = CLAY_RENDER_COMMAND_TYPE_TEXT });
|
||||
Clay_String message = CLAY_STRING("Clay Error: Layout elements exceeded Clay__maxElementCount");
|
||||
Clay__AddRenderCommand(CLAY__INIT(Clay_RenderCommand ) { .boundingBox = { context->layoutDimensions.width / 2 - 59 * 4, context->layoutDimensions.height / 2, 0, 0 }, .config = { .textElementConfig = &Clay__DebugView_ErrorTextConfig }, .text = CLAY__INIT(Clay_StringSlice) { .length = message.length, .chars = message.chars, .baseChars = message.chars }, .commandType = CLAY_RENDER_COMMAND_TYPE_TEXT });
|
||||
} else {
|
||||
Clay__CalculateFinalLayout();
|
||||
}
|
||||
|
@ -33,12 +33,12 @@ static inline Clay_Dimensions SDL_MeasureText(Clay_StringSlice text, Clay_TextEl
|
||||
return (Clay_Dimensions) { (float) width, (float) height };
|
||||
}
|
||||
|
||||
static void Label(const Clay_String text)
|
||||
static void Label(const Clay_String text, const int cornerRadius)
|
||||
{
|
||||
CLAY(CLAY_LAYOUT({ .padding = {8, 8} }),
|
||||
CLAY_RECTANGLE({
|
||||
.color = Clay_Hovered() ? COLOR_BLUE : COLOR_ORANGE,
|
||||
.cornerRadius = (Clay_CornerRadius){ 8, 8, 8, 8 },
|
||||
.cornerRadius = cornerRadius,
|
||||
})) {
|
||||
CLAY_TEXT(text, CLAY_TEXT_CONFIG({
|
||||
.textColor = { 255, 255, 255, 255 },
|
||||
@ -48,6 +48,24 @@ static void Label(const Clay_String text)
|
||||
}
|
||||
}
|
||||
|
||||
static void LabelBorder(const Clay_String text, const int cornerRadius, const int thickness)
|
||||
{
|
||||
CLAY(
|
||||
CLAY_LAYOUT({
|
||||
.padding = {16, 16, 8, 8 } }),
|
||||
CLAY_BORDER_OUTSIDE_RADIUS(
|
||||
thickness,
|
||||
COLOR_BLUE,
|
||||
cornerRadius)
|
||||
){
|
||||
CLAY_TEXT(text, CLAY_TEXT_CONFIG({
|
||||
.textColor = { 255, 255, 255, 255 },
|
||||
.fontId = FONT_ID,
|
||||
.fontSize = 24,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
static Clay_RenderCommandArray Clay_CreateLayout()
|
||||
{
|
||||
Clay_BeginLayout();
|
||||
@ -65,13 +83,21 @@ static Clay_RenderCommandArray Clay_CreateLayout()
|
||||
.padding = { 10, 10 },
|
||||
.layoutDirection = CLAY_TOP_TO_BOTTOM,
|
||||
}),
|
||||
CLAY_BORDER({
|
||||
.left = { 20, COLOR_BLUE },
|
||||
.right = { 20, COLOR_BLUE },
|
||||
.bottom = { 20, COLOR_BLUE }
|
||||
}),
|
||||
CLAY_RECTANGLE({
|
||||
.color = COLOR_LIGHT,
|
||||
})
|
||||
) {
|
||||
Label(CLAY_STRING("Button 1"));
|
||||
Label(CLAY_STRING("Button 2"));
|
||||
Label(CLAY_STRING("Button 3"));
|
||||
Label(CLAY_STRING("Rounded - Button 1"), 10);
|
||||
Label(CLAY_STRING("Straight - Button 2") , 0);
|
||||
Label(CLAY_STRING("Rounded+ - Button 3") , 20);
|
||||
LabelBorder(CLAY_STRING("Border - Button 4"), 0, 5);
|
||||
LabelBorder(CLAY_STRING("RoundedBorder - Button 5"), 10, 5);
|
||||
LabelBorder(CLAY_STRING("RoundedBorder - Button 6"), 40, 15);
|
||||
}
|
||||
return Clay_EndLayout();
|
||||
}
|
||||
|
@ -96,6 +96,11 @@
|
||||
{name: 'length', type: 'uint32_t' },
|
||||
{name: 'chars', type: 'uint32_t' },
|
||||
]};
|
||||
let stringSliceDefinition = { type: 'struct', members: [
|
||||
{name: 'length', type: 'uint32_t' },
|
||||
{name: 'chars', type: 'uint32_t' },
|
||||
{name: 'baseChars', type: 'uint32_t' },
|
||||
]};
|
||||
let borderDefinition = { type: 'struct', members: [
|
||||
{name: 'width', type: 'uint32_t'},
|
||||
{name: 'color', ...colorDefinition},
|
||||
@ -155,7 +160,8 @@
|
||||
{ name: 'height', type: 'float' },
|
||||
]},
|
||||
{ name: 'config', type: 'uint32_t'},
|
||||
{ name: 'text', ...stringDefinition },
|
||||
{ name: 'text', ...stringSliceDefinition },
|
||||
{ name: 'zIndex', type: 'int32_t' },
|
||||
{ name: 'id', type: 'uint32_t' },
|
||||
{ name: 'commandType', type: 'uint32_t', },
|
||||
]
|
||||
|
Binary file not shown.
@ -96,6 +96,11 @@
|
||||
{name: 'length', type: 'uint32_t' },
|
||||
{name: 'chars', type: 'uint32_t' },
|
||||
]};
|
||||
let stringSliceDefinition = { type: 'struct', members: [
|
||||
{name: 'length', type: 'uint32_t' },
|
||||
{name: 'chars', type: 'uint32_t' },
|
||||
{name: 'baseChars', type: 'uint32_t' },
|
||||
]};
|
||||
let borderDefinition = { type: 'struct', members: [
|
||||
{name: 'width', type: 'uint32_t'},
|
||||
{name: 'color', ...colorDefinition},
|
||||
@ -155,7 +160,8 @@
|
||||
{ name: 'height', type: 'float' },
|
||||
]},
|
||||
{ name: 'config', type: 'uint32_t'},
|
||||
{ name: 'text', ...stringDefinition },
|
||||
{ name: 'text', ...stringSliceDefinition },
|
||||
{ name: 'zIndex', type: 'int32_t' },
|
||||
{ name: 'id', type: 'uint32_t' },
|
||||
{ name: 'commandType', type: 'uint32_t', },
|
||||
]
|
||||
|
@ -27,7 +27,7 @@ target_link_libraries(clay_examples_raylib_sidebar_scrolling_container PUBLIC ra
|
||||
if(MSVC)
|
||||
set(CMAKE_C_FLAGS_DEBUG "/D CLAY_DEBUG")
|
||||
else()
|
||||
set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -Wall -Werror -DCLAY_DEBUG -fsanitize=address")
|
||||
set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -DCLAY_DEBUG -fsanitize=address")
|
||||
set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -O3")
|
||||
endif()
|
||||
|
||||
|
@ -58,7 +58,7 @@ static void Clay_SDL2_Render(SDL_Renderer *renderer, Clay_RenderCommandArray ren
|
||||
}
|
||||
case CLAY_RENDER_COMMAND_TYPE_TEXT: {
|
||||
Clay_TextElementConfig *config = renderCommand->config.textElementConfig;
|
||||
Clay_String text = renderCommand->text;
|
||||
Clay_StringSlice text = renderCommand->text;
|
||||
char *cloned = (char *)calloc(text.length + 1, 1);
|
||||
memcpy(cloned, text.chars, text.length);
|
||||
TTF_Font* font = fonts[config->fontId].font;
|
||||
|
@ -1,5 +1,4 @@
|
||||
Please note, the SDL3 renderer is not 100% feature complete. It is currently missing:
|
||||
|
||||
- Borders
|
||||
- Images
|
||||
- Scroll / Scissor handling
|
||||
|
@ -2,27 +2,27 @@
|
||||
#include <SDL3/SDL_main.h>
|
||||
#include <SDL3/SDL.h>
|
||||
#include <SDL3_ttf/SDL_ttf.h>
|
||||
#include <math.h> //needed to perform the rounded corners rendering
|
||||
|
||||
/* This needs to be global because the "MeasureText" callback doesn't have a
|
||||
* user data parameter */
|
||||
static TTF_Font *gFonts[1];
|
||||
/* Global for convenience. Even in 4K this is enough for smooth curves (low radius or rect size coupled with
|
||||
* no AA or low resolution might make it appear as jagged curves) */
|
||||
static int NUM_CIRCLE_SEGMENTS = 16;
|
||||
|
||||
//all rendering is performed by a single SDL call, avoiding multiple RenderRect + plumbing choice for circles.
|
||||
static void SDL_RenderRoundedRect(SDL_Renderer *renderer, const SDL_FRect rect, const float cornerRadius, const Clay_Color _color) {
|
||||
/* Even in 4K this is enough for smooth curves (low radius or rect size coupled with
|
||||
* no AA or low resolution might make it appear as jagged curves) */
|
||||
const int NUM_CIRCLE_SEGMENTS = 16;
|
||||
|
||||
//all rendering is performed by a single SDL call, avoiding multiple RenderRect + plumbing choice for circles.
|
||||
static void SDL_RenderFillRoundedRect(SDL_Renderer *renderer, const SDL_FRect rect, const float cornerRadius, const Clay_Color _color) {
|
||||
const SDL_FColor color = { _color.r/255, _color.g/255, _color.b/255, _color.a/255 };
|
||||
|
||||
int indexCount = 0, vertexCount = 0;
|
||||
|
||||
const float minRadius = fminf(rect.w, rect.h) / 2.0f;
|
||||
const float clampedRadius = fminf(cornerRadius, minRadius);
|
||||
const float minRadius = SDL_min(rect.w, rect.h) / 2.0f;
|
||||
const float clampedRadius = SDL_min(cornerRadius, minRadius);
|
||||
|
||||
int totalVertices = 4 + (4 * (NUM_CIRCLE_SEGMENTS * 2)) + 2*4;
|
||||
int totalIndices = 6 + (4 * (NUM_CIRCLE_SEGMENTS * 3)) + 6*4;
|
||||
const int numCircleSegments = SDL_max(NUM_CIRCLE_SEGMENTS, (int) clampedRadius * 0.5f);
|
||||
|
||||
int totalVertices = 4 + (4 * (numCircleSegments * 2)) + 2*4;
|
||||
int totalIndices = 6 + (4 * (numCircleSegments * 3)) + 6*4;
|
||||
|
||||
SDL_Vertex vertices[totalVertices];
|
||||
int indices[totalIndices];
|
||||
@ -41,9 +41,8 @@ static void SDL_RenderRoundedRect(SDL_Renderer *renderer, const SDL_FRect rect,
|
||||
indices[indexCount++] = 3;
|
||||
|
||||
//define rounded corners as triangle fans
|
||||
const float step = M_PI_2 / NUM_CIRCLE_SEGMENTS;
|
||||
for (int i = 0; i < NUM_CIRCLE_SEGMENTS; i++)
|
||||
{
|
||||
const float step = (SDL_PI_F/2) / numCircleSegments;
|
||||
for (int i = 0; i < numCircleSegments; i++) {
|
||||
const float angle1 = (float)i * step;
|
||||
const float angle2 = ((float)i + 1.0f) * step;
|
||||
|
||||
@ -55,11 +54,11 @@ static void SDL_RenderRoundedRect(SDL_Renderer *renderer, const SDL_FRect rect,
|
||||
case 1: cx = rect.x + rect.w - clampedRadius; cy = rect.y + clampedRadius; signX = 1; signY = -1; break; // Top-right
|
||||
case 2: cx = rect.x + rect.w - clampedRadius; cy = rect.y + rect.h - clampedRadius; signX = 1; signY = 1; break; // Bottom-right
|
||||
case 3: cx = rect.x + clampedRadius; cy = rect.y + rect.h - clampedRadius; signX = -1; signY = 1; break; // Bottom-left
|
||||
default: SDL_LogError(SDL_LOG_CATEGORY_ERROR, "Invalid corner index"); return;
|
||||
default: return;
|
||||
}
|
||||
|
||||
vertices[vertexCount++] = (SDL_Vertex){ {cx + cosf(angle1) * clampedRadius * signX, cy + sinf(angle1) * clampedRadius * signY}, color, {0, 0} };
|
||||
vertices[vertexCount++] = (SDL_Vertex){ {cx + cosf(angle2) * clampedRadius * signX, cy + sinf(angle2) * clampedRadius * signY}, color, {0, 0} };
|
||||
vertices[vertexCount++] = (SDL_Vertex){ {cx + SDL_cosf(angle1) * clampedRadius * signX, cy + SDL_sinf(angle1) * clampedRadius * signY}, color, {0, 0} };
|
||||
vertices[vertexCount++] = (SDL_Vertex){ {cx + SDL_cosf(angle2) * clampedRadius * signX, cy + SDL_sinf(angle2) * clampedRadius * signY}, color, {0, 0} };
|
||||
|
||||
indices[indexCount++] = j; // Connect to corresponding central rectangle vertex
|
||||
indices[indexCount++] = vertexCount - 2;
|
||||
@ -113,6 +112,30 @@ static void SDL_RenderRoundedRect(SDL_Renderer *renderer, const SDL_FRect rect,
|
||||
SDL_RenderGeometry(renderer, NULL, vertices, vertexCount, indices, indexCount);
|
||||
}
|
||||
|
||||
static void SDL_RenderArc(SDL_Renderer *renderer, const SDL_FPoint center, const float radius, const float startAngle, const float endAngle, const float thickness, const Clay_Color color) {
|
||||
SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a);
|
||||
|
||||
const float radStart = startAngle * (SDL_PI_F / 180.0f);
|
||||
const float radEnd = endAngle * (SDL_PI_F / 180.0f);
|
||||
|
||||
const int numCircleSegments = SDL_max(NUM_CIRCLE_SEGMENTS, (int)(radius * 1.5f)); //increase circle segments for larger circles, 1.5 is arbitrary.
|
||||
|
||||
const float angleStep = (radEnd - radStart) / (float)numCircleSegments;
|
||||
const float thicknessStep = 0.4f; //arbitrary value to avoid overlapping lines. Changing THICKNESS_STEP or numCircleSegments might cause artifacts.
|
||||
|
||||
for (float t = thicknessStep; t < thickness - thicknessStep; t += thicknessStep) {
|
||||
SDL_FPoint points[numCircleSegments + 1];
|
||||
const float clampedRadius = SDL_max(radius - t, 1.0f);
|
||||
|
||||
for (int i = 0; i <= numCircleSegments; i++) {
|
||||
const float angle = radStart + i * angleStep;
|
||||
points[i] = (SDL_FPoint){
|
||||
SDL_roundf(center.x + SDL_cosf(angle) * clampedRadius),
|
||||
SDL_roundf(center.y + SDL_sinf(angle) * clampedRadius) };
|
||||
}
|
||||
SDL_RenderLines(renderer, points, numCircleSegments + 1);
|
||||
}
|
||||
}
|
||||
|
||||
static void SDL_RenderClayCommands(SDL_Renderer *renderer, Clay_RenderCommandArray *rcommands)
|
||||
{
|
||||
@ -128,16 +151,14 @@ static void SDL_RenderClayCommands(SDL_Renderer *renderer, Clay_RenderCommandArr
|
||||
|
||||
SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a);
|
||||
if (config->cornerRadius.topLeft > 0) {
|
||||
//const float radius = (config->cornerRadius.topLeft * 2) / (float)((bounding_box.width > bounding_box.height) ? bounding_box.height : bounding_box.width);
|
||||
//SDL_RenderRoundedRect(renderer, rect, radius, color);
|
||||
SDL_RenderRoundedRect(renderer, rect, config->cornerRadius.topLeft, color);
|
||||
SDL_RenderFillRoundedRect(renderer, rect, config->cornerRadius.topLeft, color);
|
||||
} else {
|
||||
SDL_RenderFillRect(renderer, &rect);
|
||||
}
|
||||
} break;
|
||||
case CLAY_RENDER_COMMAND_TYPE_TEXT: {
|
||||
const Clay_TextElementConfig *config = rcmd->config.textElementConfig;
|
||||
const Clay_String *text = &rcmd->text;
|
||||
const Clay_StringSlice *text = &rcmd->text;
|
||||
const SDL_Color color = { config->textColor.r, config->textColor.g, config->textColor.b, config->textColor.a };
|
||||
|
||||
TTF_Font *font = gFonts[config->fontId];
|
||||
@ -148,6 +169,72 @@ static void SDL_RenderClayCommands(SDL_Renderer *renderer, Clay_RenderCommandArr
|
||||
SDL_DestroySurface(surface);
|
||||
SDL_DestroyTexture(texture);
|
||||
} break;
|
||||
case CLAY_RENDER_COMMAND_TYPE_BORDER: {
|
||||
const Clay_BorderElementConfig *config = rcmd->config.borderElementConfig;
|
||||
|
||||
const float minRadius = SDL_min(rect.w, rect.h) / 2.0f;
|
||||
const Clay_CornerRadius clampedRadii = {
|
||||
.topLeft = SDL_min(config->cornerRadius.topLeft, minRadius),
|
||||
.topRight = SDL_min(config->cornerRadius.topRight, minRadius),
|
||||
.bottomLeft = SDL_min(config->cornerRadius.bottomLeft, minRadius),
|
||||
.bottomRight = SDL_min(config->cornerRadius.bottomRight, minRadius)
|
||||
};
|
||||
//edges
|
||||
SDL_SetRenderDrawColor(renderer, config->left.color.r, config->left.color.g, config->left.color.b, config->left.color.a);
|
||||
if (config->left.width > 0) {
|
||||
const float starting_y = rect.y + clampedRadii.topLeft;
|
||||
const float length = rect.h - clampedRadii.topLeft - clampedRadii.bottomLeft;
|
||||
SDL_FRect line = { rect.x, starting_y, config->left.width, length };
|
||||
SDL_RenderFillRect(renderer, &line);
|
||||
}
|
||||
if (config->right.width > 0) {
|
||||
const float starting_x = rect.x + rect.w - (float)config->right.width;
|
||||
const float starting_y = rect.y + clampedRadii.topRight;
|
||||
const float length = rect.h - clampedRadii.topRight - clampedRadii.bottomRight;
|
||||
SDL_FRect line = { starting_x, starting_y, config->right.width, length };
|
||||
SDL_RenderFillRect(renderer, &line);
|
||||
}
|
||||
if (config->top.width > 0) {
|
||||
const float starting_x = rect.x + clampedRadii.topLeft;
|
||||
const float length = rect.w - clampedRadii.topLeft - clampedRadii.topRight;
|
||||
SDL_FRect line = { starting_x, rect.y, length, config->top.width };
|
||||
SDL_RenderFillRect(renderer, &line);
|
||||
}
|
||||
if (config->bottom.width > 0) {
|
||||
const float starting_x = rect.x + clampedRadii.bottomLeft;
|
||||
const float starting_y = rect.y + rect.h - (float)config->bottom.width;
|
||||
const float length = rect.w - clampedRadii.bottomLeft - clampedRadii.bottomRight;
|
||||
SDL_FRect line = { starting_x, starting_y, length, config->bottom.width };
|
||||
SDL_SetRenderDrawColor(renderer, config->bottom.color.r, config->bottom.color.g, config->bottom.color.b, config->bottom.color.a);
|
||||
SDL_RenderFillRect(renderer, &line);
|
||||
}
|
||||
//corners
|
||||
if (config->cornerRadius.topLeft > 0) {
|
||||
const float centerX = rect.x + clampedRadii.topLeft -1;
|
||||
const float centerY = rect.y + clampedRadii.topLeft;
|
||||
SDL_RenderArc(renderer, (SDL_FPoint){centerX, centerY}, clampedRadii.topLeft,
|
||||
180.0f, 270.0f, config->top.width, config->top.color);
|
||||
}
|
||||
if (config->cornerRadius.topRight > 0) {
|
||||
const float centerX = rect.x + rect.w - clampedRadii.topRight -1;
|
||||
const float centerY = rect.y + clampedRadii.topRight;
|
||||
SDL_RenderArc(renderer, (SDL_FPoint){centerX, centerY}, clampedRadii.topRight,
|
||||
270.0f, 360.0f, config->top.width, config->top.color);
|
||||
}
|
||||
if (config->cornerRadius.bottomLeft > 0) {
|
||||
const float centerX = rect.x + clampedRadii.bottomLeft -1;
|
||||
const float centerY = rect.y + rect.h - clampedRadii.bottomLeft -1;
|
||||
SDL_RenderArc(renderer, (SDL_FPoint){centerX, centerY}, clampedRadii.bottomLeft,
|
||||
90.0f, 180.0f, config->bottom.width, config->bottom.color);
|
||||
}
|
||||
if (config->cornerRadius.bottomRight > 0) {
|
||||
const float centerX = rect.x + rect.w - clampedRadii.bottomRight -1; //TODO: why need to -1 in all calculations???
|
||||
const float centerY = rect.y + rect.h - clampedRadii.bottomRight -1;
|
||||
SDL_RenderArc(renderer, (SDL_FPoint){centerX, centerY}, clampedRadii.bottomRight,
|
||||
0.0f, 90.0f, config->bottom.width, config->bottom.color);
|
||||
}
|
||||
|
||||
} break;
|
||||
default:
|
||||
SDL_Log("Unknown render command type: %d", rcmd->commandType);
|
||||
}
|
||||
|
@ -138,7 +138,7 @@ void Clay_Raylib_Render(Clay_RenderCommandArray renderCommands)
|
||||
{
|
||||
case CLAY_RENDER_COMMAND_TYPE_TEXT: {
|
||||
// Raylib uses standard C strings so isn't compatible with cheap slices, we need to clone the string to append null terminator
|
||||
Clay_String text = renderCommand->text;
|
||||
Clay_StringSlice text = renderCommand->text;
|
||||
char *cloned = (char *)malloc(text.length + 1);
|
||||
memcpy(cloned, text.chars, text.length);
|
||||
cloned[text.length] = '\0';
|
||||
|
Loading…
Reference in New Issue
Block a user