This commit is contained in:
Stowy 2025-01-05 02:36:13 +01:00 committed by GitHub
commit 52dc16ef8c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
14 changed files with 5648 additions and 0 deletions

4
bindings/jai/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
.build/
main.exe
main.pdb
main.rdi

116
bindings/jai/README.md Normal file
View File

@ -0,0 +1,116 @@
### Jai Language Bindings
This directory contains bindings for the [Jai](https://jai.community/t/overview-of-jai/128) programming language, as well as an example implementation of the Clay demo from the video in Jai.
If you haven't taken a look at the [full documentation for clay](https://github.com/nicbarker/clay/blob/main/README.md), it's recommended that you take a look there first to familiarise yourself with the general concepts. This README is abbreviated and applies to using clay in Jai specifically.
The **most notable difference** between the C API and the Jai bindings is the use of for statements to create the scope for declaring child elements. This is done using some [for_expansion](https://jai.community/t/loops/147) magic.
When using the equivalent of the [Element Macros](https://github.com/nicbarker/clay/blob/main/README.md#element-macros):
```C
// C form of element macros
// Parent element with 8px of padding
CLAY(CLAY_LAYOUT({ .padding = 8 })) {
// Child element 1
CLAY_TEXT(CLAY_STRING("Hello World"), CLAY_TEXT_CONFIG({ .fontSize = 16 }));
// Child element 2 with red background
CLAY(CLAY_RECTANGLE({ .color = COLOR_RED })) {
// etc
}
}
```
```Jai
// Jai form of element macros
// Parent element with 8px of padding
for Clay.Element(Clay.Layout(.{padding = 8})) {
// Child element 1
Clay.Text("Hello World", Clay.TextConfig(.{fontSize = 16}));
// Child element 2 with red background
for Clay.Element(Clay.Rectangle(.{color = COLOR_RED})) {
// etc
}
}
```
> [!WARNING]
> For now, the Jai and Odin bindings are missing the OnHover() and Hovered() functions.
> You can you PointerOver instead, an example of that is in `examples/introducing_clay_video_demo`.
### Quick Start
1. Download the clay-jai directory and copy it into your modules folder.
```Jai
Clay :: #import "clay-jai";
```
1. Ask clay for how much static memory it needs using [Clay.MinMemorySize()](https://github.com/nicbarker/clay/blob/main/README.md#clay_minmemorysize), create an Arena for it to use with [Clay.CreateArenaWithCapacityAndMemory()](https://github.com/nicbarker/clay/blob/main/README.md#clay_createarenawithcapacityandmemory), and initialize it with [Clay.Initialize()](https://github.com/nicbarker/clay/blob/main/README.md#clay_initialize).
```Jai
clay_required_memory := Clay.MinMemorySize();
memory := alloc(clay_required_memory);
clay_memory := Clay.CreateArenaWithCapacityAndMemory(clay_required_memory, memory);
Clay.Initialize(
clay_memory,
Clay.Dimensions.{cast(float, GetScreenWidth()), cast(float, GetScreenHeight())},
.{handle_clay_errors, 0}
);
```
3. Provide a `measure_text(text, config)` proc marked with `#c_call` with [Clay.SetMeasureTextFunction(function)](https://github.com/nicbarker/clay/blob/main/README.md#clay_setmeasuretextfunction) so that clay can measure and wrap text.
```Jai
// Example measure text function
measure_text :: (text: *Clay.String, config: *Clay.TextElementConfig) -> Clay.Dimensions #c_call {
}
// Tell clay how to measure text
Clay.SetMeasureTextFunction(measure_text)
```
4. **Optional** - Call [Clay.SetPointerPosition(pointerPosition)](https://github.com/nicbarker/clay/blob/main/README.md#clay_setpointerposition) if you want to use mouse interactions.
```Jai
// Update internal pointer position for handling mouseover / click / touch events
Clay.SetPointerPosition(.{ mousePositionX, mousePositionY })
```
5. Call [Clay.BeginLayout(screenWidth, screenHeight)](https://github.com/nicbarker/clay/blob/main/README.md#clay_beginlayout) and declare your layout using the provided macros.
```Jai
// An example function to begin the "root" of your layout tree
CreateLayout :: () -> Clay.RenderCommandArray {
Clay.BeginLayout(windowWidth, windowHeight);
for Clay.Element(
Clay.ID("OuterContainer"),
Clay.Layout(.{
sizing = .{Clay.SizingGrow(), Clay.SizingGrow()},
padding = .{16, 16},
childGap = 16
}),
Clay.Rectangle(.{color = .{250, 250, 255, 255}}),
) {
// ...
}
}
```
1. Call [Clay.EndLayout()](https://github.com/nicbarker/clay/blob/main/README.md#clay_endlayout) and process the resulting [Clay.RenderCommandArray](https://github.com/nicbarker/clay/blob/main/README.md#clay_rendercommandarray) in your choice of renderer.
```Jai
render_commands: Clay.RenderCommandArray = Clay.EndLayout();
for 0..render_commands.length - 1 {
render_command := Clay.RenderCommandArray_Get(*render_commands, cast(s32) it);
if #complete render_command.commandType == {
case .RECTANGLE;
DrawRectangle(render_command.boundingBox, render_command.config.rectangleElementConfig.color)
// ... Implement handling of other command types
}
}
```
Please see the [full C documentation for clay](https://github.com/nicbarker/clay/blob/main/README.md) for API details. All public C functions and Macros have Jai binding equivalents, generally of the form `CLAY_RECTANGLE` (C) -> `Clay.Rectangle` (Jai)

1
bindings/jai/clay-jai/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
source/clay.h

View File

@ -0,0 +1,142 @@
AT_COMPILE_TIME :: true;
SOURCE_PATH :: "source";
DECLARATIONS_TO_OMIT :: string.[
// These have custom declaration in module.jai
"Clay_Vector2",
"Clay__ElementConfigType",
"Clay__AlignClay__ElementConfigType",
"Clay_Border",
"Clay__AlignClay_Border",
"Clay_BorderElementConfig",
"Clay__AlignClay_BorderElementConfig",
// These are not supported yet
"Clay_OnHover",
"Clay_Hovered",
];
#if AT_COMPILE_TIME {
#run,stallable {
Compiler.set_build_options_dc(.{do_output=false});
options := Compiler.get_build_options();
args := options.compile_time_command_line;
if !generate_bindings(args, options.minimum_os_version) {
Compiler.compiler_set_workspace_status(.FAILED);
}
}
} else {
#import "System";
main :: () {
set_working_directory(path_strip_filename(get_path_of_running_executable()));
if !generate_bindings(get_command_line_arguments(), #run get_build_options().minimum_os_version) {
exit(1);
}
}
}
generate_bindings :: (args: [] string, minimum_os_version: type_of(Compiler.Build_Options.minimum_os_version)) -> bool {
compile := array_find(args, "-compile");
compile_debug := array_find(args, "-debug");
could_copy := FileUtils.copy_file("../../../clay.h", "source/clay.h");
if !could_copy then return false;
defer if !compile_debug then File.file_delete("source/clay.h");
if compile {
source_file := tprint("%/clay.c", SOURCE_PATH);
success := true;
#if OS == .WINDOWS {
File.make_directory_if_it_does_not_exist("windows", true);
command := ifx compile_debug {
write_string("Compiling debug...\n");
Process.break_command_into_strings("clang -g -gcodeview -c source\\clay.c");
} else {
write_string("Compiling release...\n");
Process.break_command_into_strings("clang -O3 -c source\\clay.c");
}
result := Process.run_command(..command, capture_and_return_output=true, print_captured_output=true);
if result.exit_code != 0 then return false;
defer File.file_delete("clay.o");
write_string("Linking...\n");
command = Process.break_command_into_strings("llvm-ar -rcs windows/clay.lib clay.o");
result = Process.run_command(..command, capture_and_return_output=true, print_captured_output=true);
if result.exit_code != 0 then return false;
} else {
// TODO MacOS
// TODO Linux
assert(false);
}
if !success then return false;
write_string("Succesfully built clay\n");
}
output_filename: string;
options: Generator.Generate_Bindings_Options;
{
using options;
#if OS == .WINDOWS {
array_add(*libpaths, "windows");
output_filename = "windows.jai";
} else {
assert(false);
}
array_add(*libnames, "clay");
array_add(*include_paths, SOURCE_PATH);
array_add(*source_files, tprint("%/clay.h", SOURCE_PATH));
array_add(*strip_prefixes, "Clay_");
auto_detect_enum_prefixes = true;
log_stripped_declarations = true;
generate_compile_time_struct_checks = true;
visitor = clay_visitor;
}
could_generate := Generator.generate_bindings(options, output_filename);
return could_generate;
}
clay_visitor :: (decl: *Generator.Declaration, parent_decl: *Generator.Declaration) -> Generator.Declaration_Visit_Result {
if !parent_decl {
if array_find(DECLARATIONS_TO_OMIT, decl.name) {
decl.decl_flags |= .OMIT_FROM_OUTPUT;
return .STOP;
}
if String.begins_with(decl.name, "Clay__") {
decl.output_name = String.slice(decl.name, 5, decl.name.count - 5);
}
}
return .RECURSE;
}
#scope_file
using Basic :: #import "Basic";
Generator :: #import "Bindings_Generator";
Compiler :: #import "Compiler";
File :: #import "File";
FileUtils :: #import "File_Utilities";
BuildCpp :: #import "BuildCpp";
Process :: #import "Process";
String :: #import "String";
WindowsResources :: #import "Windows_Resources";
#if OS == .WINDOWS {
Windows :: #import "Windows";
getenv :: Windows.getenv;
} else {
Posix :: #import "POSIX";
getenv :: Posix.getenv;
}

View File

@ -0,0 +1,292 @@
/*
These bindings adapt the CLAY macro using some for_expansion trickery, allowing a syntax similar to the one in the Odin bindings.
I'll try to explain here why I did it that way.
In Odin, they can mark the procedure with deferred_none, allowing to call a proc after the current one, which works well with ifs.
@(require_results, deferred_none = _CloseElement)
UI :: proc(configs: ..TypedConfig) -> bool {}
You can then use it like so :
if UI(Layout(), etc..) {Children ...}
So I tried to replicate this in Jai. The first thing I did was to try making a macro returning a bool with a backticked defer in it.
UI :: (configs: ..TypedConfig) -> bool #must #expand {
`defer EndElement();
return true;
}
But this doesn't work if you have two elements side to side, as the end of the first element will be called after the start and the end of the second one.
Another option used in these bindings : https://github.com/nick-celestin-zizic/clay-jai is to have that defer like above and have the macro return nothing. You can then use it like that :
{ UI(Layout()); Children(); }
But I'm not a big fan of that since it's possible to forget the scope braces or to put the children before the element.
Another option to consider is to pass a code block to a macro that puts it between the start and the end.
UI :: (id: ElementId, layout: LayoutConfig, configs: ..ElementConfig, $code: Code) {
OpenElement();
...
#insert code;
CloseElement();
}
UI(..., #code {
Children();
});
However this prevents to refer to variables from the previous scope, and it's also a bit akward to type.
The final solution I found, inspired by the fact that CLAY uses a for loop behind the scene, was to use Jai's for_expansions.
Here is how it works :
InternalElementConfigArray :: struct {
configs: [] TypedConfig;
}
Element :: (configs: ..TypedConfig) -> InternalElementConfigArray #expand {
return .{configs};
}
for_expansion :: (configs_array: InternalElementConfigArray, body: Code, _: For_Flags) #expand {
Jai forces the definition of these
`it_index := 0;
`it := 0;
_OpenElement();
...
#insert body;
_CloseElement();
}
As you can see it's kinda similar to the previous one, but doesn't have the limitation on refering to variable from the calling scope.
Element builds an InternalElementConfigArray that has an array to the TypedConfigs, which will be passed to the for_expansion when placed after a for (this is a Jai feature).
This then allows to write something like :
for Element(Layout()) { Children(); }
With the downside that it's not obvious why the for is there before reading the documentation.
*/
Vector2 :: Math.Vector2;
ElementConfigType :: enum s32 {
NONE :: 0;
RECTANGLE :: 1;
BORDER_CONTAINER :: 2;
FLOATING_CONTAINER :: 4;
SCROLL_CONTAINER :: 8;
IMAGE :: 16;
TEXT :: 32;
CUSTOM :: 64;
CLAY__ELEMENT_CONFIG_TYPE_NONE :: NONE;
CLAY__ELEMENT_CONFIG_TYPE_RECTANGLE :: RECTANGLE;
CLAY__ELEMENT_CONFIG_TYPE_BORDER_CONTAINER :: BORDER_CONTAINER;
CLAY__ELEMENT_CONFIG_TYPE_FLOATING_CONTAINER :: FLOATING_CONTAINER;
CLAY__ELEMENT_CONFIG_TYPE_SCROLL_CONTAINER :: SCROLL_CONTAINER;
CLAY__ELEMENT_CONFIG_TYPE_IMAGE :: IMAGE;
CLAY__ELEMENT_CONFIG_TYPE_TEXT :: TEXT;
CLAY__ELEMENT_CONFIG_TYPE_CUSTOM :: CUSTOM;
// Jai bindings specific types, please don't assume any value in those
// a it might change if the enums above overlap with it
// TODO Check if these values need to be powers of two
ID :: 256;
LAYOUT :: 257;
}
// This is passed to UI so that we can omit layout
TypedConfig :: struct {
type: ElementConfigType;
config: *void;
id: ElementId;
}
BorderData :: struct {
width: u32;
color: Color;
}
BorderElementConfig :: struct {
left: BorderData;
right: BorderData;
top: BorderData;
bottom: BorderData;
betweenChildren: BorderData;
cornerRadius: CornerRadius;
}
make_string :: (str: string) -> String {
clay_string := String.{cast(s32, str.count), str.data};
return clay_string;
}
global_counter := 0;
for_expansion :: (configs_array: InternalElementConfigArray, body: Code, _: For_Flags) #expand {
// Jai forces the definition of these
`it_index := 0;
`it := 0;
_OpenElement();
for config : configs_array.configs {
if config.type == {
case .ID;
_AttachId(config.id);
case .LAYOUT;
_AttachLayoutConfig(cast(*LayoutConfig, config.config));
case;
// config.config is a *void, it stores the address of the pointer that is stored in the union
// as ElementConfigUnion is a union of structs. We can't cast pointers directly to structs,
// we first cast the address of the *void and then dereference it.
// Maybe there's a cast modifier to avoid this, but I don't know it (no_check and trunc didn't work).
_AttachElementConfig(cast(*ElementConfigUnion, *config.config).*, config.type);
}
}
_ElementPostConfiguration();
#insert body;
_CloseElement();
}
Element :: (configs: ..TypedConfig) -> InternalElementConfigArray #expand {
return .{configs};
}
ID :: (label: string, index: u32 = 0) -> TypedConfig {
return .{type = .ID, id = _HashString(make_string(label), index, 0)};
}
Layout :: (config: LayoutConfig) -> TypedConfig {
return .{type = .LAYOUT, config = _StoreLayoutConfig(config)};
}
Rectangle :: (config: RectangleElementConfig) -> TypedConfig {
return .{
type = .RECTANGLE,
config = _StoreRectangleElementConfig(config)
};
}
Floating :: (config: FloatingElementConfig) -> TypedConfig {
return .{type = .FLOATING_CONTAINER, config = _StoreFloatingElementConfig(config)};
}
Scroll :: (config: ScrollElementConfig) -> TypedConfig {
return .{type = .SCROLL_CONTAINER, config = _StoreScrollElementConfig(config)};
}
Image :: (config: ImageElementConfig) -> TypedConfig {
return .{type = .IMAGE, config = _StoreImageElementConfig(config)};
}
Custom :: (config: CustomElementConfig) -> TypedConfig {
return .{type = .CUSTOM, config = _StoreCustomElementConfig(config)};
}
Border :: (config: BorderElementConfig) -> TypedConfig {
return .{type = .BORDER, _StoreBorderElementConfig(config)};
}
BorderOutside :: (outside_borders: BorderData) -> TypedConfig {
return .{
type = .BORDER,
config = _StoreBorderElementConfig(BorderElementConfig.{
left = outside_borders,
right = outside_borders,
top = outside_borders,
bottom = outside_borders,
}),
};
}
BorderOutsideRadius :: (outside_borders: BorderData, radius: float) -> TypedConfig {
return .{
type = .BORDER,
config = _StoreBorderElementConfig(.{
left = outside_borders,
right = outside_borders,
top = outside_borders,
bottom = outside_borders,
cornerRadius = .{radius, radius, radius, radius},
})
};
}
BorderAll :: (all_borders: BorderData) -> TypedConfig {
return .{
type = .BORDER,
config = _StoreBorderElementConfig(.{
left = all_borders,
right = all_borders,
top = all_borders,
bottom = all_borders,
betweenChildren = all_borders,
})
};
}
BorderAllRadius :: (all_borders: BorderData, radius: float) -> TypedConfig {
return .{
type = .BORDER,
config = _StoreBorderElementConfig(.{
left = all_borders,
right = all_borders,
top = all_borders,
bottom = all_borders,
cornerRadius = .{radius, radius, radius, radius},
})
};
}
CornerRadiusAll :: (radius: float) -> CornerRadius {
return .{radius, radius, radius, radius};
}
Text :: (text: string, config: *TextElementConfig) {
_OpenTextElement(make_string(text), config);
}
TextConfig :: (config: TextElementConfig) -> *TextElementConfig {
return _StoreTextElementConfig(config);
}
SizingFit :: (size_min_max: SizingMinMax) -> SizingAxis {
return .{type = .FIT, size = .{minMax = size_min_max}};
}
SizingGrow :: (size_min_max: SizingMinMax = .{}) -> SizingAxis {
return .{type = .GROW, size = .{minMax = size_min_max}};
}
SizingFixed :: (size: float) -> SizingAxis {
return .{type = .FIXED, size = .{minMax = .{size, size}}};
}
SizingPercent :: (size_percent: float) -> SizingAxis {
return .{type = .PERCENT, size = .{percent = size_percent}};
}
GetElementId :: (str: string) -> ElementId {
return GetElementId(make_string(str));
}
#scope_module
Math :: #import "Math";
Compiler :: #import "Compiler";
ProgramPrint :: #import "Program_Print";
InternalElementConfigArray :: struct {
configs: [] TypedConfig;
}
#if OS == .WINDOWS {
#load "windows.jai";
} else {
assert(false);
}

View File

@ -0,0 +1,2 @@
#define CLAY_IMPLEMENTATION
#include "clay.h"

File diff suppressed because it is too large Load Diff

Binary file not shown.

View File

@ -0,0 +1,241 @@
RaylibFont :: struct {
font_id: u16;
font: Raylib.Font;
}
g_raylib_fonts: [10]RaylibFont;
to_raylib_color :: (color: Clay.Color) -> Raylib.Color {
return .{cast(u8) color.r, cast(u8) color.g, cast(u8) color.b, cast(u8) color.a};
}
raylib_measure_text :: (text: *Clay.String, config: *Clay.TextElementConfig) -> Clay.Dimensions #c_call {
text_size := Clay.Dimensions.{0, 0};
max_text_width: float = 0;
line_text_width: float = 0;
text_height := cast(float)config.fontSize;
font_to_use := g_raylib_fonts[config.fontId].font;
if text.length > 0 {
for 0..(text.length - 1) {
if text.chars[it] == #char "\n" {
max_text_width = c_max(max_text_width, line_text_width);
line_text_width = 0;
continue;
}
index := cast(s32, text.chars[it]) - 32;
if font_to_use.glyphs[index].advanceX != 0 {
line_text_width += cast(float) font_to_use.glyphs[index].advanceX;
} else {
line_text_width += (font_to_use.recs[index].width + cast(float) font_to_use.glyphs[index].offsetX);
}
}
}
max_text_width = c_max(max_text_width, line_text_width);
text_size.width = max_text_width / 2;
text_size.height = text_height;
return text_size;
}
raylib_initialize :: (width: s32, height: s32, $$title: string, flags: Raylib.ConfigFlags) {
c_string_title: *u8;
#if is_constant(title) {
// Constant strings in Jai are null-terminated
c_string_title = title.data;
} else {
c_string_title = to_c_string(title);
}
Raylib.SetConfigFlags(flags);
Raylib.InitWindow(width, height, c_string_title);
}
clay_raylib_render :: (render_commands: Clay.RenderCommandArray) {
for 0..render_commands.length - 1 {
render_command := Clay.RenderCommandArray_Get(*render_commands, cast(s32) it);
bounding_box := render_command.boundingBox;
if #complete render_command.commandType == {
case .NONE;
case .TEXT;
text := string.{
cast(s64) render_command.text.length,
render_command.text.chars,
};
c_string_text := temp_c_string(text);
font_to_use: Raylib.Font = g_raylib_fonts[render_command.config.textElementConfig.fontId].font;
Raylib.DrawTextEx(
font_to_use,
c_string_text,
.{bounding_box.x, bounding_box.y},
cast(float) render_command.config.textElementConfig.fontSize,
cast(float) render_command.config.textElementConfig.letterSpacing,
to_raylib_color(render_command.config.textElementConfig.textColor),
);
case .IMAGE;
// TODO image handling
image_texture := cast(*Raylib.Texture2D, render_command.config.imageElementConfig.imageData).*;
Raylib.DrawTextureEx(
image_texture,
.{bounding_box.x, bounding_box.y},
0,
bounding_box.width / cast(float) image_texture.width,
Raylib.WHITE
);
case .SCISSOR_START;
Raylib.BeginScissorMode(
cast(s32, round(bounding_box.x)),
cast(s32, round(bounding_box.y)),
cast(s32, round(bounding_box.width)),
cast(s32, round(bounding_box.height)),
);
case .SCISSOR_END;
Raylib.EndScissorMode();
case .RECTANGLE;
config := render_command.config.rectangleElementConfig;
if config.cornerRadius.topLeft > 0 {
radius := (config.cornerRadius.topLeft * 2.0) / min(bounding_box.width, bounding_box.height);
Raylib.DrawRectangleRounded(
.{bounding_box.x, bounding_box.y, bounding_box.width, bounding_box.height},
radius,
8,
to_raylib_color(config.color),
);
} else {
Raylib.DrawRectangle(
cast(s32, bounding_box.x),
cast(s32, bounding_box.y),
cast(s32, bounding_box.width),
cast(s32, bounding_box.height),
to_raylib_color(config.color),
);
}
case .BORDER;
config := render_command.config.borderElementConfig;
// Left border
if config.left.width > 0 {
Raylib.DrawRectangle(
cast(s32, round(bounding_box.x)),
cast(s32, round(bounding_box.y + config.cornerRadius.topLeft)),
cast(s32, config.left.width),
cast(s32, round(bounding_box.height - config.cornerRadius.topLeft - config.cornerRadius.bottomLeft)),
to_raylib_color(config.right.color),
);
}
// Right border
if config.right.width > 0 {
Raylib.DrawRectangle(
cast(s32, round(bounding_box.x + bounding_box.width - cast(float, config.right.width))),
cast(s32, round(bounding_box.y + config.cornerRadius.topRight)),
cast(s32, config.right.width),
cast(s32, round(bounding_box.height - config.cornerRadius.topRight - config.cornerRadius.bottomRight)),
to_raylib_color(config.right.color),
);
}
// Top border
if config.top.width > 0 {
Raylib.DrawRectangle(
cast(s32, round(bounding_box.x + config.cornerRadius.topLeft)),
cast(s32, round(bounding_box.y)),
cast(s32, round(bounding_box.width - config.cornerRadius.topLeft - config.cornerRadius.topRight)),
cast(s32, config.top.width),
to_raylib_color(config.right.color),
);
}
// Bottom border
if config.bottom.width > 0 {
Raylib.DrawRectangle(
cast(s32, round(bounding_box.x + config.cornerRadius.bottomLeft)),
cast(s32, round(bounding_box.y + bounding_box.height - cast(float, config.bottom.width))),
cast(s32, round(bounding_box.width - config.cornerRadius.bottomLeft - config.cornerRadius.bottomRight)),
cast(s32, config.top.width),
to_raylib_color(config.right.color),
);
}
if config.cornerRadius.topLeft > 0 {
Raylib.DrawRing(
.{
round(bounding_box.x + config.cornerRadius.topLeft),
round(bounding_box.y + config.cornerRadius.topLeft),
},
round(config.cornerRadius.topLeft - cast(float, config.top.width)),
config.cornerRadius.topLeft,
180,
270,
10,
to_raylib_color(config.top.color),
);
}
if config.cornerRadius.topRight > 0 {
Raylib.DrawRing(
.{
round(bounding_box.x + bounding_box.width - config.cornerRadius.topRight),
round(bounding_box.y + config.cornerRadius.topRight),
},
round(config.cornerRadius.topRight - cast(float, config.top.width)),
config.cornerRadius.topRight,
270,
360,
10,
to_raylib_color(config.top.color),
);
}
if config.cornerRadius.bottomLeft > 0 {
Raylib.DrawRing(
.{
round(bounding_box.x + config.cornerRadius.bottomLeft),
round(bounding_box.y + bounding_box.height - config.cornerRadius.bottomLeft),
},
round(config.cornerRadius.bottomLeft - cast(float, config.bottom.width)),
config.cornerRadius.bottomLeft,
90,
180,
10,
to_raylib_color(config.bottom.color),
);
}
if config.cornerRadius.bottomRight > 0 {
Raylib.DrawRing(
.{
round(bounding_box.x + bounding_box.width - config.cornerRadius.bottomRight),
round(bounding_box.y + bounding_box.height - config.cornerRadius.bottomRight),
},
round(config.cornerRadius.bottomRight - cast(float, config.bottom.width)),
config.cornerRadius.bottomRight,
0.1,
90,
10,
to_raylib_color(config.bottom.color),
);
}
case .CUSTOM;
}
}
}
#scope_file
round :: (x: float) -> float {
rounded_int := cast(int, x + 0.5 * ifx x < 0 then -1 else 1);
return cast(float, rounded_int);
}
c_max :: (a: $T, b: T) -> T #c_call {
if b < a return a;
return b;
}

View File

@ -0,0 +1,292 @@
using Basic :: #import "Basic";
Clay :: #import,file "../../clay-jai/module.jai";
Raylib :: #import "raylib-jai";
for_expansion :: Clay.for_expansion;;
#load "clay_renderer_raylib.jai";
FONT_ID_BODY_16 :: 0;
COLOR_WHITE :: Clay.Color.{255, 255, 255, 255};
window_width: s32 = 1024;
window_height: s32 = 768;
Document :: struct {
title: string;
contents: string;
}
documents :: Document.[
.{"Squirrels", "The Secret Life of Squirrels: Nature's Clever Acrobats\nSquirrels are often overlooked creatures, dismissed as mere park inhabitants or backyard nuisances. Yet, beneath their fluffy tails and twitching noses lies an intricate world of cunning, agility, and survival tactics that are nothing short of fascinating. As one of the most common mammals in North America, squirrels have adapted to a wide range of environments from bustling urban centers to tranquil forests and have developed a variety of unique behaviors that continue to intrigue scientists and nature enthusiasts alike.\n\nMaster Tree Climbers\nAt the heart of a squirrel's skill set is its impressive ability to navigate trees with ease. Whether they're darting from branch to branch or leaping across wide gaps, squirrels possess an innate talent for acrobatics. Their powerful hind legs, which are longer than their front legs, give them remarkable jumping power. With a tail that acts as a counterbalance, squirrels can leap distances of up to ten times the length of their body, making them some of the best aerial acrobats in the animal kingdom.\nBut it's not just their agility that makes them exceptional climbers. Squirrels' sharp, curved claws allow them to grip tree bark with precision, while the soft pads on their feet provide traction on slippery surfaces. Their ability to run at high speeds and scale vertical trunks with ease is a testament to the evolutionary adaptations that have made them so successful in their arboreal habitats.\n\nFood Hoarders Extraordinaire\nSquirrels are often seen frantically gathering nuts, seeds, and even fungi in preparation for winter. While this behavior may seem like instinctual hoarding, it is actually a survival strategy that has been honed over millions of years. Known as \"scatter hoarding,\" squirrels store their food in a variety of hidden locations, often burying it deep in the soil or stashing it in hollowed-out tree trunks.\nInterestingly, squirrels have an incredible memory for the locations of their caches. Research has shown that they can remember thousands of hiding spots, often returning to them months later when food is scarce. However, they don't always recover every stash some forgotten caches eventually sprout into new trees, contributing to forest regeneration. This unintentional role as forest gardeners highlights the ecological importance of squirrels in their ecosystems.\n\nThe Great Squirrel Debate: Urban vs. Wild\nWhile squirrels are most commonly associated with rural or wooded areas, their adaptability has allowed them to thrive in urban environments as well. In cities, squirrels have become adept at finding food sources in places like parks, streets, and even garbage cans. However, their urban counterparts face unique challenges, including traffic, predators, and the lack of natural shelters. Despite these obstacles, squirrels in urban areas are often observed using human infrastructure such as buildings, bridges, and power lines as highways for their acrobatic escapades.\nThere is, however, a growing concern regarding the impact of urban life on squirrel populations. Pollution, deforestation, and the loss of natural habitats are making it more difficult for squirrels to find adequate food and shelter. As a result, conservationists are focusing on creating squirrel-friendly spaces within cities, with the goal of ensuring these resourceful creatures continue to thrive in both rural and urban landscapes.\n\nA Symbol of Resilience\nIn many cultures, squirrels are symbols of resourcefulness, adaptability, and preparation. Their ability to thrive in a variety of environments while navigating challenges with agility and grace serves as a reminder of the resilience inherent in nature. Whether you encounter them in a quiet forest, a city park, or your own backyard, squirrels are creatures that never fail to amaze with their endless energy and ingenuity.\nIn the end, squirrels may be small, but they are mighty in their ability to survive and thrive in a world that is constantly changing. So next time you spot one hopping across a branch or darting across your lawn, take a moment to appreciate the remarkable acrobat at work a true marvel of the natural world."},
.{"Lorem Ipsum", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."},
.{"Vacuum Instructions", "Chapter 3: Getting Started - Unpacking and Setup\n\nCongratulations on your new SuperClean Pro 5000 vacuum cleaner! In this section, we will guide you through the simple steps to get your vacuum up and running. Before you begin, please ensure that you have all the components listed in the \"Package Contents\" section on page 2.\n\n1. Unboxing Your Vacuum\nCarefully remove the vacuum cleaner from the box. Avoid using sharp objects that could damage the product. Once removed, place the unit on a flat, stable surface to proceed with the setup. Inside the box, you should find:\n\n The main vacuum unit\n A telescoping extension wand\n A set of specialized cleaning tools (crevice tool, upholstery brush, etc.)\n A reusable dust bag (if applicable)\n A power cord with a 3-prong plug\n A set of quick-start instructions\n\n2. Assembling Your Vacuum\nBegin by attaching the extension wand to the main body of the vacuum cleaner. Line up the connectors and twist the wand into place until you hear a click. Next, select the desired cleaning tool and firmly attach it to the wand's end, ensuring it is securely locked in.\n\nFor models that require a dust bag, slide the bag into the compartment at the back of the vacuum, making sure it is properly aligned with the internal mechanism. If your vacuum uses a bagless system, ensure the dust container is correctly seated and locked in place before use.\n\n3. Powering On\nTo start the vacuum, plug the power cord into a grounded electrical outlet. Once plugged in, locate the power switch, usually positioned on the side of the handle or body of the unit, depending on your model. Press the switch to the \"On\" position, and you should hear the motor begin to hum. If the vacuum does not power on, check that the power cord is securely plugged in, and ensure there are no blockages in the power switch.\n\nNote: Before first use, ensure that the vacuum filter (if your model has one) is properly installed. If unsure, refer to \"Section 5: Maintenance\" for filter installation instructions."},
.{"Article 4", "Article 4"},
.{"Article 5", "Article 5"},
];
to_jai_string :: (str: Clay.String) -> string {
return .{data = str.chars, count = cast(s64, str.length)};
}
handle_clay_errors :: (error_data: Clay.ErrorData) #c_call {
push_context {
log_error(
"Clay Error [%]: % | %",
error_data.errorType,
to_jai_string(error_data.errorText),
error_data.userData
);
}
}
render_header_button :: (text: string) {
for Clay.Element(
Clay.Layout(.{padding = .{16, 8}}),
Clay.Rectangle(.{
color = .{140, 140, 140, 255},
cornerRadius = .{5, 5, 5, 5},
})
) {
Clay.Text(text, Clay.TextConfig(.{
fontId = FONT_ID_BODY_16,
fontSize = 16,
textColor = COLOR_WHITE,
}));
}
}
render_dropdown_menu_item :: (text: string) {
for Clay.Element(
Clay.Layout(.{padding = .{16, 16}})
) {
Clay.Text(text, Clay.TextConfig(.{
fontId = FONT_ID_BODY_16,
fontSize = 16,
textColor = COLOR_WHITE,
}));
}
}
selected_document_index : int = 0;
main :: () {
flags := Raylib.ConfigFlags.WINDOW_RESIZABLE | .MSAA_4X_HINT | .VSYNC_HINT;
raylib_initialize(1024, 768, "Introducing Clay Demo", flags);
clay_required_memory := Clay.MinMemorySize();
memory := alloc(clay_required_memory);
clay_memory := Clay.CreateArenaWithCapacityAndMemory(clay_required_memory, memory);
Clay.Initialize(
clay_memory,
Clay.Dimensions.{cast(float, Raylib.GetScreenWidth()), cast(float, Raylib.GetScreenHeight())},
.{handle_clay_errors, 0}
);
Clay.SetMeasureTextFunction(raylib_measure_text);
g_raylib_fonts[FONT_ID_BODY_16] = .{
FONT_ID_BODY_16,
Raylib.LoadFontEx("resources/Roboto-Regular.ttf", 48, null, 400),
};
Raylib.SetTextureFilter(g_raylib_fonts[FONT_ID_BODY_16].font.texture, .BILINEAR);
while !Raylib.WindowShouldClose() {
Clay.SetLayoutDimensions(.{
cast(float, Raylib.GetScreenWidth()),
cast(float, Raylib.GetScreenHeight()),
});
mouse_position := Raylib.GetMousePosition();
scroll_delta := Raylib.GetMouseWheelMoveV();
Clay.SetPointerState(mouse_position, Raylib.IsMouseButtonDown(0));
Clay.UpdateScrollContainers(true, scroll_delta, Raylib.GetFrameTime());
layout_expand := Clay.Sizing.{
Clay.SizingGrow(),
Clay.SizingGrow(),
};
content_background_config := Clay.RectangleElementConfig.{
color = .{90, 90, 90, 255},
cornerRadius = .{8, 8, 8, 8},
};
Clay.BeginLayout();
for Clay.Element(
Clay.ID("OuterContainer"),
Clay.Rectangle(.{color = .{43, 41, 51, 255}}),
Clay.Layout(.{
layoutDirection = .TOP_TO_BOTTOM,
sizing = layout_expand,
padding = .{16, 16},
childGap = 16,
}),
) {
for Clay.Element(
Clay.ID("HeaderBar"),
Clay.Rectangle(content_background_config),
Clay.Layout(.{
sizing = .{
height = Clay.SizingFixed(60),
width = Clay.SizingGrow(),
},
padding = .{16, 16},
childGap = 16,
childAlignment = .{
y = .CENTER,
}
}),
) {
for Clay.Element(
Clay.ID("FileButton"),
Clay.Layout(.{padding = .{16, 8}}),
Clay.Rectangle(.{
color = .{140, 140, 140, 255},
cornerRadius = .{5, 5, 5, 5},
}),
) {
Clay.Text("File", Clay.TextConfig(.{
fontId = FONT_ID_BODY_16,
fontSize = 16,
textColor = COLOR_WHITE,
}));
file_menu_visible := Clay.PointerOver(Clay.GetElementId("FileButton")) ||
Clay.PointerOver(Clay.GetElementId("FileMenu"));
if file_menu_visible {
for Clay.Element(
Clay.ID("FileMenu"),
Clay.Floating(.{attachment = .{parent = .LEFT_BOTTOM}}),
Clay.Layout(.{padding = .{0, 8}})
) {
for Clay.Element(
Clay.Layout(.{
layoutDirection=.TOP_TO_BOTTOM,
sizing = .{width = Clay.SizingFixed(200)}
}),
Clay.Rectangle(.{
color = .{40, 40, 40, 255},
cornerRadius = .{8, 8, 8, 8}
})
) {
// Render dropdown items here
render_dropdown_menu_item("New");
render_dropdown_menu_item("Open");
render_dropdown_menu_item("Close");
}
}
}
}
// Render header buttons
render_header_button("Edit");
for Clay.Element(Clay.Layout(.{
sizing = .{Clay.SizingGrow(), Clay.SizingGrow()}})) {}
render_header_button("Upload");
render_header_button("Media");
render_header_button("Support");
}
for Clay.Element(
Clay.ID("LowerContent"),
Clay.Layout(.{sizing = layout_expand, childGap = 16}),
) {
for Clay.Element(
Clay.ID("Sidebar"),
Clay.Rectangle(content_background_config),
Clay.Layout(.{
layoutDirection = .TOP_TO_BOTTOM,
padding = .{16, 16},
childGap = 8,
sizing = .{
width = Clay.SizingFixed(250),
height = Clay.SizingGrow(),
}
})
) {
for document : documents {
sidebar_button_layout := Clay.LayoutConfig.{
sizing = .{width = Clay.SizingGrow()},
padding = .{16, 16},
};
if it_index == selected_document_index {
for Clay.Element(
Clay.Layout(sidebar_button_layout),
Clay.Rectangle(.{
color = .{120, 120, 120, 255},
cornerRadius = .{8, 8, 8, 8},
})
) {
Clay.Text(document.title, Clay.TextConfig(.{
fontId = FONT_ID_BODY_16,
fontSize = 20,
textColor = COLOR_WHITE,
}));
}
} else {
id := tprint("Parnets %", it_index);
is_hovered := Clay.PointerOver(Clay.GetElementId(id));
if is_hovered && Raylib.IsMouseButtonPressed(0) {
selected_document_index = it_index;
}
for Clay.Element(
Clay.ID(id)
) {
for Clay.Element(
Clay.Layout(sidebar_button_layout),
ifx is_hovered then Clay.Rectangle(.{
color = .{120, 120, 120, 120},
cornerRadius = .{8, 8, 8, 8},
}) else .{}
) {
Clay.Text(document.title, Clay.TextConfig(.{
fontId = FONT_ID_BODY_16,
fontSize = 20,
textColor = COLOR_WHITE
}));
}
}
}
}
}
for Clay.Element(
Clay.ID("MainContent"),
Clay.Rectangle(content_background_config),
Clay.Scroll(.{vertical = true}),
Clay.Layout(.{
layoutDirection = .TOP_TO_BOTTOM,
childGap = 16,
padding = .{16, 16},
sizing = layout_expand,
}),
) {
selected_document := documents[selected_document_index];
Clay.Text(selected_document.title, Clay.TextConfig(.{
fontId = FONT_ID_BODY_16,
fontSize = 24,
textColor = COLOR_WHITE,
}));
Clay.Text(selected_document.contents, Clay.TextConfig(.{
fontId = FONT_ID_BODY_16,
fontSize = 24,
textColor = COLOR_WHITE
}));
}
}
}
render_commands := Clay.EndLayout();
Raylib.BeginDrawing();
Raylib.ClearBackground(Raylib.BLACK);
clay_raylib_render(render_commands);
Raylib.EndDrawing();
reset_temporary_storage();
}
}

View File

@ -0,0 +1,133 @@
Vector2 :: Math.Vector2;
Vector3 :: Math.Vector3;
Vector4 :: Math.Vector4;
Quaternion :: Math.Quaternion;
Matrix :: Math.Matrix4;
PI :: Math.PI;
LIGHTGRAY :: Color.{ 200, 200, 200, 255 };
GRAY :: Color.{ 130, 130, 130, 255 };
DARKGRAY :: Color.{ 80, 80, 80, 255 };
YELLOW :: Color.{ 253, 249, 0, 255 };
GOLD :: Color.{ 255, 203, 0, 255 };
ORANGE :: Color.{ 255, 161, 0, 255 };
PINK :: Color.{ 255, 109, 194, 255 };
RED :: Color.{ 230, 41, 55, 255 };
MAROON :: Color.{ 190, 33, 55, 255 };
GREEN :: Color.{ 0, 228, 48, 255 };
LIME :: Color.{ 0, 158, 47, 255 };
DARKGREEN :: Color.{ 0, 117, 44, 255 };
SKYBLUE :: Color.{ 102, 191, 255, 255 };
BLUE :: Color.{ 0, 121, 241, 255 };
DARKBLUE :: Color.{ 0, 82, 172, 255 };
PURPLE :: Color.{ 200, 122, 255, 255 };
VIOLET :: Color.{ 135, 60, 190, 255 };
DARKPURPLE :: Color.{ 112, 31, 126, 255 };
BEIGE :: Color.{ 211, 176, 131, 255 };
BROWN :: Color.{ 127, 106, 79, 255 };
DARKBROWN :: Color.{ 76, 63, 47, 255 };
WHITE :: Color.{ 255, 255, 255, 255 };
BLACK :: Color.{ 0, 0, 0, 255 };
BLANK :: Color.{ 0, 0, 0, 0 };
MAGENTA :: Color.{ 255, 0, 255, 255 };
RAYWHITE :: Color.{ 245, 245, 245, 255 };
GetGamepadButtonPressed :: () -> GamepadButton #foreign raylib;
IsMouseButtonPressed :: (button: MouseButton) -> bool { return IsMouseButtonPressed(cast(s32) button); }
IsMouseButtonDown :: (button: MouseButton) -> bool { return IsMouseButtonDown(cast(s32) button); }
IsMouseButtonReleased :: (button: MouseButton) -> bool { return IsMouseButtonReleased(cast(s32) button); }
IsMouseButtonUp :: (button: MouseButton) -> bool { return IsMouseButtonUp(cast(s32) button); }
IsKeyPressed :: (key: KeyboardKey) -> bool { return IsKeyPressed(cast(s32) key); }
IsKeyPressedRepeat :: (key: KeyboardKey) -> bool { return IsKeyPressedRepeat(cast(s32) key); }
IsKeyDown :: (key: KeyboardKey) -> bool { return IsKeyDown(cast(s32) key); }
IsKeyReleased :: (key: KeyboardKey) -> bool { return IsKeyReleased(cast(s32) key); }
IsKeyUp :: (key: KeyboardKey) -> bool { return IsKeyUp(cast(s32) key); }
SetExitKey :: (key: KeyboardKey) -> void { return SetExitKey(cast(s32) key); }
SetConfigFlags :: (flags: ConfigFlags) -> void { return SetConfigFlags(cast(u32) flags); }
SetGesturesEnabled :: (flags: Gesture) -> void { return SetGesturesEnabled(cast(u32) flags); }
IsGestureDetected :: (gesture: Gesture) -> bool { return IsGestureDetected(cast(u32) gesture); }
IsWindowState :: (flag: ConfigFlags) -> bool { return IsWindowState(cast(u32) flag); }
SetWindowState :: (flags: ConfigFlags) -> void { return SetWindowState(cast(u32) flags); }
ClearWindowState :: (flags: ConfigFlags) -> void { return ClearWindowState(cast(u32) flags); }
UpdateCamera :: (camera: *Camera, mode: CameraMode) -> void { return UpdateCamera(camera, cast(s32) mode); }
SetTraceLogLevel :: (logLevel: TraceLogLevel) -> void { return SetTraceLogLevel(cast(s32) logLevel); }
TraceLog :: (logLevel: TraceLogLevel, text: string, __args: ..Any) { TraceLog(cast(s32) logLevel, text, __args); }
SetShaderValue :: (shader: Shader, locIndex: s32, value: *void, uniformType: ShaderUniformDataType) -> void {
return SetShaderValue(shader, locIndex, value, cast(s32) uniformType);
}
SetShaderValueV :: (shader: Shader, locIndex: s32, value: *void, uniformType: ShaderUniformDataType, count: s32) -> void {
return SetShaderValue(shader, locIndex, value, cast(s32) uniformType, count);
}
IsGamepadButtonPressed :: (gamepad: s32, button: GamepadButton) -> bool { return IsGamepadButtonPressed(gamepad, cast(s32) button); }
IsGamepadButtonDown :: (gamepad: s32, button: GamepadButton) -> bool { return IsGamepadButtonDown(gamepad, cast(s32) button); }
IsGamepadButtonReleased :: (gamepad: s32, button: GamepadButton) -> bool { return IsGamepadButtonReleased(gamepad, cast(s32) button); }
IsGamepadButtonUp :: (gamepad: s32, button: GamepadButton) -> bool { return IsGamepadButtonUp(gamepad, cast(s32) button); }
GetGamepadAxisMovement :: (gamepad: s32, axis: GamepadAxis) -> float { return GetGamepadAxisMovement(gamepad, cast(s32) axis); }
SetTextureFilter :: (texture: Texture2D, filter: TextureFilter) -> void { return SetTextureFilter(texture, cast(s32) filter); }
SetTextureWrap :: (texture: Texture2D, wrap: TextureWrap) -> void { return SetTextureWrap(textuer, cast(s32) wrap); }
BeginBlendMode :: (mode: BlendMode) -> void { return BeginBlendMode(cast(s32) mode); }
ImageFormat :: (image: *Image, newFormat: PixelFormat) -> void { return ImageFormat(image, cast(s32) newFormat); }
LoadImageRaw :: (fileName: *u8, width: s32, height: s32, format: PixelFormat, headerSize: s32) -> Image {
return LoadImageRaw(fileName, width, height, cast(s32) format, headerSize);
}
LoadFontData :: (fileData: *u8, dataSize: s32, fontSize: s32, codepoints: *s32, codepointCount: s32, type: FontType) -> *GlyphInfo {
return LoadFontData(fileData, dataSize, fontSize, codepoints, codepointCount, cast(s32) type);
}
SetMouseCursor :: (cursor: MouseCursor) -> void { return SetMouseCursor(cast(s32) cursor); }
LoadTexture :: (data: *void, width: s32, height: s32, format: PixelFormat, mipmapCount: s32) -> u32 {
return LoadTexture(data, width, height, cast(s32) format, mipmapCount);
}
FramebufferAttach :: (fboId: u32, texId: u32, attachType: FramebufferAttachType, texType: FramebufferAttachTextureType, mipLevel: s32) -> void {
return FramebufferAttach(fbiId, texId, cast(s32) attachType, cast(s32) texType, mipLevel);
}
SetUniform :: (locIndex: s32, value: *void, uniformType: ShaderUniformDataType, count: s32) -> void { return SetUniform(locIndex, value, cast(s32) uniformType, count); }
SetMaterialTexture :: (material: *Material, mapType: MaterialMapIndex, texture: Texture2D) -> void { return SetMaterialTexture(material, mapType, texture); }
Camera3D :: struct {
position: Vector3; // Camera position
target: Vector3; // Camera target it looks-at
up: Vector3; // Camera up vector (rotation over its axis)
fovy: float; // Camera field-of-view aperture in Y (degrees) in perspective, used as near plane width in orthographic
projection: CameraProjection; // Camera projection: CAMERA_PERSPECTIVE or CAMERA_ORTHOGRAPHIC
}
TraceLogCallback :: #type (logLevel: TraceLogLevel, text: *u8, args: .. Any) #c_call;
#scope_module
#if OS == .WINDOWS {
user32 :: #system_library,link_always "user32";
gdi32 :: #system_library,link_always "gdi32";
shell32 :: #system_library,link_always "shell32";
winmm :: #system_library,link_always "winmm";
raylib :: #library,no_dll "windows/raylib";
#load "windows.jai";
} else {
assert(false);
}
#import "Basic";
Math :: #import "Math";

File diff suppressed because it is too large Load Diff