diff --git a/.clang-format b/.clang-format index b0e33c64..ecd945af 100644 --- a/.clang-format +++ b/.clang-format @@ -1,8 +1,23 @@ Language: Cpp AccessModifierOffset: -2 AlignAfterOpenBracket: Align -AlignConsecutiveAssignments: true -AlignConsecutiveDeclarations: true +AlignArrayOfStructures: Left +AlignConsecutiveAssignments: + Enabled: true + AcrossEmptyLines: false + AcrossComments: true +AlignConsecutiveDeclarations: + Enabled: true + AcrossEmptyLines: false + AcrossComments: true +AlignConsecutiveBitFields: + Enabled: true + AcrossEmptyLines: false + AcrossComments: true +AlignConsecutiveMacros: + Enabled: true + AcrossEmptyLines: false + AcrossComments: true AlignEscapedNewlines: Left AlignOperands: true AlignTrailingComments: true @@ -60,40 +75,67 @@ IndentCaseLabels: true IndentPPDirectives: AfterHash IndentWidth: 2 IndentWrappedFunctionNames: true -JavaScriptQuotes: Leave -JavaScriptWrapImports: true -KeepEmptyLinesAtTheStartOfBlocks: false +InsertNewlineAtEOF: true +IntegerLiteralSeparator: + Binary: 8 + Decimal: 3 + Hex: 4 +KeepEmptyLines: + AtEndOfFile: false + AtStartOfBlock: false + AtStartOfFile: false +LineEnding: LF MacroBlockBegin: "" MacroBlockEnd: "" MaxEmptyLinesToKeep: 1 NamespaceIndentation: None -ObjCBinPackProtocolList: Auto -ObjCBlockIndentWidth: 2 -ObjCSpaceAfterProperty: false -ObjCSpaceBeforeProtocolList: true +PackConstructorInitializers: CurrentLine PenaltyBreakAssignment: 2 PenaltyBreakBeforeFirstCallParameter: 19 -PenaltyBreakComment: 300 +PenaltyBreakComment: 30000 PenaltyBreakFirstLessLess: 120 PenaltyBreakString: 1000 PenaltyExcessCharacter: 1000000 PenaltyReturnTypeOnItsOwnLine: 60 -PointerAlignment: Right -ReflowComments: true +PointerAlignment: Middle +QualifierAlignment: Right +ReferenceAlignment : Middle +ReflowComments: false +RemoveParentheses: MultipleParentheses +RemoveSemicolon : true +RequiresClausePosition: WithPreceding +SeparateDefinitionBlocks: Always SortIncludes: true SortUsingDeclarations: true SpaceAfterCStyleCast: true SpaceAfterTemplateKeyword: true SpaceBeforeAssignmentOperators: true +SpaceBeforeCpp11BracedList: false SpaceBeforeCtorInitializerColon: true SpaceBeforeInheritanceColon: true -SpaceBeforeParens: ControlStatements +SpaceBeforeParens: Custom +SpaceBeforeParensOptions: + AfterControlStatements: true + AfterFunctionDefinitionName: false + AfterOverloadedOperator: false + AfterPlacementOperator : true + AfterRequiresInClause: true + AfterRequiresInExpression: true + BeforeNonEmptyParentheses: false SpaceBeforeRangeBasedForLoopColon: true -SpaceInEmptyParentheses: false +SpaceBeforeSquareBrackets: false SpacesBeforeTrailingComments: 8 -SpacesInAngles: false +SpacesInAngles: Never SpacesInContainerLiterals: false -SpacesInCStyleCastParentheses: false -SpacesInParentheses: false +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParens: Custom +SpacesInParensOptions: + ExceptDoubleParentheses: true + InConditionalStatements: false + InCStyleCasts: false + InEmptyParentheses: false SpacesInSquareBrackets: false -TabWidth: 4 +Standard: c++20 +TabWidth: 4 \ No newline at end of file diff --git a/.clang-tidy b/.clang-tidy index 2b6cc232..23b1fbce 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,4 +1,16 @@ -Checks: "clang-diagnostic-*,clang-analyzer-*,google-*,-google-readability-casting,readability-*,bugprone-*,-bugprone-easily-swappable-parameters,cert-*,llvm-*,-llvm-header-guard,performance-*" +Checks: > + clang-diagnostic-* + clang-analyzer-* + google-* + -google-readability-casting + readability-* + -readability-identifier-length + bugprone-* + -bugprone-easily-swappable-parameters + cert-* + llvm-* + -llvm-header-guard + performance-*" WarningsAsErrors: "" HeaderFilterRegex: "" FormatStyle: file diff --git a/ashura/engine/assets.h b/ashura/engine/assets.h index 5e5d8200..8bcc8576 100644 --- a/ashura/engine/assets.h +++ b/ashura/engine/assets.h @@ -1,4 +1,3 @@ - /// SPDX-License-Identifier: MIT #pragma once #include "ashura/engine/font.h" @@ -18,7 +17,8 @@ typedef StrVecMap> FontMap; struct AssetMap { explicit AssetMap(AllocatorImpl allocator) : - shaders{allocator}, fonts{allocator} + shaders{allocator}, + fonts{allocator} { } diff --git a/ashura/engine/canvas.cc b/ashura/engine/canvas.cc index ac21ee58..b9602cc2 100644 --- a/ashura/engine/canvas.cc +++ b/ashura/engine/canvas.cc @@ -6,12 +6,18 @@ namespace ash { -void path::rect(Vec &vtx) +void path::rect(Vec & vtx) { - vtx.extend_copy(span({{-1, -1}, {1, -1}, {1, 1}, {-1, 1}})).unwrap(); + vtx.extend_copy(span({ + {-1, -1}, + {1, -1}, + {1, 1 }, + {-1, 1 } + })) + .unwrap(); } -void path::arc(Vec &vtx, f32 start, f32 stop, u32 segments) +void path::arc(Vec & vtx, f32 start, f32 stop, u32 segments) { if (segments < 2) { @@ -30,7 +36,7 @@ void path::arc(Vec &vtx, f32 start, f32 stop, u32 segments) } } -void path::circle(Vec &vtx, u32 segments) +void path::circle(Vec & vtx, u32 segments) { if (segments < 4) { @@ -49,7 +55,7 @@ void path::circle(Vec &vtx, u32 segments) } } -void path::squircle(Vec &vtx, f32 elasticity, u32 segments) +void path::squircle(Vec & vtx, f32 elasticity, u32 segments) { if (segments < 128) { @@ -68,7 +74,7 @@ void path::squircle(Vec &vtx, f32 elasticity, u32 segments) segments >> 2); } -void path::rrect(Vec &vtx, Vec4 radii, u32 segments) +void path::rrect(Vec & vtx, Vec4 radii, u32 segments) { if (segments < 8) { @@ -135,7 +141,7 @@ void path::rrect(Vec &vtx, Vec4 radii, u32 segments) vtx[first + i++] = Vec2{1, -1 + radii.y}; } -void path::brect(Vec &vtx, Vec4 slant) +void path::brect(Vec & vtx, Vec4 slant) { slant = slant * 2.0F; slant.x = min(slant.x, 2.0F); @@ -149,15 +155,21 @@ void path::brect(Vec &vtx, Vec4 slant) f32 max_radius_w = min(max_radius_z, 2.0F - slant.z); slant.w = min(slant.w, max_radius_w); - Vec2 const vertices[] = {{-1 + slant.x, -1}, {1 - slant.y, -1}, - {1, -1 + slant.y}, {1, 1 - slant.z}, - {1 - slant.z, 1}, {-1 + slant.w, 1}, - {-1, 1 - slant.w}, {-1, -1 + slant.x}}; + Vec2 const vertices[] = { + {-1 + slant.x, -1 }, + {1 - slant.y, -1 }, + {1, -1 + slant.y}, + {1, 1 - slant.z }, + {1 - slant.z, 1 }, + {-1 + slant.w, 1 }, + {-1, 1 - slant.w }, + {-1, -1 + slant.x} + }; vtx.extend_copy(vertices).unwrap(); } -void path::bezier(Vec &vtx, Vec2 cp0, Vec2 cp1, Vec2 cp2, u32 segments) +void path::bezier(Vec & vtx, Vec2 cp0, Vec2 cp1, Vec2 cp2, u32 segments) { if (segments < 3) { @@ -177,7 +189,7 @@ void path::bezier(Vec &vtx, Vec2 cp0, Vec2 cp1, Vec2 cp2, u32 segments) } } -void path::cubic_bezier(Vec &vtx, Vec2 cp0, Vec2 cp1, Vec2 cp2, Vec2 cp3, +void path::cubic_bezier(Vec & vtx, Vec2 cp0, Vec2 cp1, Vec2 cp2, Vec2 cp3, u32 segments) { if (segments < 4) @@ -199,7 +211,7 @@ void path::cubic_bezier(Vec &vtx, Vec2 cp0, Vec2 cp1, Vec2 cp2, Vec2 cp3, } } -void path::catmull_rom(Vec &vtx, Vec2 cp0, Vec2 cp1, Vec2 cp2, Vec2 cp3, +void path::catmull_rom(Vec & vtx, Vec2 cp0, Vec2 cp1, Vec2 cp2, Vec2 cp3, u32 segments) { if (segments < 4) @@ -221,8 +233,8 @@ void path::catmull_rom(Vec &vtx, Vec2 cp0, Vec2 cp1, Vec2 cp2, Vec2 cp3, } } -void path::triangulate_stroke(Span points, Vec &vertices, - Vec &indices, f32 thickness) +void path::triangulate_stroke(Span points, Vec & vertices, + Vec & indices, f32 thickness) { if (points.size() < 2) { @@ -237,9 +249,9 @@ void path::triangulate_stroke(Span points, Vec &vertices, vertices.extend_uninit(num_vertices).unwrap(); indices.extend_uninit(num_indices).unwrap(); - Vec2 *vtx = vertices.data() + first_vtx; - u32 *idx = indices.data() + first_idx; - u32 ivtx = 0; + Vec2 * vtx = vertices.data() + first_vtx; + u32 * idx = indices.data() + first_idx; + u32 ivtx = 0; for (u32 i = 0; i < num_points - 1; i++) { @@ -283,14 +295,14 @@ void path::triangulate_stroke(Span points, Vec &vertices, } } -void path::triangles(u32 first_vertex, u32 num_vertices, Vec &indices) +void path::triangles(u32 first_vertex, u32 num_vertices, Vec & indices) { CHECK(num_vertices > 3); u32 const num_triangles = num_vertices / 3; u32 const first_idx = indices.size32(); indices.extend_uninit(num_triangles * 3).unwrap(); - u32 *idx = indices.data() + first_idx; + u32 * idx = indices.data() + first_idx; for (u32 i = 0; i < num_triangles * 3; i += 3) { idx[i] = first_vertex + i; @@ -299,7 +311,8 @@ void path::triangles(u32 first_vertex, u32 num_vertices, Vec &indices) } } -void path::triangulate_convex(Vec &idx, u32 first_vertex, u32 num_vertices) +void path::triangulate_convex(Vec & idx, u32 first_vertex, + u32 num_vertices) { if (num_vertices < 3) { @@ -319,7 +332,7 @@ void path::triangulate_convex(Vec &idx, u32 first_vertex, u32 num_vertices) } } -Canvas &Canvas::reset() +Canvas & Canvas::reset() { frame_arena.reclaim(); passes.clear(); @@ -334,8 +347,8 @@ Canvas &Canvas::reset() return *this; } -Canvas &Canvas::begin_recording(Vec2 new_viewport_extent, - Vec2U new_surface_extent) +Canvas & Canvas::begin_recording(Vec2 new_viewport_extent, + Vec2U new_surface_extent) { reset(); @@ -357,8 +370,8 @@ Canvas &Canvas::begin_recording(Vec2 new_viewport_extent, return *this; } -constexpr RectU clip_to_scissor(gpu::Viewport const &viewport, - CRect const &clip) +constexpr RectU clip_to_scissor(gpu::Viewport const & viewport, + CRect const & clip) { // clips only apply translations. no scaling Rect s{viewport.offset + clip.begin(), clip.extent}; @@ -373,11 +386,13 @@ constexpr RectU clip_to_scissor(gpu::Viewport const &viewport, s.extent.y = clamp(s.offset.y + s.extent.y, 0.0F, viewport.extent.y) - s.offset.y; - return RectU{.offset{(u32) s.offset.x, (u32) s.offset.y}, - .extent{(u32) s.extent.x, (u32) s.extent.y}}; + return RectU{ + .offset{(u32) s.offset.x, (u32) s.offset.y}, + .extent{(u32) s.extent.x, (u32) s.extent.y} + }; } -static inline void flush_batch(Canvas &c) +static inline void flush_batch(Canvas & c) { Canvas::Batch batch = c.batch; c.batch = Canvas::Batch{.type = Canvas::BatchType::None}; @@ -386,7 +401,7 @@ static inline void flush_batch(Canvas &c) { case Canvas::BatchType::RRect: c.add_pass("RRect"_str, [batch, world_to_view = c.world_to_view]( - Canvas::RenderContext const &ctx) { + Canvas::RenderContext const & ctx) { RRectPassParams params{.rendering_info = ctx.rt.info, .scissor = clip_to_scissor(ctx.rt.viewport, batch.clip), @@ -403,7 +418,7 @@ static inline void flush_batch(Canvas &c) case Canvas::BatchType::Ngon: c.add_pass("Ngon"_str, [batch, world_to_view = c.world_to_view]( - Canvas::RenderContext const &ctx) { + Canvas::RenderContext const & ctx) { NgonPassParams params{ .rendering_info = ctx.rt.info, .scissor = clip_to_scissor(ctx.rt.viewport, batch.clip), @@ -424,8 +439,8 @@ static inline void flush_batch(Canvas &c) } } -static inline void add_rrect(Canvas &c, RRectParam const ¶m, - CRect const &clip) +static inline void add_rrect(Canvas & c, RRectParam const & param, + CRect const & clip) { u32 const index = c.rrect_params.size32(); c.rrect_params.push(param).unwrap(); @@ -434,17 +449,19 @@ static inline void add_rrect(Canvas &c, RRectParam const ¶m, [[unlikely]] { flush_batch(c); - c.batch = Canvas::Batch{.type = Canvas::BatchType::RRect, - .clip = clip, - .objects{.offset = index, .span = 1}}; + c.batch = Canvas::Batch{ + .type = Canvas::BatchType::RRect, + .clip = clip, + .objects{.offset = index, .span = 1} + }; return; } c.batch.objects.span++; } -static inline void add_ngon(Canvas &c, NgonParam const ¶m, - CRect const &clip, u32 num_indices) +static inline void add_ngon(Canvas & c, NgonParam const & param, + CRect const & clip, u32 num_indices) { u32 const index = c.ngon_params.size32(); c.ngon_index_counts.push(num_indices).unwrap(); @@ -454,95 +471,103 @@ static inline void add_ngon(Canvas &c, NgonParam const ¶m, [[unlikely]] { flush_batch(c); - c.batch = Canvas::Batch{.type = Canvas::BatchType::Ngon, - .clip = clip, - .objects{.offset = index, .span = 1}}; + c.batch = Canvas::Batch{ + .type = Canvas::BatchType::Ngon, + .clip = clip, + .objects{.offset = index, .span = 1} + }; return; } c.batch.objects.span++; } -Canvas &Canvas::end_recording() +Canvas & Canvas::end_recording() { flush_batch(*this); return *this; } -Canvas &Canvas::clip(CRect const &c) +Canvas & Canvas::clip(CRect const & c) { current_clip = c; return *this; } -constexpr Mat4 object_to_world(Mat4 const &transform, Vec2 center, Vec2 extent) +constexpr Mat4 object_to_world(Mat4 const & transform, Vec2 center, Vec2 extent) { return transform * translate3d(vec3(center, 0)) * scale3d(vec3(extent * 0.5F, 1)); } -Canvas &Canvas::circle(ShapeInfo const &info) -{ - add_rrect(*this, - RRectParam{.transform = object_to_world(info.transform, info.center, - info.extent), - .tint = {info.tint[0], info.tint[1], info.tint[2], - info.tint[3]}, - .radii = {1, 1, 1, 1}, - .uv = {info.uv[0], info.uv[1]}, - .tiling = info.tiling, - .aspect_ratio = info.extent.x / info.extent.y, - .stroke = info.stroke, - .thickness = info.thickness / info.extent.y, - .edge_smoothness = info.edge_smoothness, - .sampler = info.sampler, - .albedo = info.texture}, - current_clip); +Canvas & Canvas::circle(ShapeInfo const & info) +{ + add_rrect( + *this, + RRectParam{ + .transform = + object_to_world(info.transform, info.center, info.extent), + .tint = {info.tint[0], info.tint[1], info.tint[2], info.tint[3]}, + .radii = {1, 1, 1, 1}, + .uv = {info.uv[0], info.uv[1]}, + .tiling = info.tiling, + .aspect_ratio = info.extent.x / info.extent.y, + .stroke = info.stroke, + .thickness = info.thickness / info.extent.y, + .edge_smoothness = info.edge_smoothness, + .sampler = info.sampler, + .albedo = info.texture + }, + current_clip); return *this; } -Canvas &Canvas::rect(ShapeInfo const &info) -{ - add_rrect(*this, - RRectParam{.transform = object_to_world(info.transform, info.center, - info.extent), - .tint = {info.tint[0], info.tint[1], info.tint[2], - info.tint[3]}, - .radii = {0, 0, 0, 0}, - .uv = {info.uv[0], info.uv[1]}, - .tiling = info.tiling, - .aspect_ratio = info.extent.x / info.extent.y, - .stroke = info.stroke, - .thickness = info.thickness / info.extent.y, - .edge_smoothness = info.edge_smoothness, - .sampler = info.sampler, - .albedo = info.texture}, - current_clip); +Canvas & Canvas::rect(ShapeInfo const & info) +{ + add_rrect( + *this, + RRectParam{ + .transform = + object_to_world(info.transform, info.center, info.extent), + .tint = {info.tint[0], info.tint[1], info.tint[2], info.tint[3]}, + .radii = {0, 0, 0, 0}, + .uv = {info.uv[0], info.uv[1]}, + .tiling = info.tiling, + .aspect_ratio = info.extent.x / info.extent.y, + .stroke = info.stroke, + .thickness = info.thickness / info.extent.y, + .edge_smoothness = info.edge_smoothness, + .sampler = info.sampler, + .albedo = info.texture + }, + current_clip); return *this; } -Canvas &Canvas::rrect(ShapeInfo const &info) -{ - add_rrect(*this, - RRectParam{.transform = object_to_world(info.transform, info.center, - info.extent), - .tint = {info.tint[0], info.tint[1], info.tint[2], - info.tint[3]}, - .radii = info.corner_radii / info.extent.y, - .uv = {info.uv[0], info.uv[1]}, - .tiling = info.tiling, - .aspect_ratio = info.extent.x / info.extent.y, - .stroke = info.stroke, - .thickness = info.thickness / info.extent.y, - .edge_smoothness = info.edge_smoothness, - .sampler = info.sampler, - .albedo = info.texture}, - current_clip); +Canvas & Canvas::rrect(ShapeInfo const & info) +{ + add_rrect( + *this, + RRectParam{ + .transform = + object_to_world(info.transform, info.center, info.extent), + .tint = {info.tint[0], info.tint[1], info.tint[2], info.tint[3]}, + .radii = info.corner_radii / info.extent.y, + .uv = {info.uv[0], info.uv[1]}, + .tiling = info.tiling, + .aspect_ratio = info.extent.x / info.extent.y, + .stroke = info.stroke, + .thickness = info.thickness / info.extent.y, + .edge_smoothness = info.edge_smoothness, + .sampler = info.sampler, + .albedo = info.texture + }, + current_clip); return *this; } -Canvas &Canvas::brect(ShapeInfo const &info) +Canvas & Canvas::brect(ShapeInfo const & info) { u32 const first_vertex = ngon_vertices.size32(); u32 const first_index = ngon_indices.size32(); @@ -565,13 +590,14 @@ Canvas &Canvas::brect(ShapeInfo const &info) .sampler = info.sampler, .albedo = info.texture, .first_index = first_index, - .first_vertex = first_vertex}, + .first_vertex = first_vertex + }, current_clip, num_indices); return *this; } -Canvas &Canvas::squircle(ShapeInfo const &info, f32 elasticity, u32 segments) +Canvas & Canvas::squircle(ShapeInfo const & info, f32 elasticity, u32 segments) { u32 const first_vertex = ngon_vertices.size32(); u32 const first_index = ngon_indices.size32(); @@ -594,15 +620,16 @@ Canvas &Canvas::squircle(ShapeInfo const &info, f32 elasticity, u32 segments) .sampler = info.sampler, .albedo = info.texture, .first_index = first_index, - .first_vertex = first_vertex}, + .first_vertex = first_vertex + }, current_clip, num_indices); return *this; } -Canvas &Canvas::text(ShapeInfo const &info, TextBlock const &block, - TextLayout const &layout, TextBlockStyle const &style, - CRect const &clip) +Canvas & Canvas::text(ShapeInfo const & info, TextBlock const & block, + TextLayout const & layout, TextBlockStyle const & style, + CRect const & clip) { CHECK(style.runs.size() == block.runs.size()); CHECK(style.runs.size() == block.fonts.size()); @@ -620,10 +647,12 @@ Canvas &Canvas::text(ShapeInfo const &info, TextBlock const &block, for (u8 pass = 0; pass < NUM_PASSES; pass++) { f32 line_y = -block_extent.y * 0.5F; - for (Line const &ln : layout.lines) + for (Line const & ln : layout.lines) { - if (!overlaps(clip, CRect{.center = info.center + line_y, - .extent = {block_width, ln.metrics.height}})) + if (!overlaps(clip, CRect{ + .center = info.center + line_y, + .extent = {block_width, ln.metrics.height} + })) { continue; } @@ -631,18 +660,18 @@ Canvas &Canvas::text(ShapeInfo const &info, TextBlock const &block, f32 const baseline = line_y - ln.metrics.descent; TextDirection const direction = level_to_direction(ln.metrics.level); // flip the alignment axis direction if it is an RTL line - f32 const alignment = + f32 const alignment = style.alignment * ((direction == TextDirection::LeftToRight) ? 1 : -1); f32 cursor = space_align(block_width, ln.metrics.width, alignment) - ln.metrics.width * 0.5F; - for (TextRun const &run : + for (TextRun const & run : span(layout.runs).slice(ln.first_run, ln.num_runs)) { - FontStyle const &font_style = block.fonts[run.style]; - TextStyle const &run_style = style.runs[run.style]; - FontInfo const font = font_style.font->info(); - GpuFontAtlas const *atlas = font.gpu_atlas.value(); + FontStyle const & font_style = block.fonts[run.style]; + TextStyle const & run_style = style.runs[run.style]; + FontInfo const font = font_style.font->info(); + GpuFontAtlas const * atlas = font.gpu_atlas.value(); f32 const run_width = au_to_px(run.metrics.advance, run.font_height); if (pass == PASS_BACKGROUND && !run_style.background.is_transparent()) @@ -662,11 +691,11 @@ Canvas &Canvas::text(ShapeInfo const &info, TextBlock const &block, f32 glyph_cursor = cursor; for (u32 g = 0; g < run.num_glyphs; g++) { - GlyphShape const &sh = layout.glyphs[run.first_glyph + g]; - Glyph const &gl = font.glyphs[sh.glyph]; - AtlasGlyph const &agl = atlas->glyphs[sh.glyph]; - Vec2 const extent = au_to_px(gl.metrics.extent, run.font_height); - Vec2 const center = Vec2{glyph_cursor, baseline} + + GlyphShape const & sh = layout.glyphs[run.first_glyph + g]; + Glyph const & gl = font.glyphs[sh.glyph]; + AtlasGlyph const & agl = atlas->glyphs[sh.glyph]; + Vec2 const extent = au_to_px(gl.metrics.extent, run.font_height); + Vec2 const center = Vec2{glyph_cursor, baseline} + au_to_px(gl.metrics.bearing, run.font_height) + au_to_px(sh.offset, run.font_height) + extent * 0.5F; @@ -676,29 +705,33 @@ Canvas &Canvas::text(ShapeInfo const &info, TextBlock const &block, { Vec2 shadow_extent = extent * run_style.shadow_scale; Vec2 shadow_center = center + run_style.shadow_offset; - rect({.center = info.center, - .extent = shadow_extent, - .transform = - info.transform * translate3d(vec3(shadow_center, 0)), - .tint = run_style.shadow, - .sampler = info.sampler, - .texture = atlas->textures[agl.layer], - .uv = {agl.uv[0], agl.uv[1]}, - .tiling = info.tiling, - .edge_smoothness = info.edge_smoothness}); + rect({ + .center = info.center, + .extent = shadow_extent, + .transform = + info.transform * translate3d(vec3(shadow_center, 0)), + .tint = run_style.shadow, + .sampler = info.sampler, + .texture = atlas->textures[agl.layer], + .uv = {agl.uv[0], agl.uv[1]}, + .tiling = info.tiling, + .edge_smoothness = info.edge_smoothness + }); } if (pass == PASS_GLYPHS && !run_style.foreground.is_transparent()) { - rect({.center = info.center, - .extent = extent, - .transform = info.transform * translate3d(vec3(center, 0)), - .tint = run_style.foreground, - .sampler = info.sampler, - .texture = atlas->textures[agl.layer], - .uv = {agl.uv[0], agl.uv[1]}, - .tiling = info.tiling, - .edge_smoothness = info.edge_smoothness}); + rect({ + .center = info.center, + .extent = extent, + .transform = info.transform * translate3d(vec3(center, 0)), + .tint = run_style.foreground, + .sampler = info.sampler, + .texture = atlas->textures[agl.layer], + .uv = {agl.uv[0], agl.uv[1]}, + .tiling = info.tiling, + .edge_smoothness = info.edge_smoothness + }); } glyph_cursor += au_to_px(sh.advance, run.font_height); @@ -743,7 +776,7 @@ Canvas &Canvas::text(ShapeInfo const &info, TextBlock const &block, return *this; } -Canvas &Canvas::triangles(ShapeInfo const &info, Span points) +Canvas & Canvas::triangles(ShapeInfo const & info, Span points) { if (points.size() < 3) { @@ -768,14 +801,15 @@ Canvas &Canvas::triangles(ShapeInfo const &info, Span points) .sampler = info.sampler, .albedo = info.texture, .first_index = first_index, - .first_vertex = first_vertex}, + .first_vertex = first_vertex + }, current_clip, num_indices); return *this; } -Canvas &Canvas::triangles(ShapeInfo const &info, Span points, - Span idx) +Canvas & Canvas::triangles(ShapeInfo const & info, Span points, + Span idx) { if (points.size() < 3) { @@ -788,7 +822,7 @@ Canvas &Canvas::triangles(ShapeInfo const &info, Span points, ngon_vertices.extend_copy(points).unwrap(); ngon_indices.extend_copy(idx).unwrap(); - for (u32 &v : span(ngon_indices).slice(first_index)) + for (u32 & v : span(ngon_indices).slice(first_index)) { v += first_vertex; } @@ -803,13 +837,14 @@ Canvas &Canvas::triangles(ShapeInfo const &info, Span points, .sampler = info.sampler, .albedo = info.texture, .first_index = first_index, - .first_vertex = first_vertex}, + .first_vertex = first_vertex + }, current_clip, idx.size32()); return *this; } -Canvas &Canvas::line(ShapeInfo const &info, Span points) +Canvas & Canvas::line(ShapeInfo const & info, Span points) { if (points.size() < 2) { @@ -833,17 +868,18 @@ Canvas &Canvas::line(ShapeInfo const &info, Span points) .sampler = info.sampler, .albedo = info.texture, .first_index = first_index, - .first_vertex = first_vertex}, + .first_vertex = first_vertex + }, current_clip, num_indices); return *this; } -Canvas &Canvas::blur(CRect const &area, u32 num_passes) +Canvas & Canvas::blur(CRect const & area, u32 num_passes) { flush_batch(*this); - add_pass("Blur"_str, [num_passes, area](Canvas::RenderContext const &ctx) { + add_pass("Blur"_str, [num_passes, area](Canvas::RenderContext const & ctx) { BlurPassParams params{.image_view = ctx.rt.info.color_attachments[0].view, .extent = ctx.rt.extent, .texture_view = ctx.rt.color_descriptor, @@ -856,7 +892,7 @@ Canvas &Canvas::blur(CRect const &area, u32 num_passes) return *this; } -Canvas &Canvas::add_pass(Pass &&pass) +Canvas & Canvas::add_pass(Pass && pass) { flush_batch(*this); passes.push(std::move(pass)).unwrap(); diff --git a/ashura/engine/canvas.h b/ashura/engine/canvas.h index 76e28285..c6d44793 100644 --- a/ashura/engine/canvas.h +++ b/ashura/engine/canvas.h @@ -18,67 +18,67 @@ namespace ash namespace path { -void rect(Vec &vtx); +void rect(Vec & vtx); /// @brief generate vertices for an arc /// @param segments upper bound on the number of segments to divide the arc /// into /// @param start start angle /// @param stop stop angle -void arc(Vec &vtx, f32 start, f32 stop, u32 segments); +void arc(Vec & vtx, f32 start, f32 stop, u32 segments); /// @brief generate vertices for a circle /// @param segments upper bound on the number of segments to divide the circle /// into -void circle(Vec &vtx, u32 segments); +void circle(Vec & vtx, u32 segments); /// @brief generate vertices for a circle /// @param segments upper bound on the number of segments to divide the circle /// into /// @param degree number of degrees of the super-ellipse -void squircle(Vec &vtx, f32 degree, u32 segments); +void squircle(Vec & vtx, f32 degree, u32 segments); /// @brief generate vertices for a circle /// @param segments upper bound on the number of segments to divide the circle /// into /// @param corner_radii border radius of each corner -void rrect(Vec &vtx, Vec4 corner_radii, u32 segments); +void rrect(Vec & vtx, Vec4 corner_radii, u32 segments); /// @brief generate vertices of a bevel rect /// @param vtx /// @param slants each component represents the relative distance from the /// corners of each bevel -void brect(Vec &vtx, Vec4 slants); +void brect(Vec & vtx, Vec4 slants); /// @brief generate vertices for a quadratic bezier curve /// @param segments upper bound on the number of segments to divide the bezier /// curve into /// @param cp[0-2] control points -void bezier(Vec &vtx, Vec2 cp0, Vec2 cp1, Vec2 cp2, u32 segments); +void bezier(Vec & vtx, Vec2 cp0, Vec2 cp1, Vec2 cp2, u32 segments); /// @brief generate vertices for a quadratic bezier curve /// @param segments upper bound on the number of segments to divide the bezier /// curve into /// @param cp[0-3] control points -void cubic_bezier(Vec &vtx, Vec2 cp0, Vec2 cp1, Vec2 cp2, Vec2 cp3, +void cubic_bezier(Vec & vtx, Vec2 cp0, Vec2 cp1, Vec2 cp2, Vec2 cp3, u32 segments); /// @brief generate a catmull rom spline /// @param segments upper bound on the number of segments to divide the bezier /// curve into /// @param cp[0-3] control points -void catmull_rom(Vec &vtx, Vec2 cp0, Vec2 cp1, Vec2 cp2, Vec2 cp3, +void catmull_rom(Vec & vtx, Vec2 cp0, Vec2 cp1, Vec2 cp2, Vec2 cp3, u32 segments); /// @brief triangulate a stroke path, given the vertices for its points -void triangulate_stroke(Span points, Vec &vtx, Vec &idx, - f32 thickness); +void triangulate_stroke(Span points, Vec & vtx, + Vec & idx, f32 thickness); /// @brief generate indices for a triangle list -void triangles(u32 first_vertex, u32 num_vertices, Vec &idx); +void triangles(u32 first_vertex, u32 num_vertices, Vec & idx); /// @brief generate vertices for a quadratic bezier curve -void triangulate_convex(Vec &idx, u32 first_vertex, u32 num_vertices); +void triangulate_convex(Vec & idx, u32 first_vertex, u32 num_vertices); }; // namespace path @@ -122,7 +122,10 @@ struct ShapeInfo u32 texture = 0; - Vec2 uv[2] = {{0, 0}, {1, 1}}; + Vec2 uv[2] = { + {0, 0}, + {1, 1} + }; f32 tiling = 1; @@ -133,15 +136,15 @@ struct Canvas { struct RenderContext { - Canvas &canvas; - GpuContext &gpu; - PassContext &passes; - RenderTarget const &rt; - gpu::CommandEncoder &enc; - SSBO const &rrects; - SSBO const &ngons; - SSBO const &ngon_vertices; - SSBO const &ngon_indices; + Canvas & canvas; + GpuContext & gpu; + PassContext & passes; + RenderTarget const & rt; + gpu::CommandEncoder & enc; + SSBO const & rrects; + SSBO const & ngons; + SSBO const & ngon_vertices; + SSBO const & ngon_indices; }; enum class BatchType : u8 @@ -154,7 +157,10 @@ struct Canvas struct Batch { BatchType type = BatchType::None; - CRect clip{.center{F32_MAX / 2, F32_MAX / 2}, .extent{F32_MAX, F32_MAX}}; + CRect clip{ + .center{F32_MAX / 2, F32_MAX / 2}, + .extent{F32_MAX, F32_MAX } + }; Slice32 objects{}; }; @@ -174,8 +180,10 @@ struct Canvas Mat4 world_to_view = Mat4::identity(); - CRect current_clip{.center{F32_MAX / 2, F32_MAX / 2}, - .extent{F32_MAX, F32_MAX}}; + CRect current_clip{ + .center{F32_MAX / 2, F32_MAX / 2}, + .extent{F32_MAX, F32_MAX } + }; Vec rrect_params; @@ -206,36 +214,36 @@ struct Canvas { } - Canvas(Canvas const &) = delete; - Canvas(Canvas &&) = default; - Canvas &operator=(Canvas const &) = delete; - Canvas &operator=(Canvas &&) = default; - ~Canvas() = default; + Canvas(Canvas const &) = delete; + Canvas(Canvas &&) = default; + Canvas & operator=(Canvas const &) = delete; + Canvas & operator=(Canvas &&) = default; + ~Canvas() = default; - Canvas &begin_recording(Vec2 viewport_extent, Vec2U surface_extent); + Canvas & begin_recording(Vec2 viewport_extent, Vec2U surface_extent); - Canvas &end_recording(); + Canvas & end_recording(); - Canvas &reset(); + Canvas & reset(); - Canvas &clip(CRect const &area); + Canvas & clip(CRect const & area); /// @brief render a circle - Canvas &circle(ShapeInfo const &info); + Canvas & circle(ShapeInfo const & info); /// @brief render a rectangle - Canvas &rect(ShapeInfo const &info); + Canvas & rect(ShapeInfo const & info); /// @brief render a rounded rectangle - Canvas &rrect(ShapeInfo const &info); + Canvas & rrect(ShapeInfo const & info); /// @brief render a beveled rectangle - Canvas &brect(ShapeInfo const &info); + Canvas & brect(ShapeInfo const & info); /// @brief render a squircle (triangulation based) /// @param num_segments an upper bound on the number of segments to /// @param degree - Canvas &squircle(ShapeInfo const &info, f32 degree, u32 segments); + Canvas & squircle(ShapeInfo const & info, f32 degree, u32 segments); /// @brief /// @@ -258,8 +266,8 @@ struct Canvas /// @param info /// @param mode /// @param uvs - Canvas &nine_slice(ShapeInfo const &info, ScaleMode mode, - Span uvs); + Canvas & nine_slice(ShapeInfo const & info, ScaleMode mode, + Span uvs); /// @brief Render text using font atlases /// @param info only info.center, info.transform, info.tiling, and @@ -270,32 +278,34 @@ struct Canvas /// alignment of the block /// @param atlases font atlases /// @param clip clip rect for culling draw commands of the text block - Canvas &text(ShapeInfo const &info, TextBlock const &block, - TextLayout const &layout, TextBlockStyle const &style, - CRect const &clip = {{F32_MAX / 2, F32_MAX / 2}, - {F32_MAX, F32_MAX}}); + Canvas & text(ShapeInfo const & info, TextBlock const & block, + TextLayout const & layout, TextBlockStyle const & style, + CRect const & clip = { + {F32_MAX / 2, F32_MAX / 2}, + {F32_MAX, F32_MAX } + }); /// @brief Render Non-Indexed Triangles - Canvas &triangles(ShapeInfo const &info, Span vertices); + Canvas & triangles(ShapeInfo const & info, Span vertices); /// @brief Render Indexed Triangles - Canvas &triangles(ShapeInfo const &info, Span vertices, - Span indices); + Canvas & triangles(ShapeInfo const & info, Span vertices, + Span indices); /// @brief triangulate and render line - Canvas &line(ShapeInfo const &info, Span vertices); + Canvas & line(ShapeInfo const & info, Span vertices); /// @brief perform a Canvas-space blur /// @param area region in the canvas to apply the blur to /// @param num_passes number of blur passes to execute, higher values result /// in blurrier results - Canvas &blur(CRect const &area, u32 num_passes); + Canvas & blur(CRect const & area, u32 num_passes); /// @brief register a custom canvas pass to be executed in the render thread - Canvas &add_pass(Pass &&pass); + Canvas & add_pass(Pass && pass); template - Canvas &add_pass(Span name, Lambda &&task) + Canvas & add_pass(Span name, Lambda && task) { // relocate lambda to heap Dyn lambda = diff --git a/ashura/engine/color.h b/ashura/engine/color.h index ccbc32b1..c026ff59 100644 --- a/ashura/engine/color.h +++ b/ashura/engine/color.h @@ -1,4 +1,3 @@ - /// SPDX-License-Identifier: MIT #pragma once #include "ashura/std/math.h" @@ -403,7 +402,10 @@ struct ColorGradient } constexpr ColorGradient(Vec4 tl, Vec4 tr, Vec4 bl, Vec4 br) : - tl{tl}, tr{tr}, bl{bl}, br{br} + tl{tl}, + tr{tr}, + bl{bl}, + br{br} { } @@ -432,12 +434,12 @@ struct ColorGradient return y(y0.norm(), y1.norm()); } - constexpr Vec4 const &operator[](usize i) const + constexpr Vec4 const & operator[](usize i) const { return (&tl)[i]; } - constexpr Vec4 &operator[](usize i) + constexpr Vec4 & operator[](usize i) { return (&tl)[i]; } diff --git a/ashura/engine/engine.cc b/ashura/engine/engine.cc index f35d25c4..6257a8ea 100644 --- a/ashura/engine/engine.cc +++ b/ashura/engine/engine.cc @@ -6,7 +6,7 @@ namespace ash { -ASH_C_LINKAGE ASH_DLL_EXPORT Engine *engine = nullptr; +ASH_C_LINKAGE ASH_DLL_EXPORT Engine * engine = nullptr; EngineCfg EngineCfg::parse(AllocatorImpl allocator, Span json) { @@ -112,7 +112,7 @@ EngineCfg EngineCfg::parse(AllocatorImpl allocator, Span json) return out; } -void Engine::init(AllocatorImpl allocator, void *app, +void Engine::init(AllocatorImpl allocator, void * app, Span config_path, Span assets_dir) { if (logger == nullptr) @@ -139,7 +139,7 @@ void Engine::init(AllocatorImpl allocator, void *app, Dyn instance = gpu::create_vulkan_instance(allocator, cfg.gpu.validation).unwrap(); - gpu::Device *device = + gpu::Device * device = instance->create_device(allocator, cfg.gpu.preferences, 2).unwrap(); GpuContext gpu_ctx = @@ -210,7 +210,7 @@ void Engine::init(AllocatorImpl allocator, void *app, window_system->listen( SystemEventTypes::All, - fn(engine, [](Engine *engine, SystemEvent const &event) { + fn(engine, [](Engine * engine, SystemEvent const & event) { if (event.type == SystemEventTypes::ThemeChanged) { engine->view_ctx.theme = event.theme; @@ -219,7 +219,7 @@ void Engine::init(AllocatorImpl allocator, void *app, window_system->listen( window, WindowEventTypes::All, - fn(engine, [](Engine *engine, WindowEvent const &event) { + fn(engine, [](Engine * engine, WindowEvent const & event) { if (event.type == WindowEventTypes::CloseRequested) { engine->should_shutdown = true; @@ -235,7 +235,7 @@ void Engine::init(AllocatorImpl allocator, void *app, create_semaphore(allocator, cfg.shaders.size() + cfg.fonts.size()) .unwrap(); - cfg.shaders.iter([&](Vec &id, Vec &path) { + cfg.shaders.iter([&](Vec & id, Vec & path) { Vec resolved_path = vec(allocator, assets_dir).unwrap(); path_append(resolved_path, path).unwrap(); @@ -287,7 +287,7 @@ void Engine::init(AllocatorImpl allocator, void *app, }); }); - cfg.fonts.iter([&](Vec &id, Vec &path) { + cfg.fonts.iter([&](Vec & id, Vec & path) { Vec resolved_path = vec(allocator, assets_dir).unwrap(); path_append(resolved_path, path).unwrap(); @@ -379,7 +379,7 @@ Engine::~Engine() assets.shaders.iter( [&](Vec &, gpu::Shader shader) { device->uninit_shader(shader); }); assets.shaders.clear(); - assets.fonts.iter([&](Vec &, Dyn &font) { + assets.fonts.iter([&](Vec &, Dyn & font) { font->unload_from_device(gpu_ctx); }); assets.fonts.clear(); @@ -499,7 +499,7 @@ void Engine::recreate_swapchain_() } } -void Engine::run(View &view) +void Engine::run(View & view) { view_ctx.timestamp = steady_clock::now(); view_ctx.timedelta = 0ms; @@ -556,25 +556,27 @@ void Engine::run(View &view) .resolve_mode = gpu::ResolveModes::None, .load_op = gpu::LoadOp::Load, .store_op = gpu::StoreOp::Store, - .clear = {}}}; + .clear = {}} + }; RenderTarget rt{ .info = gpu::RenderingInfo{ - .render_area = {.offset = {}, + .render_area = {.offset = {}, .extent = gpu_ctx.screen_fb.extent}, - .num_layers = 1, - .color_attachments = span(attachments), - .depth_attachment = {}, - .stencil_attachment = {}}, + .num_layers = 1, + .color_attachments = span(attachments), + .depth_attachment = {}, + .stencil_attachment = {}}, .viewport = gpu::Viewport{.offset = {0, 0}, - .extent = as_vec2(gpu_ctx.screen_fb.extent), - .min_depth = 0, - .max_depth = 1}, + .extent = as_vec2(gpu_ctx.screen_fb.extent), + .min_depth = 0, + .max_depth = 1}, .extent = gpu_ctx.screen_fb.extent, .color_descriptor = gpu_ctx.screen_fb.color_texture, .depth_descriptor = nullptr, - .stencil_descriptor = nullptr}; + .stencil_descriptor = nullptr + }; canvas.begin_recording(Vec2{(f32) rt.extent.x, (f32) rt.extent.y}, rt.extent); @@ -591,4 +593,4 @@ void Engine::run(View &view) logger->trace("Ended Engine Run Loop"); } -} // namespace ash \ No newline at end of file +} // namespace ash diff --git a/ashura/engine/engine.h b/ashura/engine/engine.h index a067fc86..b51276a4 100644 --- a/ashura/engine/engine.h +++ b/ashura/engine/engine.h @@ -27,8 +27,8 @@ struct EngineCfg bool resizable = true; bool maximized = false; bool full_screen = false; - u32 width = 1920; - u32 height = 1080; + u32 width = 1'920; + u32 height = 1'080; }; Gpu gpu{}; @@ -58,11 +58,11 @@ struct Engine { AllocatorImpl allocator; - void *app; + void * app; Dyn instance; - gpu::Device *device; + gpu::Device * device; Window window; @@ -86,12 +86,12 @@ struct Engine Vec default_font_name; - Font *default_font = nullptr; + Font * default_font = nullptr; bool should_shutdown = false; - Engine(AllocatorImpl allocator, void *app, Dyn instance, - gpu::Device *device, Window window, gpu::Surface surface, + Engine(AllocatorImpl allocator, void * app, Dyn instance, + gpu::Device * device, Window window, gpu::Surface surface, gpu::PresentMode present_mode_preference, GpuContext gpu_ctx, Renderer renderer, Canvas canvas, ViewSystem view_system, ViewContext view_ctx) : @@ -114,18 +114,18 @@ struct Engine ~Engine(); - static void init(AllocatorImpl allocator, void *app, + static void init(AllocatorImpl allocator, void * app, Span config_path, Span assets_dir); static void uninit(); void recreate_swapchain_(); - void run(View &view); + void run(View & view); }; /// Global Engine Pointer. Can be hooked at runtime for dynamically loaded /// executables. -ASH_C_LINKAGE ASH_DLL_EXPORT Engine *engine; +ASH_C_LINKAGE ASH_DLL_EXPORT Engine * engine; } // namespace ash diff --git a/ashura/engine/font.h b/ashura/engine/font.h index 4ef0609f..a663c8d1 100644 --- a/ashura/engine/font.h +++ b/ashura/engine/font.h @@ -57,7 +57,7 @@ constexpr Span to_string(FontErr err) namespace fmt { -inline bool push(Context const &ctx, Spec const &spec, FontErr const &err) +inline bool push(Context const & ctx, Spec const & spec, FontErr const & err) { return push(ctx, spec, to_string(err)); } @@ -149,9 +149,9 @@ struct Font virtual FontInfo info() = 0; - virtual void upload_to_device(GpuContext &c, AllocatorImpl allocator) = 0; + virtual void upload_to_device(GpuContext & c, AllocatorImpl allocator) = 0; - virtual void unload_from_device(GpuContext &c) = 0; + virtual void unload_from_device(GpuContext & c) = 0; virtual ~Font() = default; }; diff --git a/ashura/engine/font_impl.cc b/ashura/engine/font_impl.cc index f50fa101..e82fe698 100644 --- a/ashura/engine/font_impl.cc +++ b/ashura/engine/font_impl.cc @@ -1,4 +1,3 @@ - /// SPDX-License-Identifier: MIT #include "ashura/engine/font_impl.h" @@ -14,7 +13,7 @@ Result, FontErr> Font::decode(Span encoded, u32 face, return Err{FontErr::OutOfMemory}; } - hb_blob_t *hb_blob = + hb_blob_t * hb_blob = hb_blob_create(font_data.data(), font_data.size(), HB_MEMORY_MODE_READONLY, nullptr, nullptr); @@ -37,7 +36,7 @@ Result, FontErr> Font::decode(Span encoded, u32 face, return Err{FontErr::FaceNotFound}; } - hb_face_t *hb_face = hb_face_create(hb_blob, face); + hb_face_t * hb_face = hb_face_create(hb_blob, face); if (hb_face == nullptr) { @@ -51,7 +50,7 @@ Result, FontErr> Font::decode(Span encoded, u32 face, } }}; - hb_font_t *hb_font = hb_font_create(hb_face); + hb_font_t * hb_font = hb_font_create(hb_face); if (hb_font == nullptr) { @@ -100,8 +99,8 @@ Result, FontErr> Font::decode(Span encoded, u32 face, } }}; - char const *ft_postscript_name = FT_Get_Postscript_Name(ft_face); - usize postscript_name_size = 0; + char const * ft_postscript_name = FT_Get_Postscript_Name(ft_face); + usize postscript_name_size = 0; Vec postscript_name{allocator}; @@ -139,7 +138,7 @@ Result, FontErr> Font::decode(Span encoded, u32 face, } } - u32 const num_glyphs = (u32) ft_face->num_glyphs; + u32 const num_glyphs = (u32) ft_face->num_glyphs; // glyph 0 is selected if the replacement codepoint glyph is not found u32 const replacement_glyph = FT_Get_Char_Index(ft_face, 0xFFFD); u32 const ellipsis_glyph = FT_Get_Char_Index(ft_face, 0x2026); @@ -163,10 +162,12 @@ Result, FontErr> Font::decode(Span encoded, u32 face, { FT_GlyphSlot s = ft_face->glyph; - GlyphMetrics m{.bearing{(i32) s->metrics.horiBearingX, - (i32) -s->metrics.horiBearingY}, - .advance = (i32) s->metrics.horiAdvance, - .extent{(i32) s->metrics.width, (i32) s->metrics.height}}; + GlyphMetrics m{ + .bearing{(i32) s->metrics.horiBearingX, + (i32) -s->metrics.horiBearingY }, + .advance = (i32) s->metrics.horiAdvance, + .extent{(i32) s->metrics.width, (i32) s->metrics.height} + }; // bin offsets are determined after binning and during rect packing glyphs[i] = Glyph{.is_valid = true, .metrics = m}; @@ -195,9 +196,9 @@ Result, FontErr> Font::decode(Span encoded, u32 face, ft_lib = nullptr; ft_face = nullptr; - Font *font_base = font.value().get(); + Font * font_base = font.value().get(); return Ok{transmute(std::move(font.value()), font_base)}; } -} // namespace ash \ No newline at end of file +} // namespace ash diff --git a/ashura/engine/font_impl.h b/ashura/engine/font_impl.h index ba1ad9bd..c46002f7 100644 --- a/ashura/engine/font_impl.h +++ b/ashura/engine/font_impl.h @@ -37,11 +37,11 @@ struct FontImpl : Font /// @brief Font family style name, ASCII. i.e. Bold Vec style_name; - hb_blob_t *hb_blob; + hb_blob_t * hb_blob; - hb_face_t *hb_face; + hb_face_t * hb_face; - hb_font_t *hb_font; + hb_font_t * hb_font; FT_Library ft_lib; @@ -64,8 +64,8 @@ struct FontImpl : Font Option gpu_atlas = None; FontImpl(Vec font_data, Vec postscript_name, - Vec family_name, Vec style_name, hb_blob_t *hb_blob, - hb_face_t *hb_face, hb_font_t *hb_font, FT_Library ft_lib, + Vec family_name, Vec style_name, hb_blob_t * hb_blob, + hb_face_t * hb_face, hb_font_t * hb_font, FT_Library ft_lib, FT_Face ft_face, u32 face, Vec glyphs, u32 replacement_glyph, u32 ellipsis_glyph, u32 space_glyph, FontMetrics metrics) : font_data{std::move(font_data)}, @@ -90,9 +90,9 @@ struct FontImpl : Font FontImpl(FontImpl &&) = delete; - FontImpl &operator=(FontImpl const &) = delete; + FontImpl & operator=(FontImpl const &) = delete; - FontImpl &operator=(FontImpl &&) = delete; + FontImpl & operator=(FontImpl &&) = delete; virtual ~FontImpl() override { @@ -138,7 +138,7 @@ struct FontImpl : Font "Font atlas extent should be a multiple of 64"); static_assert(MIN_ATLAS_EXTENT <= gpu::MAX_IMAGE_EXTENT_2D, "Font atlas extent too large for GPU platform"); - CHECK(font_height <= 1024); + CHECK(font_height <= 1'024); CHECK(font_height <= MIN_ATLAS_EXTENT / 8); Vec2U atlas_extent{MIN_ATLAS_EXTENT, MIN_ATLAS_EXTENT}; @@ -193,21 +193,21 @@ struct FontImpl : Font for (u32 g = 0, irect = 0; g < glyphs.size32(); g++) { - Glyph const &gl = glyphs[g]; - AtlasGlyph const &agl = atlas.glyphs[g]; + Glyph const & gl = glyphs[g]; + AtlasGlyph const & agl = atlas.glyphs[g]; // only assign packing rects to the valid glyphs if (gl.is_valid && agl.area.extent.x != 0 && agl.area.extent.y != 0) { - rect_pack::rect &r = rects[irect]; - r.glyph_index = g; - r.x = 0; - r.y = 0; + rect_pack::rect & r = rects[irect]; + r.glyph_index = g; + r.x = 0; + r.y = 0; // added padding to avoid texture spilling due to accumulated // floating-point uv interpolation errors - r.w = (i32) (agl.area.extent.x + 2); - r.h = (i32) (agl.area.extent.y + 2); - atlas_extent.x = max(atlas_extent.x, agl.area.extent.x + 2); - atlas_extent.y = max(atlas_extent.y, agl.area.extent.y + 2); + r.w = (i32) (agl.area.extent.x + 2); + r.h = (i32) (agl.area.extent.y + 2); + atlas_extent.x = max(atlas_extent.x, agl.area.extent.x + 2); + atlas_extent.y = max(atlas_extent.y, agl.area.extent.y + 2); irect++; } } @@ -235,7 +235,7 @@ struct FontImpl : Font num_rasterized_glyphs - num_packed); auto [just_packed, unpacked] = partition(span(rects).slice(num_packed), - [](rect_pack::rect const &r) { return r.was_packed; }); + [](rect_pack::rect const & r) { return r.was_packed; }); for (u32 i = num_packed; i < (num_packed + just_packed.span); i++) { rects[i].layer = num_layers; @@ -251,7 +251,7 @@ struct FontImpl : Font for (u32 i = 0; i < num_rasterized_glyphs; i++) { rect_pack::rect r = rects[i]; - AtlasGlyph &g = atlas.glyphs[r.glyph_index]; + AtlasGlyph & g = atlas.glyphs[r.glyph_index]; g.area.offset.x = (u32) r.x + 1; g.area.offset.y = (u32) r.y + 1; g.layer = r.layer; @@ -276,8 +276,8 @@ struct FontImpl : Font for (u32 i = 0; i < glyphs.size32(); i++) { - Glyph const &g = glyphs[i]; - AtlasGlyph const &ag = atlas.glyphs[i]; + Glyph const & g = glyphs[i]; + AtlasGlyph const & ag = atlas.glyphs[i]; if (g.is_valid) { FT_GlyphSlot slot = ft_face->glyph; @@ -297,7 +297,8 @@ struct FontImpl : Font slot->bitmap.rows * (u32) slot->bitmap.pitch}, .width = slot->bitmap.width, .height = slot->bitmap.rows, - .stride = (u32) slot->bitmap.pitch}; + .stride = (u32) slot->bitmap.pitch + }; copy_image(src, atlas_span.get_layer(ag.layer).slice(ag.area.offset, ag.area.extent)); @@ -313,35 +314,37 @@ struct FontImpl : Font return Ok{}; } - virtual void upload_to_device(GpuContext &c, AllocatorImpl allocator) override + virtual void upload_to_device(GpuContext & c, + AllocatorImpl allocator) override { - gpu::CommandEncoder &enc = c.encoder(); - gpu::Device &dev = *c.device; + gpu::CommandEncoder & enc = c.encoder(); + gpu::Device & dev = *c.device; CHECK(cpu_atlas.is_some()); CHECK(gpu_atlas.is_none()); - CpuFontAtlas const &atlas = cpu_atlas.value(); + CpuFontAtlas const & atlas = cpu_atlas.value(); CHECK(atlas.num_layers > 0); CHECK(atlas.extent.x > 0); CHECK(atlas.extent.y > 0); gpu::Image image = - dev.create_image( - gpu::ImageInfo{.label = "Font Atlas Image"_str, - .type = gpu::ImageType::Type2D, - .format = gpu::Format::B8G8R8A8_UNORM, - .usage = gpu::ImageUsage::Sampled | - gpu::ImageUsage::InputAttachment | - gpu::ImageUsage::Storage | - gpu::ImageUsage::TransferSrc | - gpu::ImageUsage::TransferDst, - .aspects = gpu::ImageAspects::Color, - .extent = {atlas.extent.x, atlas.extent.y, 1}, - .mip_levels = 1, - .array_layers = atlas.num_layers, - .sample_count = gpu::SampleCount::Count1}) + dev.create_image(gpu::ImageInfo{ + .label = "Font Atlas Image"_str, + .type = gpu::ImageType::Type2D, + .format = gpu::Format::B8G8R8A8_UNORM, + .usage = gpu::ImageUsage::Sampled | + gpu::ImageUsage::InputAttachment | + gpu::ImageUsage::Storage | + gpu::ImageUsage::TransferSrc | + gpu::ImageUsage::TransferDst, + .aspects = gpu::ImageAspects::Color, + .extent = {atlas.extent.x, atlas.extent.y, 1}, + .mip_levels = 1, + .array_layers = atlas.num_layers, + .sample_count = gpu::SampleCount::Count1 + }) .unwrap(); Vec views; @@ -375,12 +378,14 @@ struct FontImpl : Font gpu::BufferUsage::TransferDst}) .unwrap(); - u8 *map = (u8 *) dev.map_buffer_memory(staging_buffer).unwrap(); + u8 * map = (u8 *) dev.map_buffer_memory(staging_buffer).unwrap(); - ImageLayerSpan dst{.channels = {map, atlas_size}, - .width = atlas.extent.x, - .height = atlas.extent.y, - .layers = atlas.num_layers}; + ImageLayerSpan dst{ + .channels = {map, atlas_size}, + .width = atlas.extent.x, + .height = atlas.extent.y, + .layers = atlas.num_layers + }; for (u32 i = 0; i < atlas.num_layers; i++) { @@ -410,7 +415,8 @@ struct FontImpl : Font .first_array_layer = layer, .num_array_layers = 1}, .image_offset = {0, 0, 0}, - .image_extent = {atlas.extent.x, atlas.extent.y, 1}}; + .image_extent = {atlas.extent.x, atlas.extent.y, 1} + }; } enc.copy_buffer_to_image(staging_buffer, image, copies); @@ -434,17 +440,19 @@ struct FontImpl : Font .images = span({gpu::ImageBinding{.image_view = views[i]}})}); } - gpu_atlas = Some{GpuFontAtlas{.image = image, - .views = std::move(views), - .textures = std::move(textures), - .font_height = atlas.font_height, - .num_layers = atlas.num_layers, - .extent = atlas.extent, - .glyphs = std::move(glyphs), - .format = format}}; + gpu_atlas = Some{ + GpuFontAtlas{.image = image, + .views = std::move(views), + .textures = std::move(textures), + .font_height = atlas.font_height, + .num_layers = atlas.num_layers, + .extent = atlas.extent, + .glyphs = std::move(glyphs), + .format = format} + }; } - virtual void unload_from_device(GpuContext &c) override + virtual void unload_from_device(GpuContext & c) override { CHECK_DESC(gpu_atlas.is_some(), "Requested font to be unloaded from GPU with no GPU atlas"); diff --git a/ashura/engine/gpu_context.cc b/ashura/engine/gpu_context.cc index d6f45b9d..36598b0b 100644 --- a/ashura/engine/gpu_context.cc +++ b/ashura/engine/gpu_context.cc @@ -4,7 +4,7 @@ namespace ash { -GpuContext GpuContext::create(AllocatorImpl allocator, gpu::Device *device, +GpuContext GpuContext::create(AllocatorImpl allocator, gpu::Device * device, bool use_hdr, u32 buffering, gpu::Extent initial_extent) { @@ -108,7 +108,9 @@ GpuContext GpuContext::create(AllocatorImpl allocator, gpu::Device *device, .bindings = span({gpu::DescriptorBindingInfo{ .type = gpu::DescriptorType::DynamicUniformBuffer, .count = 1, - .is_variable_length = false}})}) + .is_variable_length = false}} + ) + }) .unwrap(); gpu::DescriptorSetLayout ssbo_layout = @@ -120,7 +122,9 @@ GpuContext GpuContext::create(AllocatorImpl allocator, gpu::Device *device, .bindings = span({gpu::DescriptorBindingInfo{ .type = gpu::DescriptorType::DynamicStorageBuffer, .count = 1, - .is_variable_length = false}})}) + .is_variable_length = false}} + ) + }) .unwrap(); gpu::DescriptorSetLayout textures_layout = @@ -132,7 +136,9 @@ GpuContext GpuContext::create(AllocatorImpl allocator, gpu::Device *device, .bindings = span({gpu::DescriptorBindingInfo{ .type = gpu::DescriptorType::SampledImage, .count = NUM_TEXTURE_SLOTS, - .is_variable_length = true}})}) + .is_variable_length = true}} + ) + }) .unwrap(); gpu::DescriptorSetLayout samplers_layout = @@ -144,7 +150,9 @@ GpuContext GpuContext::create(AllocatorImpl allocator, gpu::Device *device, .bindings = span({gpu::DescriptorBindingInfo{ .type = gpu::DescriptorType::Sampler, .count = NUM_SAMPLER_SLOTS, - .is_variable_length = true}})}) + .is_variable_length = true}} + ) + }) .unwrap(); gpu::DescriptorSet texture_views = @@ -171,7 +179,8 @@ GpuContext GpuContext::create(AllocatorImpl allocator, gpu::Device *device, .extent = {1, 1, 1}, .mip_levels = 1, .array_layers = 1, - .sample_count = gpu::SampleCount::Count1}) + .sample_count = gpu::SampleCount::Count1 + }) .unwrap(); Array default_image_views; @@ -344,7 +353,7 @@ GpuContext GpuContext::create(AllocatorImpl allocator, gpu::Device *device, return ctx; } -static void recreate_framebuffer(GpuContext &ctx, Framebuffer &fb, +static void recreate_framebuffer(GpuContext & ctx, Framebuffer & fb, gpu::Extent new_extent) { ctx.release(fb); @@ -360,7 +369,8 @@ static void recreate_framebuffer(GpuContext &ctx, Framebuffer &fb, .extent = gpu::Extent3D{new_extent.x, new_extent.y, 1}, .mip_levels = 1, .array_layers = 1, - .sample_count = gpu::SampleCount::Count1}; + .sample_count = gpu::SampleCount::Count1 + }; fb.color.image = ctx.device->create_image(fb.color.info).unwrap(); @@ -388,7 +398,8 @@ static void recreate_framebuffer(GpuContext &ctx, Framebuffer &fb, .extent = gpu::Extent3D{new_extent.x, new_extent.y, 1}, .mip_levels = 1, .array_layers = 1, - .sample_count = gpu::SampleCount::Count1}; + .sample_count = gpu::SampleCount::Count1 + }; fb.depth_stencil.image = ctx.device->create_image(fb.depth_stencil.info).unwrap(); @@ -426,13 +437,13 @@ static void recreate_framebuffer(GpuContext &ctx, Framebuffer &fb, void GpuContext::recreate_framebuffers(gpu::Extent new_extent) { recreate_framebuffer(*this, screen_fb, new_extent); - for (Framebuffer &f : scratch_fbs) + for (Framebuffer & f : scratch_fbs) { recreate_framebuffer(*this, f, new_extent); } } -gpu::CommandEncoder &GpuContext::encoder() +gpu::CommandEncoder & GpuContext::encoder() { gpu::FrameContext ctx = device->get_frame_context(); return *ctx.encoders[ctx.ring_index]; @@ -456,9 +467,9 @@ gpu::FrameId GpuContext::tail_frame_id() return ctx.tail; } -CachedSampler GpuContext::create_sampler(gpu::SamplerInfo const &info) +CachedSampler GpuContext::create_sampler(gpu::SamplerInfo const & info) { - CachedSampler *cached = sampler_cache.try_get(info); + CachedSampler * cached = sampler_cache.try_get(info); if (cached != nullptr) { return *cached; @@ -586,7 +597,7 @@ void GpuContext::release(gpu::Sampler sampler) .unwrap(); } -static void uninit_objects(gpu::Device *d, Span objects) +static void uninit_objects(gpu::Device * d, Span objects) { for (gpu::Object obj : objects) { @@ -622,7 +633,7 @@ static void uninit_objects(gpu::Device *d, Span objects) void GpuContext::idle_reclaim() { device->wait_idle().unwrap(); - for (auto &objects : released_objects) + for (auto & objects : released_objects) { uninit_objects(device, objects); objects.clear(); @@ -635,20 +646,26 @@ void GpuContext::begin_frame(gpu::Swapchain swapchain) uninit_objects(device, released_objects[ring_index()]); released_objects[ring_index()].clear(); - gpu::CommandEncoder &enc = encoder(); + gpu::CommandEncoder & enc = encoder(); enc.clear_color_image( - screen_fb.color.image, gpu::Color{.float32 = {0, 0, 0, 0}}, + screen_fb.color.image, + gpu::Color{ + .float32 = {0, 0, 0, 0} + }, span({gpu::ImageSubresourceRange{.aspects = gpu::ImageAspects::Color, .first_mip_level = 0, .num_mip_levels = 1, .first_array_layer = 0, .num_array_layers = 1}})); - for (Framebuffer const &f : scratch_fbs) + for (Framebuffer const & f : scratch_fbs) { enc.clear_color_image( - f.color.image, gpu::Color{.float32 = {0, 0, 0, 0}}, + f.color.image, + gpu::Color{ + .float32 = {0, 0, 0, 0} + }, span({gpu::ImageSubresourceRange{.aspects = gpu::ImageAspects::Color, .first_mip_level = 0, .num_mip_levels = 1, @@ -658,7 +675,9 @@ void GpuContext::begin_frame(gpu::Swapchain swapchain) enc.clear_depth_stencil_image( screen_fb.depth_stencil.image, - gpu::DepthStencil{.depth = 0, .stencil = 0}, + gpu::DepthStencil{ + .depth = 0, .stencil = 0 + }, span({gpu::ImageSubresourceRange{.aspects = gpu::ImageAspects::Depth | gpu::ImageAspects::Stencil, .first_mip_level = 0, @@ -666,10 +685,13 @@ void GpuContext::begin_frame(gpu::Swapchain swapchain) .first_array_layer = 0, .num_array_layers = 1}})); - for (Framebuffer const &f : scratch_fbs) + for (Framebuffer const & f : scratch_fbs) { enc.clear_depth_stencil_image( - f.depth_stencil.image, gpu::DepthStencil{.depth = 0, .stencil = 0}, + f.depth_stencil.image, + gpu::DepthStencil{ + .depth = 0, .stencil = 0 + }, span({gpu::ImageSubresourceRange{.aspects = gpu::ImageAspects::Depth | gpu::ImageAspects::Stencil, .first_mip_level = 0, @@ -681,7 +703,7 @@ void GpuContext::begin_frame(gpu::Swapchain swapchain) void GpuContext::submit_frame(gpu::Swapchain swapchain) { - gpu::CommandEncoder &enc = encoder(); + gpu::CommandEncoder & enc = encoder(); if (swapchain != nullptr) { gpu::SwapchainState swapchain_state = @@ -692,33 +714,35 @@ void GpuContext::submit_frame(gpu::Swapchain swapchain) enc.blit_image( screen_fb.color.image, swapchain_state.images[swapchain_state.current_image.unwrap()], - span({gpu::ImageBlit{ - .src_layers = {.aspects = gpu::ImageAspects::Color, - .mip_level = 0, - .first_array_layer = 0, - .num_array_layers = 1}, - .src_offsets = {{0, 0, 0}, - {screen_fb.extent.x, screen_fb.extent.y, 1}}, - .dst_layers = {.aspects = gpu::ImageAspects::Color, - .mip_level = 0, - .first_array_layer = 0, - .num_array_layers = 1}, - .dst_offsets = {{0, 0, 0}, - {swapchain_state.extent.x, - swapchain_state.extent.y, 1}}}}), + span({ + gpu::ImageBlit{ + .src_layers = {.aspects = gpu::ImageAspects::Color, + .mip_level = 0, + .first_array_layer = 0, + .num_array_layers = 1}, + .src_offsets = {{0, 0, 0}, + {screen_fb.extent.x, screen_fb.extent.y, 1}}, + .dst_layers = {.aspects = gpu::ImageAspects::Color, + .mip_level = 0, + .first_array_layer = 0, + .num_array_layers = 1}, + .dst_offsets = {{0, 0, 0}, + {swapchain_state.extent.x, + swapchain_state.extent.y, 1}}} + }), gpu::Filter::Linear); } } device->submit_frame(swapchain).unwrap(); } -void SSBO::uninit(GpuContext &ctx) +void SSBO::uninit(GpuContext & ctx) { ctx.device->uninit_descriptor_set(descriptor); ctx.device->uninit_buffer(buffer); } -void SSBO::reserve(GpuContext &ctx, u64 p_size) +void SSBO::reserve(GpuContext & ctx, u64 p_size) { p_size = max(p_size, (u64) 1); if (buffer != nullptr && size >= p_size) @@ -751,38 +775,40 @@ void SSBO::reserve(GpuContext &ctx, u64 p_size) .binding = 0, .element = 0, .buffers = span({gpu::BufferBinding{ - .buffer = buffer, .offset = 0, .size = p_size}})}); + .buffer = buffer, .offset = 0, .size = p_size}} + ) + }); size = p_size; } -void SSBO::copy(GpuContext &ctx, Span src) +void SSBO::copy(GpuContext & ctx, Span src) { reserve(ctx, (u64) src.size()); - u8 *data = (u8 *) map(ctx); + u8 * data = (u8 *) map(ctx); mem::copy(src, data); flush(ctx); unmap(ctx); } -void *SSBO::map(GpuContext &ctx) +void * SSBO::map(GpuContext & ctx) { return ctx.device->map_buffer_memory(buffer).unwrap(); } -void SSBO::unmap(GpuContext &ctx) +void SSBO::unmap(GpuContext & ctx) { ctx.device->unmap_buffer_memory(buffer); } -void SSBO::flush(GpuContext &ctx) +void SSBO::flush(GpuContext & ctx) { ctx.device ->flush_mapped_buffer_memory(buffer, gpu::MemoryRange{0, gpu::WHOLE_SIZE}) .unwrap(); } -void SSBO::release(GpuContext &ctx) +void SSBO::release(GpuContext & ctx) { ctx.release(buffer); ctx.release(descriptor); @@ -791,4 +817,4 @@ void SSBO::release(GpuContext &ctx) descriptor = nullptr; } -} // namespace ash \ No newline at end of file +} // namespace ash diff --git a/ashura/engine/gpu_context.h b/ashura/engine/gpu_context.h index 04729e94..79044298 100644 --- a/ashura/engine/gpu_context.h +++ b/ashura/engine/gpu_context.h @@ -44,7 +44,7 @@ struct Framebuffer struct SamplerHasher { - constexpr Hash operator()(gpu::SamplerInfo const &info) const + constexpr Hash operator()(gpu::SamplerInfo const & info) const { return hash_combine_n( (Hash) info.mag_filter, (Hash) info.min_filter, @@ -59,8 +59,8 @@ struct SamplerHasher struct SamplerEq { - constexpr Hash operator()(gpu::SamplerInfo const &a, - gpu::SamplerInfo const &b) const + constexpr Hash operator()(gpu::SamplerInfo const & a, + gpu::SamplerInfo const & b) const { return a.mag_filter == b.mag_filter && a.mip_map_mode == b.mip_map_mode && a.address_mode_u == b.address_mode_u && @@ -116,11 +116,11 @@ struct GpuContext gpu::Format::D16_UNORM_S8_UINT, gpu::Format::D24_UNORM_S8_UINT, gpu::Format::D32_SFLOAT_S8_UINT}; - static constexpr u16 NUM_TEXTURE_SLOTS = 1024; + static constexpr u16 NUM_TEXTURE_SLOTS = 1'024; static constexpr u16 NUM_SAMPLER_SLOTS = 64; static constexpr u16 NUM_SCRATCH_FRAMEBUFFERS = 2; - gpu::Device *device; + gpu::Device * device; gpu::PipelineCache pipeline_cache; @@ -158,12 +158,12 @@ struct GpuContext Bits sampler_slots; - static GpuContext create(AllocatorImpl allocator, gpu::Device *device, + static GpuContext create(AllocatorImpl allocator, gpu::Device * device, bool use_hdr, u32 buffering, gpu::Extent initial_extent); GpuContext( - AllocatorImpl allocator, gpu::Device *device, + AllocatorImpl allocator, gpu::Device * device, gpu::PipelineCache pipeline_cache, u32 buffering, gpu::Format color_format, gpu::Format depth_stencil_format, gpu::DescriptorSetLayout ubo_layout, gpu::DescriptorSetLayout ssbo_layout, @@ -195,10 +195,10 @@ struct GpuContext { } - GpuContext(GpuContext const &) = delete; - GpuContext(GpuContext &&) = default; - GpuContext &operator=(GpuContext const &) = delete; - GpuContext &operator=(GpuContext &&) = default; + GpuContext(GpuContext const &) = delete; + GpuContext(GpuContext &&) = default; + GpuContext & operator=(GpuContext const &) = delete; + GpuContext & operator=(GpuContext &&) = default; ~GpuContext() { @@ -214,7 +214,7 @@ struct GpuContext release(textures_layout); release(samplers_layout); release(screen_fb); - for (Framebuffer &f : scratch_fbs) + for (Framebuffer & f : scratch_fbs) { release(f); } @@ -227,7 +227,7 @@ struct GpuContext void recreate_framebuffers(gpu::Extent new_extent); - gpu::CommandEncoder &encoder(); + gpu::CommandEncoder & encoder(); u32 ring_index(); @@ -235,7 +235,7 @@ struct GpuContext gpu::FrameId tail_frame_id(); - CachedSampler create_sampler(gpu::SamplerInfo const &info); + CachedSampler create_sampler(gpu::SamplerInfo const & info); u32 alloc_texture_slot(); @@ -289,19 +289,19 @@ struct SSBO Span label = "SSBO"_str; - void uninit(GpuContext &ctx); + void uninit(GpuContext & ctx); - void reserve(GpuContext &ctx, u64 size); + void reserve(GpuContext & ctx, u64 size); - void copy(GpuContext &ctx, Span src); + void copy(GpuContext & ctx, Span src); - void *map(GpuContext &ctx); + void * map(GpuContext & ctx); - void unmap(GpuContext &ctx); + void unmap(GpuContext & ctx); - void flush(GpuContext &ctx); + void flush(GpuContext & ctx); - void release(GpuContext &ctx); + void release(GpuContext & ctx); }; } // namespace ash diff --git a/ashura/engine/image_decoder.cc b/ashura/engine/image_decoder.cc index 2a681ff6..73075428 100644 --- a/ashura/engine/image_decoder.cc +++ b/ashura/engine/image_decoder.cc @@ -19,7 +19,7 @@ constexpr u64 rgba8_size(bool has_alpha, u32 width, u32 height) return ((u64) width) * ((u64) height) * (has_alpha ? 4ULL : 3ULL); } -ImageDecodeError decode_webp(Span bytes, DecodedImage &image) +ImageDecodeError decode_webp(Span bytes, DecodedImage & image) { WebPBitstreamFeatures features; @@ -63,15 +63,15 @@ ImageDecodeError decode_webp(Span bytes, DecodedImage &image) return ImageDecodeError::None; } -inline void png_stream_reader(png_structp png_ptr, unsigned char *out, +inline void png_stream_reader(png_structp png_ptr, unsigned char * out, usize nbytes_to_read) { - Span *input = (Span *) png_get_io_ptr(png_ptr); + Span * input = (Span *) png_get_io_ptr(png_ptr); mem::copy(input->slice(0, nbytes_to_read), out); *input = input->slice(nbytes_to_read); } -ImageDecodeError decode_png(Span bytes, DecodedImage &image) +ImageDecodeError decode_png(Span bytes, DecodedImage & image) { // skip magic number bytes = bytes.slice(8); @@ -128,7 +128,7 @@ ImageDecodeError decode_png(Span bytes, DecodedImage &image) return ImageDecodeError::OutOfMemory; } - u8 *row = image.channels.data(); + u8 * row = image.channels.data(); for (u32 i = 0; i < height; i++) { png_read_row(png_ptr, row, nullptr); @@ -143,7 +143,7 @@ ImageDecodeError decode_png(Span bytes, DecodedImage &image) return ImageDecodeError::None; } -ImageDecodeError decode_jpg(Span bytes, DecodedImage &image) +ImageDecodeError decode_jpg(Span bytes, DecodedImage & image) { jpeg_decompress_struct info; jpeg_error_mgr error_mgr; @@ -184,10 +184,10 @@ ImageDecodeError decode_jpg(Span bytes, DecodedImage &image) return ImageDecodeError::OutOfMemory; } - u8 *scanline = image.channels.data(); + u8 * scanline = image.channels.data(); while (info.output_scanline < height) { - u8 *scanlines[] = {scanline}; + u8 * scanlines[] = {scanline}; scanline += (u64) jpeg_read_scanlines(&info, scanlines, 1) * pitch; } @@ -200,7 +200,7 @@ ImageDecodeError decode_jpg(Span bytes, DecodedImage &image) return ImageDecodeError::None; } -ImageDecodeError decode_image(Span bytes, DecodedImage &image) +ImageDecodeError decode_image(Span bytes, DecodedImage & image) { constexpr u8 JPG_MAGIC[] = {0xFF, 0xD8, 0xFF}; @@ -229,4 +229,4 @@ ImageDecodeError decode_image(Span bytes, DecodedImage &image) return ImageDecodeError::UnsupportedFormat; } -} // namespace ash \ No newline at end of file +} // namespace ash diff --git a/ashura/engine/image_decoder.h b/ashura/engine/image_decoder.h index 6fbf7055..ae441c84 100644 --- a/ashura/engine/image_decoder.h +++ b/ashura/engine/image_decoder.h @@ -32,9 +32,9 @@ struct DecodedImage gpu::Format format = gpu::Format::Undefined; }; -ImageDecodeError decode_webp(Span bytes, DecodedImage &image); -ImageDecodeError decode_jpg(Span bytes, DecodedImage &image); -ImageDecodeError decode_png(Span bytes, DecodedImage &image); -ImageDecodeError decode_image(Span bytes, DecodedImage &image); +ImageDecodeError decode_webp(Span bytes, DecodedImage & image); +ImageDecodeError decode_jpg(Span bytes, DecodedImage & image); +ImageDecodeError decode_png(Span bytes, DecodedImage & image); +ImageDecodeError decode_image(Span bytes, DecodedImage & image); } // namespace ash diff --git a/ashura/engine/input.h b/ashura/engine/input.h index a6e15102..7a961814 100644 --- a/ashura/engine/input.h +++ b/ashura/engine/input.h @@ -597,30 +597,30 @@ struct MouseWheelEvent enum class WindowEventTypes : u32 { - None = 0x00000000, - Shown = 0x00000001, - Hidden = 0x00000002, - Exposed = 0x00000004, - Moved = 0x00000008, - Resized = 0x00000010, - SurfaceResized = 0x00000020, - Minimized = 0x00000040, - Maximized = 0x00000080, - Restored = 0x00000100, - MouseEnter = 0x00000200, - MouseLeave = 0x00000400, - FocusIn = 0x00000800, - FocusOut = 0x00001000, - CloseRequested = 0x00002000, - Occluded = 0x00004000, - EnterFullScreen = 0x00008000, - LeaveFullScreen = 0x00010000, - Key = 0x00020000, - MouseMotion = 0x00040000, - MouseClick = 0x00080000, - MouseWheel = 0x00100000, - Destroyed = 0x00200000, - All = 0xFFFFFFFF + None = 0x0000'0000, + Shown = 0x0000'0001, + Hidden = 0x0000'0002, + Exposed = 0x0000'0004, + Moved = 0x0000'0008, + Resized = 0x0000'0010, + SurfaceResized = 0x0000'0020, + Minimized = 0x0000'0040, + Maximized = 0x0000'0080, + Restored = 0x0000'0100, + MouseEnter = 0x0000'0200, + MouseLeave = 0x0000'0400, + FocusIn = 0x0000'0800, + FocusOut = 0x0000'1000, + CloseRequested = 0x0000'2000, + Occluded = 0x0000'4000, + EnterFullScreen = 0x0000'8000, + LeaveFullScreen = 0x0001'0000, + Key = 0x0002'0000, + MouseMotion = 0x0004'0000, + MouseClick = 0x0008'0000, + MouseWheel = 0x0010'0000, + Destroyed = 0x0020'0000, + All = 0xFFFF'FFFF }; ASH_DEFINE_ENUM_BIT_OPS(WindowEventTypes) @@ -634,26 +634,27 @@ struct WindowEvent MouseClickEvent mouse_click; MouseWheelEvent mouse_wheel; }; + WindowEventTypes type = WindowEventTypes::None; }; enum class SystemEventTypes : u32 { - None = 0x00000000, - ThemeChanged = 0x00000001, - KeymapChanged = 0x00000002, - AudioDeviceAdded = 0x00000004, - AudioDeviceRemoved = 0x00000008, - AudioDeviceFormatChanged = 0x00000010, - DisplayReoriented = 0x00000020, - DisplayAdded = 0x00000040, - DisplayRemoved = 0x00000080, - DisplayMoved = 0x00000100, - CameraAdded = 0x00000200, - CameraRemoved = 0x00000400, - CameraApproved = 0x00000800, - CameraDenied = 0x00001000, - All = 0xFFFFFFFF + None = 0x0000'0000, + ThemeChanged = 0x0000'0001, + KeymapChanged = 0x0000'0002, + AudioDeviceAdded = 0x0000'0004, + AudioDeviceRemoved = 0x0000'0008, + AudioDeviceFormatChanged = 0x0000'0010, + DisplayReoriented = 0x0000'0020, + DisplayAdded = 0x0000'0040, + DisplayRemoved = 0x0000'0080, + DisplayMoved = 0x0000'0100, + CameraAdded = 0x0000'0200, + CameraRemoved = 0x0000'0400, + CameraApproved = 0x0000'0800, + CameraDenied = 0x0000'1000, + All = 0xFFFF'FFFF }; ASH_DEFINE_ENUM_BIT_OPS(SystemEventTypes) @@ -664,6 +665,7 @@ struct SystemEvent { SystemTheme theme; }; + SystemEventTypes type = SystemEventTypes::None; }; @@ -782,7 +784,7 @@ constexpr char const MIME_FONT_WOFF2[] = "font/woff2"; struct ClipBoard { - virtual Result<> get(Span mime, Vec &out) + virtual Result<> get(Span mime, Vec & out) { (void) mime; (void) out; @@ -796,7 +798,7 @@ struct ClipBoard return Err{}; } - Result<> get_text(Vec &out) + Result<> get_text(Vec & out) { return get(MIME_TEXT_UTF8, out); } diff --git a/ashura/engine/passes.cc b/ashura/engine/passes.cc index 0af97c56..2b56b307 100644 --- a/ashura/engine/passes.cc +++ b/ashura/engine/passes.cc @@ -23,7 +23,7 @@ void BloomPass::encode(GpuContext &, gpu::CommandEncoder &, /// A' = Blur(A) + B' } -void BlurPass::acquire(GpuContext &ctx, AssetMap &assets) +void BlurPass::acquire(GpuContext & ctx, AssetMap & assets) { // https://www.youtube.com/watch?v=ml-5OGZC7vE // @@ -66,10 +66,12 @@ void BlurPass::acquire(GpuContext &ctx, AssetMap &assets) .src_alpha_blend_factor = gpu::BlendFactor::Zero, .dst_alpha_blend_factor = gpu::BlendFactor::Zero, .alpha_blend_op = gpu::BlendOp::Add, - .color_write_mask = gpu::ColorComponents::All}}; + .color_write_mask = gpu::ColorComponents::All} + }; - gpu::ColorBlendState color_blend_state{.attachments = attachment_states, - .blend_constant = {1, 1, 1, 1}}; + gpu::ColorBlendState color_blend_state{ + .attachments = attachment_states, .blend_constant = {1, 1, 1, 1} + }; gpu::DescriptorSetLayout set_layouts[] = {ctx.samplers_layout, ctx.textures_layout}; @@ -95,7 +97,8 @@ void BlurPass::acquire(GpuContext &ctx, AssetMap &assets) .rasterization_state = raster_state, .depth_stencil_state = depth_stencil_state, .color_blend_state = color_blend_state, - .cache = ctx.pipeline_cache}; + .cache = ctx.pipeline_cache + }; downsample_pipeline = ctx.device->create_graphics_pipeline(pipeline_info).unwrap(); @@ -107,13 +110,13 @@ void BlurPass::acquire(GpuContext &ctx, AssetMap &assets) ctx.device->create_graphics_pipeline(pipeline_info).unwrap(); } -void BlurPass::release(GpuContext &ctx, AssetMap &) +void BlurPass::release(GpuContext & ctx, AssetMap &) { ctx.device->uninit_graphics_pipeline(downsample_pipeline); ctx.device->uninit_graphics_pipeline(upsample_pipeline); } -void sample(BlurPass &b, GpuContext &c, gpu::CommandEncoder &e, f32 rad, +void sample(BlurPass & b, GpuContext & c, gpu::CommandEncoder & e, f32 rad, gpu::DescriptorSet src_texture, u32 src_index, gpu::Extent src_extent, gpu::Rect src_area, gpu::ImageView dst, Vec2U dst_offset, bool upsample) @@ -130,28 +133,33 @@ void sample(BlurPass &b, GpuContext &c, gpu::CommandEncoder &e, f32 rad, .resolve = nullptr, .resolve_mode = gpu::ResolveModes::None, .load_op = gpu::LoadOp::Clear, - .store_op = gpu::StoreOp::Store}}), + .store_op = gpu::StoreOp::Store}} + ), .depth_attachment = {}, - .stencil_attachment = {}}); + .stencil_attachment = {} + }); e.bind_graphics_pipeline(upsample ? b.upsample_pipeline : b.downsample_pipeline); e.set_graphics_state(gpu::GraphicsState{ - .scissor = {.offset = dst_offset, .extent = src_area.extent}, + .scissor = {.offset = dst_offset, .extent = src_area.extent}, .viewport = {.offset = as_vec2(dst_offset), - .extent = as_vec2(src_area.extent)}}); + .extent = as_vec2(src_area.extent) } + }); e.bind_descriptor_sets(span({c.samplers, src_texture}), {}); - e.push_constants(span({BlurParam{.uv = {uv0, uv1}, - .radius = radius, - .sampler = SAMPLER_LINEAR_CLAMPED, - .texture = src_index}}) + e.push_constants(span({ + BlurParam{.uv = {uv0, uv1}, + .radius = radius, + .sampler = SAMPLER_LINEAR_CLAMPED, + .texture = src_index} + }) .as_u8()); e.draw(4, 1, 0, 0); e.end_rendering(); } -void BlurPass::encode(GpuContext &ctx, gpu::CommandEncoder &e, - BlurPassParams const ¶ms) +void BlurPass::encode(GpuContext & ctx, gpu::CommandEncoder & e, + BlurPassParams const & params) { CHECK(params.passes > 0); Vec2U extent = params.area.extent; @@ -172,7 +180,10 @@ void BlurPass::encode(GpuContext &ctx, gpu::CommandEncoder &e, radius += 1; sample(*this, ctx, e, (f32) radius, ctx.scratch_fbs[src].color_texture, 0, ctx.scratch_fbs[src].extent, - gpu::Rect{Vec2U{0, 0}, params.area.extent}, + gpu::Rect{ + Vec2U{0, 0}, + params.area.extent + }, ctx.scratch_fbs[dst].color.view, Vec2U{0, 0}, false); src = (src + 1) & 1; dst = (dst + 1) & 1; @@ -183,7 +194,10 @@ void BlurPass::encode(GpuContext &ctx, gpu::CommandEncoder &e, { sample(*this, ctx, e, (f32) radius, ctx.scratch_fbs[src].color_texture, 0, ctx.scratch_fbs[src].extent, - gpu::Rect{Vec2U{0, 0}, params.area.extent}, + gpu::Rect{ + Vec2U{0, 0}, + params.area.extent + }, ctx.scratch_fbs[dst].color.view, Vec2U{0, 0}, true); src = (src + 1) & 1; dst = (dst + 1) & 1; @@ -192,11 +206,14 @@ void BlurPass::encode(GpuContext &ctx, gpu::CommandEncoder &e, sample(*this, ctx, e, (f32) radius, ctx.scratch_fbs[src].color_texture, 0, ctx.scratch_fbs[src].extent, - gpu::Rect{Vec2U{0, 0}, params.area.extent}, params.image_view, - params.area.offset, true); + gpu::Rect{ + Vec2U{0, 0}, + params.area.extent + }, + params.image_view, params.area.offset, true); } -void NgonPass::acquire(GpuContext &ctx, AssetMap &assets) +void NgonPass::acquire(GpuContext & ctx, AssetMap & assets) { gpu::Shader vertex_shader = assets.shaders["Ngon:VS"_str]; gpu::Shader fragment_shader = assets.shaders["Ngon:FS"_str]; @@ -230,10 +247,12 @@ void NgonPass::acquire(GpuContext &ctx, AssetMap &assets) .src_alpha_blend_factor = gpu::BlendFactor::One, .dst_alpha_blend_factor = gpu::BlendFactor::Zero, .alpha_blend_op = gpu::BlendOp::Add, - .color_write_mask = gpu::ColorComponents::All}}; + .color_write_mask = gpu::ColorComponents::All} + }; - gpu::ColorBlendState color_blend_state{.attachments = attachment_states, - .blend_constant = {1, 1, 1, 1}}; + gpu::ColorBlendState color_blend_state{ + .attachments = attachment_states, .blend_constant = {1, 1, 1, 1} + }; gpu::DescriptorSetLayout set_layouts[] = { ctx.ssbo_layout, ctx.ssbo_layout, ctx.ssbo_layout, ctx.samplers_layout, @@ -260,13 +279,14 @@ void NgonPass::acquire(GpuContext &ctx, AssetMap &assets) .rasterization_state = raster_state, .depth_stencil_state = depth_stencil_state, .color_blend_state = color_blend_state, - .cache = ctx.pipeline_cache}; + .cache = ctx.pipeline_cache + }; pipeline = ctx.device->create_graphics_pipeline(pipeline_info).unwrap(); } -void NgonPass::encode(GpuContext &ctx, gpu::CommandEncoder &e, - NgonPassParams const ¶ms) +void NgonPass::encode(GpuContext & ctx, gpu::CommandEncoder & e, + NgonPassParams const & params) { e.begin_rendering(params.rendering_info); e.bind_graphics_pipeline(pipeline); @@ -287,12 +307,12 @@ void NgonPass::encode(GpuContext &ctx, gpu::CommandEncoder &e, e.end_rendering(); } -void NgonPass::release(GpuContext &ctx, AssetMap &) +void NgonPass::release(GpuContext & ctx, AssetMap &) { ctx.device->uninit_graphics_pipeline(pipeline); } -void PBRPass::acquire(GpuContext &ctx, AssetMap &assets) +void PBRPass::acquire(GpuContext & ctx, AssetMap & assets) { gpu::Shader vertex_shader = assets.shaders["PBR:VS"_str]; gpu::Shader fragment_shader = assets.shaders["PBR:FS"_str]; @@ -326,10 +346,12 @@ void PBRPass::acquire(GpuContext &ctx, AssetMap &assets) .src_alpha_blend_factor = gpu::BlendFactor::Zero, .dst_alpha_blend_factor = gpu::BlendFactor::Zero, .alpha_blend_op = gpu::BlendOp::Add, - .color_write_mask = gpu::ColorComponents::All}}; + .color_write_mask = gpu::ColorComponents::All} + }; - gpu::ColorBlendState color_blend_state{.attachments = attachment_states, - .blend_constant = {1, 1, 1, 1}}; + gpu::ColorBlendState color_blend_state{ + .attachments = attachment_states, .blend_constant = {1, 1, 1, 1} + }; gpu::DescriptorSetLayout const set_layouts[] = { ctx.ssbo_layout, ctx.ssbo_layout, ctx.ssbo_layout, @@ -357,7 +379,8 @@ void PBRPass::acquire(GpuContext &ctx, AssetMap &assets) .rasterization_state = raster_state, .depth_stencil_state = depth_stencil_state, .color_blend_state = color_blend_state, - .cache = ctx.pipeline_cache}; + .cache = ctx.pipeline_cache + }; pipeline = ctx.device->create_graphics_pipeline(pipeline_info).unwrap(); @@ -367,20 +390,21 @@ void PBRPass::acquire(GpuContext &ctx, AssetMap &assets) ctx.device->create_graphics_pipeline(pipeline_info).unwrap(); } -void PBRPass::encode(GpuContext &ctx, gpu::CommandEncoder &e, - PBRPassParams const ¶ms) +void PBRPass::encode(GpuContext & ctx, gpu::CommandEncoder & e, + PBRPassParams const & params) { e.begin_rendering(params.rendering_info); e.bind_graphics_pipeline(params.wireframe ? this->wireframe_pipeline : this->pipeline); - e.set_graphics_state( - gpu::GraphicsState{.scissor = params.scissor, - .viewport = params.viewport, - .blend_constant = {1, 1, 1, 1}, - .depth_test_enable = true, - .depth_compare_op = gpu::CompareOp::Less, - .depth_write_enable = true}); + e.set_graphics_state(gpu::GraphicsState{ + .scissor = params.scissor, + .viewport = params.viewport, + .blend_constant = {1, 1, 1, 1}, + .depth_test_enable = true, + .depth_compare_op = gpu::CompareOp::Less, + .depth_write_enable = true + }); e.bind_descriptor_sets( span({params.vertices_ssbo, params.indices_ssbo, params.params_ssbo, params.lights_ssbo, ctx.samplers, params.textures}), @@ -390,13 +414,13 @@ void PBRPass::encode(GpuContext &ctx, gpu::CommandEncoder &e, e.end_rendering(); } -void PBRPass::release(GpuContext &ctx, AssetMap &) +void PBRPass::release(GpuContext & ctx, AssetMap &) { ctx.device->uninit_graphics_pipeline(pipeline); ctx.device->uninit_graphics_pipeline(wireframe_pipeline); } -void RRectPass::acquire(GpuContext &ctx, AssetMap &assets) +void RRectPass::acquire(GpuContext & ctx, AssetMap & assets) { gpu::Shader vertex_shader = assets.shaders["RRect:VS"_str]; gpu::Shader fragment_shader = assets.shaders["RRect:FS"_str]; @@ -430,10 +454,12 @@ void RRectPass::acquire(GpuContext &ctx, AssetMap &assets) .src_alpha_blend_factor = gpu::BlendFactor::One, .dst_alpha_blend_factor = gpu::BlendFactor::Zero, .alpha_blend_op = gpu::BlendOp::Add, - .color_write_mask = gpu::ColorComponents::All}}; + .color_write_mask = gpu::ColorComponents::All} + }; - gpu::ColorBlendState color_blend_state{.attachments = attachment_states, - .blend_constant = {1, 1, 1, 1}}; + gpu::ColorBlendState color_blend_state{ + .attachments = attachment_states, .blend_constant = {1, 1, 1, 1} + }; gpu::DescriptorSetLayout set_layouts[] = { ctx.ssbo_layout, ctx.samplers_layout, ctx.textures_layout}; @@ -459,13 +485,14 @@ void RRectPass::acquire(GpuContext &ctx, AssetMap &assets) .rasterization_state = raster_state, .depth_stencil_state = depth_stencil_state, .color_blend_state = color_blend_state, - .cache = ctx.pipeline_cache}; + .cache = ctx.pipeline_cache + }; pipeline = ctx.device->create_graphics_pipeline(pipeline_info).unwrap(); } -void RRectPass::encode(GpuContext &ctx, gpu::CommandEncoder &e, - RRectPassParams const ¶ms) +void RRectPass::encode(GpuContext & ctx, gpu::CommandEncoder & e, + RRectPassParams const & params) { e.begin_rendering(params.rendering_info); e.bind_graphics_pipeline(pipeline); @@ -479,9 +506,9 @@ void RRectPass::encode(GpuContext &ctx, gpu::CommandEncoder &e, e.end_rendering(); } -void RRectPass::release(GpuContext &ctx, AssetMap &) +void RRectPass::release(GpuContext & ctx, AssetMap &) { ctx.device->uninit_graphics_pipeline(pipeline); } -} // namespace ash \ No newline at end of file +} // namespace ash diff --git a/ashura/engine/passes.h b/ashura/engine/passes.h index e6d17209..c30a9607 100644 --- a/ashura/engine/passes.h +++ b/ashura/engine/passes.h @@ -1,4 +1,3 @@ - /// SPDX-License-Identifier: MIT #pragma once #include "ashura/engine/assets.h" @@ -39,12 +38,12 @@ struct BloomPass : Pass return "Bloom"_str; } - virtual void acquire(GpuContext &ct, AssetMap &assets) override; + virtual void acquire(GpuContext & ct, AssetMap & assets) override; - virtual void release(GpuContext &ctx, AssetMap &assets) override; + virtual void release(GpuContext & ctx, AssetMap & assets) override; - void encode(GpuContext &ctx, gpu::CommandEncoder &encoder, - BloomPassParams const ¶ms); + void encode(GpuContext & ctx, gpu::CommandEncoder & encoder, + BloomPassParams const & params); virtual ~BloomPass() override = default; }; @@ -79,14 +78,14 @@ struct BlurPass : Pass return "Blur"_str; } - virtual void acquire(GpuContext &ctx, AssetMap &assets) override; + virtual void acquire(GpuContext & ctx, AssetMap & assets) override; - virtual void release(GpuContext &ctx, AssetMap &assets) override; + virtual void release(GpuContext & ctx, AssetMap & assets) override; virtual ~BlurPass() override = default; - void encode(GpuContext &ctx, gpu::CommandEncoder &encoder, - BlurPassParams const ¶ms); + void encode(GpuContext & ctx, gpu::CommandEncoder & encoder, + BlurPassParams const & params); }; /// @param transform needs to transform from [-1, +1] to clip space @@ -126,14 +125,14 @@ struct NgonPass : Pass return "Ngon"_str; } - virtual void acquire(GpuContext &ctx, AssetMap &assets) override; + virtual void acquire(GpuContext & ctx, AssetMap & assets) override; - virtual void release(GpuContext &ctx, AssetMap &assets) override; + virtual void release(GpuContext & ctx, AssetMap & assets) override; virtual ~NgonPass() override = default; - void encode(GpuContext &ctx, gpu::CommandEncoder &encoder, - NgonPassParams const ¶ms); + void encode(GpuContext & ctx, gpu::CommandEncoder & encoder, + NgonPassParams const & params); }; /// @see https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos @@ -201,14 +200,14 @@ struct PBRPass : Pass return "PBR"_str; } - virtual void acquire(GpuContext &ctx, AssetMap &assets) override; + virtual void acquire(GpuContext & ctx, AssetMap & assets) override; - virtual void release(GpuContext &ctx, AssetMap &assets) override; + virtual void release(GpuContext & ctx, AssetMap & assets) override; virtual ~PBRPass() override = default; - void encode(GpuContext &ctx, gpu::CommandEncoder &encoder, - PBRPassParams const ¶ms); + void encode(GpuContext & ctx, gpu::CommandEncoder & encoder, + PBRPassParams const & params); }; /// @param transform needs to transform from [-1, +1] to clip space @@ -250,14 +249,14 @@ struct RRectPass : Pass RRectPass() = default; - virtual void acquire(GpuContext &ctx, AssetMap &assets) override; + virtual void acquire(GpuContext & ctx, AssetMap & assets) override; - virtual void release(GpuContext &ctx, AssetMap &assets) override; + virtual void release(GpuContext & ctx, AssetMap & assets) override; virtual ~RRectPass() override = default; - void encode(GpuContext &ctx, gpu::CommandEncoder &encoder, - RRectPassParams const ¶ms); + void encode(GpuContext & ctx, gpu::CommandEncoder & encoder, + RRectPassParams const & params); }; } // namespace ash diff --git a/ashura/engine/rect_pack.h b/ashura/engine/rect_pack.h index f3e6b344..98113fa4 100644 --- a/ashura/engine/rect_pack.h +++ b/ashura/engine/rect_pack.h @@ -121,10 +121,10 @@ struct rect i32 was_packed = 0; }; -constexpr int rect_height_compare(void const *a, void const *b) +constexpr int rect_height_compare(void const * a, void const * b) { - rect const *p = (rect const *) a; - rect const *q = (rect const *) b; + rect const * p = (rect const *) a; + rect const * q = (rect const *) b; if (p->h > q->h) return -1; if (p->h < q->h) @@ -132,10 +132,10 @@ constexpr int rect_height_compare(void const *a, void const *b) return (p->w > q->w) ? -1 : (p->w < q->w); } -constexpr int rect_original_order(void const *a, void const *b) +constexpr int rect_original_order(void const * a, void const * b) { - rect const *p = (rect const *) a; - rect const *q = (rect const *) b; + rect const * p = (rect const *) a; + rect const * q = (rect const *) b; return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed); } @@ -146,8 +146,8 @@ constexpr int rect_original_order(void const *a, void const *b) struct Node { - i32 x = 0, y = 0; - Node *next = nullptr; + i32 x = 0, y = 0; + Node * next = nullptr; }; enum class Heuristic @@ -169,20 +169,20 @@ struct Context Mode init_mode = Mode::Default; Heuristic heuristic = Heuristic::BL_sortHeight; i32 num_nodes = 0; - Node *active_head = nullptr; - Node *free_head = nullptr; + Node * active_head = nullptr; + Node * free_head = nullptr; // we allocate two extra nodes so optimal // user-node-count is 'width' not 'width+2' - Node extra[2]; + Node extra[2]; }; // find minimum y position if it starts at x1 -inline i32 skyline_find_min_y(Context &c, Node *first, i32 x0, i32 width, - i32 *pwaste) +inline i32 skyline_find_min_y(Context & c, Node * first, i32 x0, i32 width, + i32 * pwaste) { - Node *node = first; - i32 x1 = x0 + width; - i32 min_y, visited_width, waste_area; + Node * node = first; + i32 x1 = x0 + width; + i32 min_y, visited_width, waste_area; (void) c; @@ -235,15 +235,15 @@ inline i32 skyline_find_min_y(Context &c, Node *first, i32 x0, i32 width, struct FindResult { - i32 x = 0, y = 0; - Node **prev_link = nullptr; + i32 x = 0, y = 0; + Node ** prev_link = nullptr; }; -inline FindResult skyline_find_best_pos(Context &ctx, i32 width, i32 height) +inline FindResult skyline_find_best_pos(Context & ctx, i32 width, i32 height) { i32 best_waste = (1 << 30), best_x, best_y = (1 << 30); FindResult find_result; - Node **prev, *node, *tail, **best = nullptr; + Node ** prev, *node, *tail, **best = nullptr; // align to multiple of ctx.align width = (width + ctx.align - 1); @@ -359,11 +359,11 @@ inline FindResult skyline_find_best_pos(Context &ctx, i32 width, i32 height) return find_result; } -inline FindResult skyline_pack_rectangle(Context &ctx, i32 width, i32 height) +inline FindResult skyline_pack_rectangle(Context & ctx, i32 width, i32 height) { // find best position according to heuristic FindResult res = skyline_find_best_pos(ctx, width, height); - Node *node, *cur; + Node * node, *cur; // bail if: // 1. it failed @@ -391,9 +391,9 @@ inline FindResult skyline_pack_rectangle(Context &ctx, i32 width, i32 height) if (cur->x < res.x) { // preserve the existing one, so start testing with the next one - Node *next = cur->next; - cur->next = node; - cur = next; + Node * next = cur->next; + cur->next = node; + cur = next; } else { @@ -404,7 +404,7 @@ inline FindResult skyline_pack_rectangle(Context &ctx, i32 width, i32 height) // that shouldn't be freed while (cur->next && cur->next->x <= res.x + width) { - Node *next = cur->next; + Node * next = cur->next; // move the current node to the free list cur->next = ctx.free_head; ctx.free_head = cur; @@ -471,7 +471,7 @@ inline FindResult skyline_pack_rectangle(Context &ctx, i32 width, i32 height) // algorithm may run out of temporary storage and be unable to pack some // rectangles. // -inline Context init(i32 width, i32 height, Node *nodes, i32 num_nodes, +inline Context init(i32 width, i32 height, Node * nodes, i32 num_nodes, bool allow_out_of_mem) { Context ctx; @@ -545,7 +545,7 @@ inline Context init(i32 width, i32 height, Node *nodes, i32 num_nodes, // // The function returns 1 if all of the rectangles were successfully // packed and 0 otherwise. -inline bool pack_rects(Context &ctx, rect *rects, i32 num_rects) +inline bool pack_rects(Context & ctx, rect * rects, i32 num_rects) { i32 all_rects_packed = 1; diff --git a/ashura/engine/render_text.h b/ashura/engine/render_text.h index 12cb9597..955ea0e6 100644 --- a/ashura/engine/render_text.h +++ b/ashura/engine/render_text.h @@ -53,7 +53,7 @@ struct RenderText /// @param count range of the number of codepoints to be patched /// @param style font style to be applied /// @param font font configuration to be applied - void style(TextStyle const &style, FontStyle const &font, u32 first = 0, + void style(TextStyle const & style, FontStyle const & font, u32 first = 0, u32 count = U32_MAX) { if (count == 0) @@ -183,7 +183,7 @@ struct RenderText inner.dirty = true; } - void highlight(TextHighlight const &highlight) + void highlight(TextHighlight const & highlight) { inner.highlights.push(highlight).unwrap(); } @@ -228,8 +228,8 @@ struct RenderText return inner.text; } - void set_text(Span utf32, TextStyle const &style, - FontStyle const &font) + void set_text(Span utf32, TextStyle const & style, + FontStyle const & font) { set_text(utf32); inner.style(style, font); @@ -243,8 +243,8 @@ struct RenderText flush_text(); } - void set_text(Span utf8, TextStyle const &style, - FontStyle const &font) + void set_text(Span utf8, TextStyle const & style, + FontStyle const & font) { inner.style(style, font); set_text(utf8); @@ -258,7 +258,7 @@ struct RenderText flush_text(); } - void style(TextStyle const &style, FontStyle const &font, u32 first = 0, + void style(TextStyle const & style, FontStyle const & font, u32 first = 0, u32 count = U32_MAX) { inner.style(style, font, first, count); @@ -293,7 +293,7 @@ struct RenderText layout_text(block(), max_width, inner.layout); } - void render(Canvas &canvas, CRect const ®ion, CRect const &clip, + void render(Canvas & canvas, CRect const & region, CRect const & clip, f32 zoom) const { (void) zoom; @@ -307,4 +307,4 @@ struct RenderText } }; -} // namespace ash \ No newline at end of file +} // namespace ash diff --git a/ashura/engine/renderer.cc b/ashura/engine/renderer.cc index 8ee74d5d..cf341b3b 100644 --- a/ashura/engine/renderer.cc +++ b/ashura/engine/renderer.cc @@ -7,11 +7,11 @@ namespace ash { -void Renderer::begin_frame(GpuContext &ctx, RenderTarget const &, - Canvas &canvas) +void Renderer::begin_frame(GpuContext & ctx, RenderTarget const &, + Canvas & canvas) { - gpu::CommandEncoder &enc = ctx.encoder(); - Resources &r = resources[ctx.ring_index()]; + gpu::CommandEncoder & enc = ctx.encoder(); + Resources & r = resources[ctx.ring_index()]; r.ngon_vertices.copy(ctx, span(canvas.ngon_vertices).as_u8()); r.ngon_indices.copy(ctx, span(canvas.ngon_indices).as_u8()); @@ -19,27 +19,27 @@ void Renderer::begin_frame(GpuContext &ctx, RenderTarget const &, r.rrect_params.copy(ctx, span(canvas.rrect_params).as_u8()); r.ngon_vertices.copy(ctx, span(canvas.ngon_vertices).as_u8()); - for (Dyn const &p : pipelines) + for (Dyn const & p : pipelines) { p->begin_frame(ctx, passes, enc); } } -void Renderer::end_frame(GpuContext &ctx, RenderTarget const &, Canvas &) +void Renderer::end_frame(GpuContext & ctx, RenderTarget const &, Canvas &) { - gpu::CommandEncoder &enc = ctx.encoder(); + gpu::CommandEncoder & enc = ctx.encoder(); - for (Dyn const &p : pipelines) + for (Dyn const & p : pipelines) { p->end_frame(ctx, passes, enc); } } -void Renderer::render_frame(GpuContext &ctx, RenderTarget const &rt, - Canvas &canvas) +void Renderer::render_frame(GpuContext & ctx, RenderTarget const & rt, + Canvas & canvas) { - Resources &r = resources[ctx.ring_index()]; - gpu::CommandEncoder &enc = ctx.encoder(); + Resources & r = resources[ctx.ring_index()]; + gpu::CommandEncoder & enc = ctx.encoder(); Canvas::RenderContext render_ctx{.canvas = canvas, .gpu = ctx, @@ -51,10 +51,10 @@ void Renderer::render_frame(GpuContext &ctx, RenderTarget const &rt, .ngon_vertices = r.ngon_vertices, .ngon_indices = r.ngon_indices}; - for (Canvas::Pass const &pass : canvas.passes) + for (Canvas::Pass const & pass : canvas.passes) { pass.task(render_ctx); } } -} // namespace ash \ No newline at end of file +} // namespace ash diff --git a/ashura/engine/renderer.h b/ashura/engine/renderer.h index 583cad06..1fbe8769 100644 --- a/ashura/engine/renderer.h +++ b/ashura/engine/renderer.h @@ -10,15 +10,15 @@ namespace ash struct PassContext { - BloomPass *bloom; - BlurPass *blur; - NgonPass *ngon; - PBRPass *pbr; - RRectPass *rrect; + BloomPass * bloom; + BlurPass * blur; + NgonPass * ngon; + PBRPass * pbr; + RRectPass * rrect; Vec> all; - explicit PassContext(BloomPass &bloom, BlurPass &blur, NgonPass &ngon, - PBRPass &pbr, RRectPass &rrect, Vec> all) : + explicit PassContext(BloomPass & bloom, BlurPass & blur, NgonPass & ngon, + PBRPass & pbr, RRectPass & rrect, Vec> all) : bloom{&bloom}, blur{&blur}, ngon{&ngon}, @@ -36,11 +36,11 @@ struct PassContext Dyn pbr = dyn(allocator, PBRPass{}).unwrap(); Dyn rrect = dyn(allocator, RRectPass{}).unwrap(); - BloomPass *pbloom = bloom.get(); - BlurPass *pblur = blur.get(); - NgonPass *pngon = ngon.get(); - PBRPass *ppbr = pbr.get(); - RRectPass *prrect = rrect.get(); + BloomPass * pbloom = bloom.get(); + BlurPass * pblur = blur.get(); + NgonPass * pngon = ngon.get(); + PBRPass * ppbr = pbr.get(); + RRectPass * prrect = rrect.get(); Vec> all{allocator}; @@ -53,23 +53,23 @@ struct PassContext return PassContext{*pbloom, *pblur, *pngon, *ppbr, *prrect, std::move(all)}; } - PassContext(PassContext const &) = delete; - PassContext(PassContext &&) = default; - PassContext &operator=(PassContext const &) = delete; - PassContext &operator=(PassContext &&) = default; - ~PassContext() = default; + PassContext(PassContext const &) = delete; + PassContext(PassContext &&) = default; + PassContext & operator=(PassContext const &) = delete; + PassContext & operator=(PassContext &&) = default; + ~PassContext() = default; - void acquire(GpuContext &ctx, AssetMap &assets) + void acquire(GpuContext & ctx, AssetMap & assets) { - for (auto const &p : all) + for (auto const & p : all) { p->acquire(ctx, assets); }; } - void release(GpuContext &ctx, AssetMap &assets) + void release(GpuContext & ctx, AssetMap & assets) { - for (auto const &p : all) + for (auto const & p : all) { p->release(ctx, assets); }; @@ -80,17 +80,17 @@ struct RenderPipeline { virtual Span id() = 0; - virtual void acquire(GpuContext &ctx, PassContext &passes, - AssetMap &assets) = 0; + virtual void acquire(GpuContext & ctx, PassContext & passes, + AssetMap & assets) = 0; - virtual void release(GpuContext &ctx, PassContext &passes, - AssetMap &assets) = 0; + virtual void release(GpuContext & ctx, PassContext & passes, + AssetMap & assets) = 0; - virtual void begin_frame(GpuContext &ctx, PassContext &passes, - gpu::CommandEncoder &enc) = 0; + virtual void begin_frame(GpuContext & ctx, PassContext & passes, + gpu::CommandEncoder & enc) = 0; - virtual void end_frame(GpuContext &ctx, PassContext &passes, - gpu::CommandEncoder &enc) = 0; + virtual void end_frame(GpuContext & ctx, PassContext & passes, + gpu::CommandEncoder & enc) = 0; virtual ~RenderPipeline() = default; }; @@ -131,7 +131,9 @@ struct Renderer Vec> pipelines; Renderer(AllocatorImpl allocator, PassContext passes) : - resources{}, passes{std::move(passes)}, pipelines{allocator} + resources{}, + passes{std::move(passes)}, + pipelines{allocator} { } @@ -141,17 +143,17 @@ struct Renderer return Renderer{allocator, std::move(passes)}; } - Renderer(Renderer const &) = delete; - Renderer(Renderer &&) = default; - Renderer &operator=(Renderer const &) = delete; - Renderer &operator=(Renderer &&) = default; - ~Renderer() = default; + Renderer(Renderer const &) = delete; + Renderer(Renderer &&) = default; + Renderer & operator=(Renderer const &) = delete; + Renderer & operator=(Renderer &&) = default; + ~Renderer() = default; - void acquire(GpuContext &ctx, AssetMap &assets) + void acquire(GpuContext & ctx, AssetMap & assets) { passes.acquire(ctx, assets); - for (Dyn const &p : pipelines) + for (Dyn const & p : pipelines) { p->acquire(ctx, passes, assets); } @@ -159,9 +161,9 @@ struct Renderer resources.resize_defaulted(ctx.buffering).unwrap(); } - void release(GpuContext &ctx, AssetMap &assets) + void release(GpuContext & ctx, AssetMap & assets) { - for (Resources &r : resources) + for (Resources & r : resources) { r.pbr_params.uninit(ctx); r.pbr_light_params.uninit(ctx); @@ -173,7 +175,7 @@ struct Renderer resources.reset(); - for (Dyn const &p : pipelines) + for (Dyn const & p : pipelines) { p->release(ctx, passes, assets); } @@ -181,24 +183,24 @@ struct Renderer passes.release(ctx, assets); } - void add_pass(GpuContext &ctx, Dyn pass, AssetMap &assets) + void add_pass(GpuContext & ctx, Dyn pass, AssetMap & assets) { pass->acquire(ctx, assets); passes.all.push(std::move(pass)).unwrap(); } - void add_pipeline(GpuContext &ctx, Dyn pipeline, - AssetMap &assets) + void add_pipeline(GpuContext & ctx, Dyn pipeline, + AssetMap & assets) { pipeline->acquire(ctx, passes, assets); pipelines.push(std::move(pipeline)).unwrap(); } - void begin_frame(GpuContext &ctx, RenderTarget const &rt, Canvas &canvas); + void begin_frame(GpuContext & ctx, RenderTarget const & rt, Canvas & canvas); - void end_frame(GpuContext &ctx, RenderTarget const &rt, Canvas &canvas); + void end_frame(GpuContext & ctx, RenderTarget const & rt, Canvas & canvas); - void render_frame(GpuContext &ctx, RenderTarget const &rt, Canvas &canvas); + void render_frame(GpuContext & ctx, RenderTarget const & rt, Canvas & canvas); }; } // namespace ash diff --git a/ashura/engine/shader.cc b/ashura/engine/shader.cc index d0b7a49c..4c687b86 100644 --- a/ashura/engine/shader.cc +++ b/ashura/engine/shader.cc @@ -17,12 +17,12 @@ constexpr TBuiltInResource SHADER_RESOURCE_LIMITS = { .maxTextureUnits = 32, .maxTextureCoords = 32, .maxVertexAttribs = 64, - .maxVertexUniformComponents = 4096, + .maxVertexUniformComponents = 4'096, .maxVaryingFloats = 64, .maxVertexTextureImageUnits = 32, .maxCombinedTextureImageUnits = 80, .maxTextureImageUnits = 32, - .maxFragmentUniformComponents = 4096, + .maxFragmentUniformComponents = 4'096, .maxDrawBuffers = 32, .maxVertexUniformVectors = 128, .maxVaryingVectors = 8, @@ -32,13 +32,13 @@ constexpr TBuiltInResource SHADER_RESOURCE_LIMITS = { .minProgramTexelOffset = -8, .maxProgramTexelOffset = 7, .maxClipDistances = 8, - .maxComputeWorkGroupCountX = 65535, - .maxComputeWorkGroupCountY = 65535, - .maxComputeWorkGroupCountZ = 65535, - .maxComputeWorkGroupSizeX = 1024, - .maxComputeWorkGroupSizeY = 1024, + .maxComputeWorkGroupCountX = 65'535, + .maxComputeWorkGroupCountY = 65'535, + .maxComputeWorkGroupCountZ = 65'535, + .maxComputeWorkGroupSizeX = 1'024, + .maxComputeWorkGroupSizeY = 1'024, .maxComputeWorkGroupSizeZ = 64, - .maxComputeUniformComponents = 1024, + .maxComputeUniformComponents = 1'024, .maxComputeTextureImageUnits = 16, .maxComputeImageUniforms = 8, .maxComputeAtomicCounters = 8, @@ -60,18 +60,18 @@ constexpr TBuiltInResource SHADER_RESOURCE_LIMITS = { .maxCombinedImageUniforms = 8, .maxGeometryTextureImageUnits = 16, .maxGeometryOutputVertices = 256, - .maxGeometryTotalOutputComponents = 1024, - .maxGeometryUniformComponents = 1024, + .maxGeometryTotalOutputComponents = 1'024, + .maxGeometryUniformComponents = 1'024, .maxGeometryVaryingComponents = 64, .maxTessControlInputComponents = 128, .maxTessControlOutputComponents = 128, .maxTessControlTextureImageUnits = 16, - .maxTessControlUniformComponents = 1024, - .maxTessControlTotalOutputComponents = 4096, + .maxTessControlUniformComponents = 1'024, + .maxTessControlTotalOutputComponents = 4'096, .maxTessEvaluationInputComponents = 128, .maxTessEvaluationOutputComponents = 128, .maxTessEvaluationTextureImageUnits = 16, - .maxTessEvaluationUniformComponents = 1024, + .maxTessEvaluationUniformComponents = 1'024, .maxTessPatchComponents = 120, .maxPatchVertices = 32, .maxTessGenLevel = 64, @@ -89,7 +89,7 @@ constexpr TBuiltInResource SHADER_RESOURCE_LIMITS = { .maxGeometryAtomicCounterBuffers = 0, .maxFragmentAtomicCounterBuffers = 1, .maxCombinedAtomicCounterBuffers = 1, - .maxAtomicCounterBufferSize = 16384, + .maxAtomicCounterBufferSize = 16'384, .maxTransformFeedbackBuffers = 4, .maxTransformFeedbackInterleavedComponents = 64, .maxCullDistances = 8, @@ -115,16 +115,17 @@ constexpr TBuiltInResource SHADER_RESOURCE_LIMITS = { .maxMeshViewCountEXT = 4, .maxDualSourceDrawBuffersEXT = 1, .limits = { - .nonInductiveForLoops = true, - .whileLoops = true, - .doWhileLoops = true, - .generalUniformIndexing = true, - .generalAttributeMatrixVectorIndexing = true, - .generalVaryingIndexing = true, - .generalSamplerIndexing = true, - .generalVariableIndexing = true, - .generalConstantMatrixVectorIndexing = true, - }}; + .nonInductiveForLoops = true, + .whileLoops = true, + .doWhileLoops = true, + .generalUniformIndexing = true, + .generalAttributeMatrixVectorIndexing = true, + .generalVaryingIndexing = true, + .generalSamplerIndexing = true, + .generalVariableIndexing = true, + .generalConstantMatrixVectorIndexing = true, + } +}; struct Includer : glslang::TShader::Includer { @@ -132,32 +133,32 @@ struct Includer : glslang::TShader::Includer { } - Includer(Includer const &) = delete; - Includer(Includer &&) = delete; - Includer &operator=(Includer const &) = delete; - Includer &operator=(Includer &&) = delete; + Includer(Includer const &) = delete; + Includer(Includer &&) = delete; + Includer & operator=(Includer const &) = delete; + Includer & operator=(Includer &&) = delete; - virtual IncludeResult *includeLocal(const char *header_name, - const char *includer_name, - size_t inclusion_depth) override + virtual IncludeResult * includeLocal(char const * header_name, + char const * includer_name, + size_t inclusion_depth) override { return include_path(header_name, includer_name, (int) inclusion_depth, true); } - virtual IncludeResult *includeSystem(const char *header_name, - const char *includer_name, - size_t inclusion_depth) override + virtual IncludeResult * includeSystem(char const * header_name, + char const * includer_name, + size_t inclusion_depth) override { return include_path(header_name, includer_name, (int) inclusion_depth, false); } - virtual void releaseInclude(IncludeResult *result) override + virtual void releaseInclude(IncludeResult * result) override { if (result != nullptr) { - auto *blob = reinterpret_cast *>(result->userData); + auto * blob = reinterpret_cast *>(result->userData); blob->reset(); default_allocator.ndealloc(blob, 1); result->~IncludeResult(); @@ -169,11 +170,11 @@ struct Includer : glslang::TShader::Includer { } - IncludeResult *include_path(const char *header_name, - const char *includer_name, int depth, - bool is_local) + IncludeResult * include_path(char const * header_name, + char const * includer_name, int depth, + bool is_local) { - IncludeResult *result = nullptr; + IncludeResult * result = nullptr; if (is_local) { result = include_local(header_name, includer_name, depth); @@ -192,8 +193,8 @@ struct Includer : glslang::TShader::Includer return include_local(header_name, includer_name, depth); } - IncludeResult *include_local(const char *header_name, - const char *includer_name, int depth) + IncludeResult * include_local(char const * header_name, + char const * includer_name, int depth) { (void) includer_name; (void) depth; @@ -210,7 +211,9 @@ struct Includer : glslang::TShader::Includer for (Span folder : local_directories) { - std::filesystem::path cnd{std::string_view{folder.data(), folder.size()}}; + std::filesystem::path cnd{ + std::string_view{folder.data(), folder.size()} + }; cnd /= header_name; if (std::filesystem::exists(cnd)) @@ -223,14 +226,16 @@ struct Includer : glslang::TShader::Includer return nullptr; } - IncludeResult *include_system(const char *header_name, - const char *includer_name, int depth) + IncludeResult * include_system(char const * header_name, + char const * includer_name, int depth) { (void) includer_name; (void) depth; for (Span folder : system_directories) { - std::filesystem::path cnd{std::string_view{folder.data(), folder.size()}}; + std::filesystem::path cnd{ + std::string_view{folder.data(), folder.size()} + }; cnd /= header_name; if (std::filesystem::exists(cnd)) @@ -242,9 +247,9 @@ struct Includer : glslang::TShader::Includer return nullptr; } - IncludeResult *include_file(char const *header_name, char const *path) + IncludeResult * include_file(char const * header_name, char const * path) { - Vec *blob; + Vec * blob; if (!default_allocator.nalloc(1, blob)) { return nullptr; @@ -263,7 +268,7 @@ struct Includer : glslang::TShader::Includer return nullptr; } - IncludeResult *result; + IncludeResult * result; if (!default_allocator.nalloc(1, result)) { return nullptr; @@ -281,7 +286,7 @@ struct Includer : glslang::TShader::Includer }; ShaderCompileError - compile_shader(Logger &logger, Vec &spirv, Span file, + compile_shader(Logger & logger, Vec & spirv, Span file, ShaderType type, Span preamble, Span entry_point, Span const> system_directories, @@ -319,7 +324,7 @@ ShaderCompileError UNREACHABLE(); } - char const *buff_p = (char *) buff.data(); + char const * buff_p = (char *) buff.data(); int buff_length = (int) buff.size(); glslang::TShader shader{language}; shader.setStringsWithLengths(&buff_p, &buff_length, 1); @@ -377,7 +382,7 @@ ShaderCompileError return ShaderCompileError::LinkFailed; } - glslang::TIntermediate *intermediate = program.getIntermediate(language); + glslang::TIntermediate * intermediate = program.getIntermediate(language); if (intermediate == nullptr) { return ShaderCompileError::LinkFailed; @@ -411,10 +416,10 @@ ShaderCompileError return ShaderCompileError::None; } -ShaderCompileError pack_shader(Vec, Vec>> &compiled, - Span id, - Span root_directory, - Span file, Span preamble) +ShaderCompileError + pack_shader(Vec, Vec>> & compiled, + Span id, Span root_directory, + Span file, Span preamble) { ShaderType type = ShaderType::Compute; @@ -460,11 +465,11 @@ ShaderCompileError pack_shader(Vec, Vec>> &compiled, } ShaderCompileError - pack_shaders(Vec, Vec>> &compiled, - Span entries, - Span root_directory) + pack_shaders(Vec, Vec>> & compiled, + Span entries, + Span root_directory) { - for (ShaderUnit const &entry : entries) + for (ShaderUnit const & entry : entries) { ShaderCompileError error = pack_shader(compiled, entry.id, root_directory, entry.file, entry.preamble); @@ -476,4 +481,4 @@ ShaderCompileError return ShaderCompileError::None; } -} // namespace ash \ No newline at end of file +} // namespace ash diff --git a/ashura/engine/shader.h b/ashura/engine/shader.h index b8c2b1ae..ca51b902 100644 --- a/ashura/engine/shader.h +++ b/ashura/engine/shader.h @@ -27,7 +27,7 @@ enum class ShaderCompileError : i32 }; ShaderCompileError - compile_shader(Logger &logger, Vec &spirv, Span file, + compile_shader(Logger & logger, Vec & spirv, Span file, ShaderType type, Span preamble, Span entry_point, Span const> system_directories, @@ -41,8 +41,8 @@ struct ShaderUnit }; ShaderCompileError - pack_shaders(Vec, Vec>> &compiled, - Span entries, - Span root_directory); + pack_shaders(Vec, Vec>> & compiled, + Span entries, + Span root_directory); } // namespace ash diff --git a/ashura/engine/text.cc b/ashura/engine/text.cc index 9cb43233..3b6d7506 100644 --- a/ashura/engine/text.cc +++ b/ashura/engine/text.cc @@ -20,12 +20,13 @@ namespace ash /// with invalid codepoints replaced before calling this. /// @param script OpenType (ISO15924) Script /// Tag. See: https://unicode.org/reports/tr24/#Relation_To_ISO15924 -static inline void shape(hb_font_t *font, hb_buffer_t *buffer, +static inline void shape(hb_font_t * font, hb_buffer_t * buffer, Span text, u32 first, u32 count, hb_script_t script, hb_direction_t direction, hb_language_t language, bool use_kerning, - bool use_ligatures, Span &infos, - Span &positions) + bool use_ligatures, + Span & infos, + Span & positions) { // tags are opentype feature tags hb_feature_t const shaping_features[] = { @@ -43,7 +44,8 @@ static inline void shape(hb_font_t *font, hb_buffer_t *buffer, {.tag = HB_TAG('c', 'l', 'i', 'g'), .value = use_ligatures, .start = HB_FEATURE_GLOBAL_START, - .end = HB_FEATURE_GLOBAL_END}}; + .end = HB_FEATURE_GLOBAL_END} + }; hb_buffer_reset(buffer); // invalid character replacement @@ -58,13 +60,13 @@ static inline void shape(hb_font_t *font, hb_buffer_t *buffer, first, (i32) count); hb_shape(font, buffer, shaping_features, (u32) size(shaping_features)); - u32 num_pos; - hb_glyph_position_t const *glyph_pos = + u32 num_pos; + hb_glyph_position_t const * glyph_pos = hb_buffer_get_glyph_positions(buffer, &num_pos); CHECK(!(glyph_pos == nullptr && num_pos > 0)); - u32 num_info; - hb_glyph_info_t const *glyph_info = + u32 num_info; + hb_glyph_info_t const * glyph_info = hb_buffer_get_glyph_infos(buffer, &num_info); CHECK(!(glyph_info == nullptr && num_info > 0)); @@ -114,7 +116,7 @@ static inline void segment_scripts(Span text, CHECK(locator != nullptr); SBScriptLocatorLoadCodepoints(locator, &codepoints); - SBScriptAgent const *agent = SBScriptLocatorGetAgent(locator); + SBScriptAgent const * agent = SBScriptLocatorGetAgent(locator); CHECK(agent != nullptr); while (SBScriptLocatorMoveNext(locator) == SBTrue) @@ -156,8 +158,8 @@ static inline void segment_levels(Span text, CHECK(paragraph != nullptr); CHECK(SBParagraphGetLength(paragraph) == length); - SBLevel const base_level = SBParagraphGetBaseLevel(paragraph); - SBLevel const *levels = SBParagraphGetLevelsPtr(paragraph); + SBLevel const base_level = SBParagraphGetBaseLevel(paragraph); + SBLevel const * levels = SBParagraphGetLevelsPtr(paragraph); CHECK(levels != nullptr); for (u32 i = 0; i < length; i++) { @@ -195,9 +197,9 @@ static inline void segment_breakpoints(Span text, } } -static inline void insert_run(TextLayout &l, FontStyle const &s, u32 first, +static inline void insert_run(TextLayout & l, FontStyle const & s, u32 first, u32 count, u16 style, - FontMetrics const &font_metrics, u8 base_level, + FontMetrics const & font_metrics, u8 base_level, u8 level, bool paragraph, bool breakable, Span infos, Span positions) @@ -211,32 +213,36 @@ static inline void insert_run(TextLayout &l, FontStyle const &s, u32 first, for (u32 i = 0; i < num_glyphs; i++) { - hb_glyph_info_t const &info = infos[i]; - hb_glyph_position_t const &pos = positions[i]; - GlyphShape shape{.glyph = info.codepoint, - .cluster = info.cluster, - .advance = pos.x_advance, - .offset = {pos.x_offset, -pos.y_offset}}; + hb_glyph_info_t const & info = infos[i]; + hb_glyph_position_t const & pos = positions[i]; + GlyphShape shape{ + .glyph = info.codepoint, + .cluster = info.cluster, + .advance = pos.x_advance, + .offset = {pos.x_offset, -pos.y_offset} + }; l.glyphs[first_glyph + i] = shape; advance += pos.x_advance; } l.runs - .push(TextRun{.first_codepoint = first, - .num_codepoints = count, - .style = style, - .font_height = s.font_height, - .line_height = max(s.line_height, 1.0F), - .first_glyph = first_glyph, - .num_glyphs = num_glyphs, - .metrics = TextRunMetrics{.advance = advance, - .ascent = font_metrics.ascent, - .descent = font_metrics.descent}, - .base_level = base_level, - .level = level, - .paragraph = paragraph, - .breakable = breakable}) + .push(TextRun{ + .first_codepoint = first, + .num_codepoints = count, + .style = style, + .font_height = s.font_height, + .line_height = max(s.line_height, 1.0F), + .first_glyph = first_glyph, + .num_glyphs = num_glyphs, + .metrics = TextRunMetrics{.advance = advance, + .ascent = font_metrics.ascent, + .descent = font_metrics.descent}, + .base_level = base_level, + .level = level, + .paragraph = paragraph, + .breakable = breakable + }) .unwrap(); } @@ -246,7 +252,7 @@ static inline void insert_run(TextLayout &l, FontStyle const &s, u32 first, static inline void reorder_line(Span runs) { u8 max_level = 0; - for (TextRun const &r : runs) + for (TextRun const & r : runs) { max_level = max(r.level, max_level); } @@ -278,7 +284,7 @@ static inline void reorder_line(Span runs) /// see: /// https://stackoverflow.com/questions/62374506/how-do-i-align-glyphs-along-the-baseline-with-freetype /// -void layout_text(TextBlock const &block, f32 max_width, TextLayout &layout) +void layout_text(TextBlock const & block, f32 max_width, TextLayout & layout) { layout.clear(); @@ -295,7 +301,7 @@ void layout_text(TextBlock const &block, f32 max_width, TextLayout &layout) layout.segments.resize_defaulted(block.text.size()).unwrap(); Span segments = layout.segments; - for (TextSegment &s : segments) + for (TextSegment & s : segments) { s = TextSegment{}; } @@ -335,7 +341,7 @@ void layout_text(TextBlock const &block, f32 max_width, TextLayout &layout) hb_language_get_default() : hb_language_from_string(block.language.data(), (i32) block.language.size()); - hb_buffer_t *buffer = hb_buffer_create(); + hb_buffer_t * buffer = hb_buffer_create(); CHECK(buffer != nullptr); defer buffer_{[&] { hb_buffer_destroy(buffer); }}; @@ -350,8 +356,8 @@ void layout_text(TextBlock const &block, f32 max_width, TextLayout &layout) for (u32 i = paragraph_begin; i < paragraph_end;) { - u32 const first = i++; - TextSegment const &first_segment = segments[first]; + u32 const first = i++; + TextSegment const & first_segment = segments[first]; while (i < paragraph_end && first_segment.style == segments[i].style && first_segment.script == segments[i].script && first_segment.level == segments[i].level && @@ -360,8 +366,8 @@ void layout_text(TextBlock const &block, f32 max_width, TextLayout &layout) i++; } - FontStyle const &s = block.fonts[first_segment.style]; - FontImpl const *f = (FontImpl const *) s.font; + FontStyle const & s = block.fonts[first_segment.style]; + FontImpl const * f = (FontImpl const *) s.font; Span infos = {}; Span positions = {}; shape(f->hb_font, buffer, block.text, first, i - first, @@ -391,10 +397,10 @@ void layout_text(TextBlock const &block, f32 max_width, TextLayout &layout) for (u32 i = 0; i < num_runs;) { - u32 const first = i++; - TextRun const &first_run = layout.runs[first]; - u8 const base_level = first_run.base_level; - bool const paragraph = first_run.paragraph; + u32 const first = i++; + TextRun const & first_run = layout.runs[first]; + u8 const base_level = first_run.base_level; + bool const paragraph = first_run.paragraph; f32 width = au_to_px(first_run.metrics.advance, first_run.font_height); f32 ascent = au_to_px(first_run.metrics.ascent, first_run.font_height); f32 descent = au_to_px(first_run.metrics.descent, first_run.font_height); @@ -407,8 +413,8 @@ void layout_text(TextBlock const &block, f32 max_width, TextLayout &layout) layout.runs[i].font_height) + width) > max_width)) { - TextRun const &r = layout.runs[i]; - TextRunMetrics const &m = r.metrics; + TextRun const & r = layout.runs[i]; + TextRunMetrics const & m = r.metrics; width += au_to_px(m.advance, r.font_height); ascent = max(ascent, au_to_px(m.ascent, r.font_height)); descent = max(descent, au_to_px(m.descent, r.font_height)); @@ -416,21 +422,23 @@ void layout_text(TextBlock const &block, f32 max_width, TextLayout &layout) i++; } - TextRun const &last_run = layout.runs[i - 1]; - u32 const first_codepoint = first_run.first_codepoint; - u32 const num_codepoints = + TextRun const & last_run = layout.runs[i - 1]; + u32 const first_codepoint = first_run.first_codepoint; + u32 const num_codepoints = (last_run.first_codepoint + last_run.num_codepoints) - first_codepoint; - Line line{.first_codepoint = first_codepoint, - .num_codepoints = num_codepoints, - .first_run = first, - .num_runs = (i - first), - .metrics = LineMetrics{.width = width, - .height = height, - .ascent = ascent, - .descent = descent, - .level = base_level}, - .paragraph = paragraph}; + Line line{ + .first_codepoint = first_codepoint, + .num_codepoints = num_codepoints, + .first_run = first, + .num_runs = (i - first), + .metrics = LineMetrics{.width = width, + .height = height, + .ascent = ascent, + .descent = descent, + .level = base_level}, + .paragraph = paragraph + }; layout.lines.push(line).unwrap(); @@ -444,7 +452,7 @@ void layout_text(TextBlock const &block, f32 max_width, TextLayout &layout) layout.extent = extent; } -TextHitResult hit_text(TextLayout const &layout, f32 style_align_width, +TextHitResult hit_text(TextLayout const & layout, f32 style_align_width, f32 style_alignment, Vec2 pos) { u32 const num_lines = layout.lines.size32(); @@ -471,7 +479,7 @@ TextHitResult hit_text(TextLayout const &layout, f32 style_align_width, l = min(l, num_lines - 1); - Line const &ln = layout.lines[l]; + Line const & ln = layout.lines[l]; TextDirection const direction = level_to_direction(ln.metrics.level); f32 const alignment = style_alignment * ((direction == TextDirection::LeftToRight) ? 1 : -1); @@ -480,8 +488,8 @@ TextHitResult hit_text(TextLayout const &layout, f32 style_align_width, for (u32 r = 0; r < ln.num_runs; r++) { - TextRun const &run = layout.runs[r]; - bool const intersects = + TextRun const & run = layout.runs[r]; + bool const intersects = (pos.x >= cursor && pos.x <= (cursor + au_to_px(run.metrics.advance, run.font_height))) || (r == ln.num_runs - 1); @@ -492,9 +500,9 @@ TextHitResult hit_text(TextLayout const &layout, f32 style_align_width, f32 glyph_cursor = cursor; for (u32 g = 0; g < run.num_glyphs; g++) { - GlyphShape const &glyph = layout.glyphs[run.first_glyph + g]; - f32 const advance = au_to_px(glyph.advance, run.font_height); - bool const intersects = + GlyphShape const & glyph = layout.glyphs[run.first_glyph + g]; + f32 const advance = au_to_px(glyph.advance, run.font_height); + bool const intersects = (pos.x >= glyph_cursor && pos.x <= (glyph_cursor + advance)) || (g == run.num_glyphs - 1); if (!intersects) diff --git a/ashura/engine/text.h b/ashura/engine/text.h index b38e6720..f2f6eb65 100644 --- a/ashura/engine/text.h +++ b/ashura/engine/text.h @@ -232,9 +232,9 @@ enum class TextScript : u8 /// @param line_height relative. multiplied by font_height struct FontStyle { - Font *font = nullptr; - f32 font_height = 20; - f32 line_height = 1.2F; + Font * font = nullptr; + f32 font_height = 20; + f32 line_height = 1.2F; }; /// @param shadow_scale relative. multiplied by font_height @@ -313,8 +313,8 @@ struct alignas(4) TextSegment u16 style = 0; TextScript script = TextScript::None; bool paragraph_begin : 1 = false; - bool paragraph_end : 1 = false; - bool breakable : 1 = false; + bool paragraph_end : 1 = false; + bool breakable : 1 = false; u8 base_level = 0; u8 level = 0; }; @@ -420,13 +420,13 @@ constexpr TextDirection level_to_direction(u8 level) TextDirection::RightToLeft; } -void layout_text(TextBlock const &block, f32 max_width, TextLayout &layout); +void layout_text(TextBlock const & block, f32 max_width, TextLayout & layout); /// @brief given a position in the laid-out text return the location of the /// grapheme the cursor points to. returns the last column if the position /// overlaps with the row and returns the last line if no overlap was found. /// @param pos position in laid-out text to return from. -TextHitResult hit_text(TextLayout const &layout, f32 align_width, f32 alignment, - Vec2 pos); +TextHitResult hit_text(TextLayout const & layout, f32 align_width, + f32 alignment, Vec2 pos); -} // namespace ash \ No newline at end of file +} // namespace ash diff --git a/ashura/engine/text_compositor.cc b/ashura/engine/text_compositor.cc index 63cf4f0f..a5aafad7 100644 --- a/ashura/engine/text_compositor.cc +++ b/ashura/engine/text_compositor.cc @@ -8,7 +8,7 @@ namespace ash { -static inline u32 goto_line(TextLayout const &layout, u32 alignment, u32 line) +static inline u32 goto_line(TextLayout const & layout, u32 alignment, u32 line) { if (layout.lines.is_empty()) { @@ -17,7 +17,7 @@ static inline u32 goto_line(TextLayout const &layout, u32 alignment, u32 line) line = min(line, layout.lines.size32() - 1); - Line const &ln = layout.lines[line]; + Line const & ln = layout.lines[line]; if (alignment > ln.num_codepoints) { @@ -71,7 +71,9 @@ void TextCompositor::Inner::append_record(bool is_insert, u32 text_pos, current_record++; latest_record = current_record; records[latest_record] = TextEditRecord{ - .slice = Slice32{text_pos, segment.size32()}, .is_insert = is_insert}; + .slice = Slice32{text_pos, segment.size32()}, + .is_insert = is_insert + }; buffer_pos += segment.size32(); } @@ -82,7 +84,7 @@ void TextCompositor::Inner::undo(Insert insert, Erase erase) return; } // undo changes of current record - TextEditRecord &record = records[current_record]; + TextEditRecord & record = records[current_record]; buffer_pos -= record.slice.span; if (record.is_insert) { @@ -108,7 +110,7 @@ void TextCompositor::Inner::redo(Insert insert, Erase erase) } current_record++; // apply changes of next record - TextEditRecord &record = records[current_record]; + TextEditRecord & record = records[current_record]; if (record.is_insert) { insert(record.slice.offset, @@ -212,7 +214,7 @@ struct LinePosition u32 alignment = 0; }; -static inline LinePosition line_translate(TextLayout const &layout, u32 cursor, +static inline LinePosition line_translate(TextLayout const & layout, u32 cursor, i64 dy) { if (layout.lines.is_empty()) @@ -222,7 +224,7 @@ static inline LinePosition line_translate(TextLayout const &layout, u32 cursor, for (u32 ln = 0; ln < layout.lines.size32(); ln++) { - Line const &line = layout.lines[ln]; + Line const & line = layout.lines[ln]; if (line.first_codepoint <= cursor && (line.first_codepoint + line.num_codepoints) > cursor) { @@ -236,12 +238,10 @@ static inline LinePosition line_translate(TextLayout const &layout, u32 cursor, return LinePosition{}; } -void TextCompositor::Inner::command(Span text, - TextLayout const &layout, f32 align_width, - f32 alignment, TextCommand cmd, - Insert insert, Erase erase, - Span input, ClipBoard &clipboard, - u32 lines_per_page, Vec2 pos) +void TextCompositor::Inner::command( + Span text, TextLayout const & layout, f32 align_width, + f32 alignment, TextCommand cmd, Insert insert, Erase erase, + Span input, ClipBoard & clipboard, u32 lines_per_page, Vec2 pos) { switch (cmd) { diff --git a/ashura/engine/text_compositor.h b/ashura/engine/text_compositor.h index 2504dfe9..447b78d2 100644 --- a/ashura/engine/text_compositor.h +++ b/ashura/engine/text_compositor.h @@ -202,15 +202,15 @@ struct TextCompositor void delete_selection(Span text, Erase erase); - void command(Span text, TextLayout const &layout, + void command(Span text, TextLayout const & layout, f32 align_width, f32 alignment, TextCommand cmd, Insert insert, - Erase erase, Span input, ClipBoard &clipboard, + Erase erase, Span input, ClipBoard & clipboard, u32 lines_per_page, Vec2 pos); }; Inner inner; - TextCompositor(u32 num_buffer_codepoints = 16_KB, u32 num_records = 1024) : + TextCompositor(u32 num_buffer_codepoints = 16_KB, u32 num_records = 1'024) : inner{num_buffer_codepoints, num_records} { } @@ -252,9 +252,9 @@ struct TextCompositor /// @param text original text /// @param input text from IME to insert - void command(Span text, TextLayout const &layout, f32 align_width, + void command(Span text, TextLayout const & layout, f32 align_width, f32 alignment, TextCommand cmd, Insert insert, Erase erase, - Span input, ClipBoard &clipboard, u32 lines_per_page, + Span input, ClipBoard & clipboard, u32 lines_per_page, Vec2 pos) { inner.command(text, layout, align_width, alignment, cmd, insert, erase, diff --git a/ashura/engine/view.cc b/ashura/engine/view.cc index 8ac631f3..bf664c96 100644 --- a/ashura/engine/view.cc +++ b/ashura/engine/view.cc @@ -4,4 +4,4 @@ namespace ash { -} \ No newline at end of file +} diff --git a/ashura/engine/view.h b/ashura/engine/view.h index 2addb3b6..2c278ac1 100644 --- a/ashura/engine/view.h +++ b/ashura/engine/view.h @@ -45,12 +45,12 @@ struct Frame Size width{}; Size height{}; - constexpr Frame() = default; - constexpr Frame(Frame const &) = default; - constexpr Frame(Frame &&) = default; - constexpr Frame &operator=(Frame const &) = default; - constexpr Frame &operator=(Frame &&) = default; - constexpr ~Frame() = default; + constexpr Frame() = default; + constexpr Frame(Frame const &) = default; + constexpr Frame(Frame &&) = default; + constexpr Frame & operator=(Frame const &) = default; + constexpr Frame & operator=(Frame &&) = default; + constexpr ~Frame() = default; constexpr Frame(Size width, Size height) : width{width}, height{height} { @@ -128,7 +128,10 @@ struct CornerRadii } constexpr CornerRadii(Size tl, Size tr, Size bl, Size br) : - tl{tl}, tr{tr}, bl{bl}, br{br} + tl{tl}, + tr{tr}, + bl{bl}, + br{br} { } @@ -137,7 +140,9 @@ struct CornerRadii } constexpr CornerRadii(f32 s, bool constrained) : - CornerRadii{Size{.offset = s, .rmax = constrained ? 1 : F32_INF}} + CornerRadii{ + Size{.offset = s, .rmax = constrained ? 1 : F32_INF} + } { } @@ -177,26 +182,26 @@ enum class MainAlign : u8 /// @param text_input the view has received composition text struct ViewEvents { - bool mounted : 1 = false; - bool view_hit : 1 = false; - bool mouse_in : 1 = false; - bool mouse_out : 1 = false; - bool mouse_down : 1 = false; - bool mouse_up : 1 = false; - bool mouse_moved : 1 = false; + bool mounted : 1 = false; + bool view_hit : 1 = false; + bool mouse_in : 1 = false; + bool mouse_out : 1 = false; + bool mouse_down : 1 = false; + bool mouse_up : 1 = false; + bool mouse_moved : 1 = false; bool mouse_scroll : 1 = false; - bool drag_start : 1 = false; - bool dragging : 1 = false; - bool drag_end : 1 = false; - bool drag_in : 1 = false; - bool drag_out : 1 = false; - bool drag_over : 1 = false; - bool drop : 1 = false; - bool focus_in : 1 = false; - bool focus_out : 1 = false; - bool key_down : 1 = false; - bool key_up : 1 = false; - bool text_input : 1 = false; + bool drag_start : 1 = false; + bool dragging : 1 = false; + bool drag_end : 1 = false; + bool drag_in : 1 = false; + bool drag_out : 1 = false; + bool drag_over : 1 = false; + bool drop : 1 = false; + bool focus_in : 1 = false; + bool focus_out : 1 = false; + bool key_down : 1 = false; + bool key_up : 1 = false; + bool text_input : 1 = false; }; /// @brief Global View Context, Properties of the context all the views for @@ -220,14 +225,14 @@ struct ViewContext { struct Mouse { - bool in : 1 = false; - bool out : 1 = false; - bool focused : 1 = false; - bool moved : 1 = false; + bool in : 1 = false; + bool out : 1 = false; + bool focused : 1 = false; + bool moved : 1 = false; bool wheel_scrolled : 1 = false; - MouseButtons downs : 8 = MouseButtons::None; - MouseButtons ups : 8 = MouseButtons::None; - MouseButtons states : 8 = MouseButtons::None; + MouseButtons downs : 8 = MouseButtons::None; + MouseButtons ups : 8 = MouseButtons::None; + MouseButtons states : 8 = MouseButtons::None; u32 num_clicks = 0; Vec2 position = {}; Vec2 translation = {}; @@ -237,7 +242,7 @@ struct ViewContext struct KeyBoard { bool down : 1 = false; - bool up : 1 = false; + bool up : 1 = false; Bits downs = {}; Bits ups = {}; Bits states = {}; @@ -246,8 +251,8 @@ struct ViewContext Bits scan_states = {}; }; - void *app = nullptr; - ClipBoard *clipboard = nullptr; + void * app = nullptr; + ClipBoard * clipboard = nullptr; time_point timestamp = {}; nanoseconds timedelta = {}; SystemTheme theme = SystemTheme::None; @@ -258,15 +263,17 @@ struct ViewContext Span text_input = {}; Vec2 viewport_extent = {}; - constexpr ViewContext(void *app, ClipBoard &clipboard) : - app{app}, clipboard{&clipboard} + constexpr ViewContext(void * app, ClipBoard & clipboard) : + app{app}, + clipboard{&clipboard} { } - constexpr ViewContext(ViewContext const &) = delete; - constexpr ViewContext(ViewContext &&) = default; - constexpr ViewContext &operator=(ViewContext const &) = delete; - constexpr ViewContext &operator=(ViewContext &&) = default; - constexpr ~ViewContext() = default; + + constexpr ViewContext(ViewContext const &) = delete; + constexpr ViewContext(ViewContext &&) = default; + constexpr ViewContext & operator=(ViewContext const &) = delete; + constexpr ViewContext & operator=(ViewContext &&) = default; + constexpr ~ViewContext() = default; constexpr bool key_down(KeyCode key) const { @@ -348,18 +355,18 @@ constexpr Mat3Affine scroll_transform(Vec2 viewport_extent, Vec2 view_extent, struct ViewState { i32 tab = I32_MIN; - bool hidden : 1 = false; - bool pointable : 1 = false; - bool clickable : 1 = false; + bool hidden : 1 = false; + bool pointable : 1 = false; + bool clickable : 1 = false; bool scrollable : 1 = false; - bool draggable : 1 = false; - bool droppable : 1 = false; - bool focusable : 1 = false; + bool draggable : 1 = false; + bool droppable : 1 = false; + bool focusable : 1 = false; bool text_input : 1 = false; - bool tab_input : 1 = false; - bool esc_input : 1 = false; + bool tab_input : 1 = false; + bool esc_input : 1 = false; bool grab_focus : 1 = false; - bool viewport : 1 = false; + bool viewport : 1 = false; }; struct CoreViewTheme @@ -392,8 +399,10 @@ struct CoreViewTheme }; constexpr CoreViewTheme DEFAULT_THEME = { - .background = Vec4U8{0x19, 0x19, 0x19, 0xFF}.norm(), - .surface = Vec4U8{0x33, 0x33, 0x33, 0xFF}.norm(), + .background = Vec4U8{0x19, 0x19, 0x19, 0xFF} + .norm(), + .surface = Vec4U8{0x33, 0x33, 0x33, 0xFF} + .norm(), .primary = mdc::DEEP_ORANGE_600.norm(), .primary_variant = mdc::DEEP_ORANGE_400.norm(), .secondary = mdc::PURPLE_600.norm(), @@ -401,8 +410,10 @@ constexpr CoreViewTheme DEFAULT_THEME = { .error = mdc::RED_500.norm(), .warning = mdc::YELLOW_800.norm(), .success = mdc::GREEN_700.norm(), - .active = Vec4U8{0x70, 0x70, 0x70, 0xFF}.norm(), - .inactive = Vec4U8{0x47, 0x47, 0x47, 0xFF}.norm(), + .active = Vec4U8{0x70, 0x70, 0x70, 0xFF} + .norm(), + .inactive = Vec4U8{0x47, 0x47, 0x47, 0xFF} + .norm(), .on_background = mdc::WHITE.norm(), .on_surface = mdc::WHITE.norm(), .on_primary = mdc::WHITE.norm(), @@ -415,7 +426,8 @@ constexpr CoreViewTheme DEFAULT_THEME = { .h2_font_height = 27, .h3_font_height = 22, .line_height = 1.2F, - .focus_thickness = 1}; + .focus_thickness = 1 +}; /// @param extent extent of the view within the parent. if it is a viewport, /// this is the visible extent of the viewport within the parent viewport. @@ -456,12 +468,12 @@ struct View f32 zoom = 1; } inner = {}; - constexpr View() = default; - constexpr View(View const &) = delete; - constexpr View(View &&) = delete; - constexpr View &operator=(View const &) = delete; - constexpr View &operator=(View &&) = delete; - constexpr virtual ~View() = default; + constexpr View() = default; + constexpr View(View const &) = delete; + constexpr View(View &&) = delete; + constexpr View & operator=(View const &) = delete; + constexpr View & operator=(View &&) = delete; + constexpr virtual ~View() = default; /// @returns the ID currently allocated to the view or U64_MAX constexpr u64 id() const @@ -475,9 +487,9 @@ struct View /// handle it. i.e. using the multi-tasking or asset-loading systems. /// @param region canvas-space region the view is on /// @param build callback to be called to insert subviews. - constexpr virtual ViewState tick(ViewContext const &ctx, CRect const ®ion, - f32 zoom, ViewEvents events, - Fn build) + constexpr virtual ViewState tick(ViewContext const & ctx, + CRect const & region, f32 zoom, + ViewEvents events, Fn build) { (void) ctx; (void) region; @@ -537,8 +549,8 @@ struct View /// @param zoom zoom scale of the view /// @param clip canvas-space clip of the view, applied by viewports. /// @param canvas canvas to render view into - constexpr virtual void render(Canvas &canvas, CRect const ®ion, f32 zoom, - CRect const &clip) + constexpr virtual void render(Canvas & canvas, CRect const & region, f32 zoom, + CRect const & clip) { (void) canvas; (void) region; @@ -550,7 +562,7 @@ struct View /// @param region canvas-space region of the view /// @param position canvas-space position of the pointer /// @return true if in hit region - constexpr virtual bool hit(CRect const ®ion, f32 zoom, Vec2 position) + constexpr virtual bool hit(CRect const & region, f32 zoom, Vec2 position) { (void) region; (void) zoom; @@ -561,7 +573,7 @@ struct View /// @brief Select cursor type given a pointed region of the view. /// @param region canvas-space region of the view /// @param position canvas-space position of the pointer - constexpr virtual Cursor cursor(CRect const ®ion, f32 zoom, Vec2 position) + constexpr virtual Cursor cursor(CRect const & region, f32 zoom, Vec2 position) { (void) region; (void) zoom; @@ -572,7 +584,7 @@ struct View /// @brief Called when the viewport is needed to zoom itself, scaling its /// inner extent /// @param zoom zoom to apply to the inner extent - constexpr virtual void zoom(Mat3Affine const &transform) + constexpr virtual void zoom(Mat3Affine const & transform) { (void) transform; } diff --git a/ashura/engine/view_system.h b/ashura/engine/view_system.h index af6364f7..904b68ec 100644 --- a/ashura/engine/view_system.h +++ b/ashura/engine/view_system.h @@ -44,18 +44,18 @@ struct ViewSystemState u64 drag_source_view = 0; u64 drag_target_view = 0; FocusInfo focused = {}; - bool focusing : 1 = false; - Cursor cursor : 5 = Cursor::Default; - bool mouse_down : 1 = false; - bool mouse_up : 1 = false; - bool mouse_moved : 1 = false; - bool mouse_scrolled : 1 = false; + bool focusing : 1 = false; + Cursor cursor : 5 = Cursor::Default; + bool mouse_down : 1 = false; + bool mouse_up : 1 = false; + bool mouse_moved : 1 = false; + bool mouse_scrolled : 1 = false; bool mouse_drag_start : 1 = false; - bool mouse_drag_end : 1 = false; - bool mouse_dragging : 1 = false; - bool mouse_drag_drop : 1 = false; - bool keyboard_down : 1 = false; - bool keyboard_up : 1 = false; + bool mouse_drag_end : 1 = false; + bool mouse_dragging : 1 = false; + bool mouse_drag_drop : 1 = false; + bool keyboard_down : 1 = false; + bool keyboard_up : 1 = false; }; enum class FocusAction : u8 @@ -133,11 +133,11 @@ struct ViewSystem { } - ViewSystem(ViewSystem const &) = delete; - ViewSystem(ViewSystem &&) = default; - ViewSystem &operator=(ViewSystem const &) = delete; - ViewSystem &operator=(ViewSystem &&) = default; - ~ViewSystem() = default; + ViewSystem(ViewSystem const &) = delete; + ViewSystem(ViewSystem &&) = default; + ViewSystem & operator=(ViewSystem const &) = delete; + ViewSystem & operator=(ViewSystem &&) = default; + ~ViewSystem() = default; void clear() { @@ -173,7 +173,7 @@ struct ViewSystem focus_ordering.clear(); } - ViewEvents process_events(View &view) + ViewEvents process_events(View & view) { ViewEvents events; @@ -186,8 +186,8 @@ struct ViewSystem events.view_hit = (view.inner.last_rendered_frame + 1) == frame; - ViewSystemState const &s0 = state[0]; - ViewSystemState const &s1 = state[1]; + ViewSystemState const & s0 = state[0]; + ViewSystemState const & s1 = state[1]; if (s1.mouse_pointed_view == view.id()) [[unlikely]] { @@ -240,7 +240,7 @@ struct ViewSystem return events; } - void push_view(View &view, u32 depth, u32 breadth, u32 parent) + void push_view(View & view, u32 depth, u32 breadth, u32 parent) { views.push(&view).unwrap(); nodes @@ -265,13 +265,13 @@ struct ViewSystem is_viewport.extend_uninit(1).unwrap(); } - void build_children(ViewContext const &ctx, View &view, u32 idx, u32 depth, - i32 &tab_index, u32 viewport) + void build_children(ViewContext const & ctx, View & view, u32 idx, u32 depth, + i32 & tab_index, u32 viewport) { u32 const first_child = views.size32(); u32 num_children = 0; - auto builder = [&](View &child) { + auto builder = [&](View & child) { push_view(child, depth + 1, num_children++, idx); }; @@ -313,7 +313,7 @@ struct ViewSystem } } - void build(ViewContext const &ctx, View &root) + void build(ViewContext const & ctx, View & root) { push_view(root, 0, 0, U32_MAX); i32 tab_index = 0; @@ -347,7 +347,7 @@ struct ViewSystem extents[0] = viewport_extent; for (u32 i = 0; i < n; i++) { - ViewNode const &node = nodes[i]; + ViewNode const & node = nodes[i]; views[i]->size(extents[i], span(extents).slice(node.first_child, node.num_children)); } @@ -359,8 +359,8 @@ struct ViewSystem for (u32 i = n; i != 0;) { i--; - ViewNode const &node = nodes[i]; - ViewLayout layout = views[i]->fit( + ViewNode const & node = nodes[i]; + ViewLayout layout = views[i]->fit( extents[i], span(extents).slice(node.first_child, node.num_children), span(centers).slice(node.first_child, node.num_children)); extents[i] = layout.extent; @@ -379,12 +379,12 @@ struct ViewSystem for (u32 i = 0; i < n; i++) { - ViewNode const &node = nodes[i]; + ViewNode const & node = nodes[i]; // parent-space to local viewport-space transformation matrix - Mat3Affine const &viewport_transform = viewport_transforms[i]; + Mat3Affine const & viewport_transform = viewport_transforms[i]; // accumulated transform of all ancestors, determines position until this // parent - Mat3Affine const &ancestor_transform = transforms[i]; + Mat3Affine const & ancestor_transform = transforms[i]; for (u32 c = node.first_child; c < (node.first_child + node.num_children); c++) { @@ -402,8 +402,8 @@ struct ViewSystem for (u32 i = 0; i < n; i++) { - Mat3Affine const &transform = transforms[i]; - f32 const zoom = transform[0][0]; + Mat3Affine const & transform = transforms[i]; + f32 const zoom = transform[0][0]; centers[i] = ash::transform(transform, Vec2{0, 0}) + viewport_extent * 0.5F; extents[i] = extents[i] * zoom; @@ -468,8 +468,8 @@ struct ViewSystem for (u32 i = 0; i < n; i++) { - ViewNode const &node = nodes[i]; - z_indices[i] = views[i]->z_index( + ViewNode const & node = nodes[i]; + z_indices[i] = views[i]->z_index( z_indices[i], span(z_indices).slice(node.first_child, node.num_children)); } @@ -477,7 +477,7 @@ struct ViewSystem stacking_contexts[0] = 0; for (u32 i = 0; i < n; i++) { - ViewNode const &node = nodes[i]; + ViewNode const & node = nodes[i]; if (node.parent != U32_MAX) { stacking_contexts[i] = views[i]->stack(stacking_contexts[node.parent]); @@ -512,7 +512,7 @@ struct ViewSystem { for (u32 i = 0; i < views.size32(); i++) { - ViewNode const &node = nodes[i]; + ViewNode const & node = nodes[i]; if (is_hidden[i]) { @@ -525,9 +525,9 @@ struct ViewSystem } else { - CRect region{.center = centers[i], .extent = extents[i]}; - CRect const &clip = clips[i]; - bool const hidden = + CRect region{.center = centers[i], .extent = extents[i]}; + CRect const & clip = clips[i]; + bool const hidden = !overlaps(region, clip) || !overlaps(region, CRect::from_offset({0, 0}, viewport_extent)) || !region.is_visible() || !clip.is_visible(); @@ -537,13 +537,13 @@ struct ViewSystem } } - void render(Canvas &canvas) + void render(Canvas & canvas) { for (u32 i : z_ordering) { if (!is_hidden.get(i)) [[unlikely]] { - View &view = *views[i]; + View & view = *views[i]; canvas.clip(clips[i]); view.render(canvas, view.inner.region, transforms[i][0][0], clips[i]); view.inner.last_rendered_frame = frame; @@ -564,14 +564,14 @@ struct ViewSystem // scroll into them. } - void events(ViewContext const &ctx) + void events(ViewContext const & ctx) { - state[0] = state[1]; - state[1] = {}; - ViewSystemState &s0 = state[0]; - ViewSystemState &s1 = state[1]; - u32 const n = views.size32(); - FocusInfo focused = s0.focused; + state[0] = state[1]; + state[1] = {}; + ViewSystemState & s0 = state[0]; + ViewSystemState & s1 = state[1]; + u32 const n = views.size32(); + FocusInfo focused = s0.focused; Cursor cursor = ctx.mouse.focused ? Cursor::Default : Cursor::None; bool focusing = s0.focusing; @@ -588,7 +588,7 @@ struct ViewSystem u32 i = z_ordering[z_i]; if (!is_hidden[i]) { - View &view = *views[i]; + View & view = *views[i]; if ((is_clickable[i] || is_draggable[i]) && view.hit(view.inner.region, transforms[i][0][0], ctx.mouse.position)) [[unlikely]] @@ -629,7 +629,7 @@ struct ViewSystem u32 i = z_ordering[z_i]; if (!is_hidden[i]) { - View &view = *views[i]; + View & view = *views[i]; if (is_clickable[i] && view.hit(view.inner.region, transforms[i][0][0], ctx.mouse.position)) [[unlikely]] @@ -661,7 +661,7 @@ struct ViewSystem u32 i = z_ordering[z_i]; if (!is_hidden[i]) { - View &view = *views[i]; + View & view = *views[i]; if (is_droppable[i] && view.hit(view.inner.region, transforms[i][0][0], ctx.mouse.position)) [[unlikely]] @@ -693,7 +693,7 @@ struct ViewSystem u32 i = z_ordering[z_i]; if (!is_hidden[i]) { - View &view = *views[i]; + View & view = *views[i]; if (is_droppable[i] && view.hit(view.inner.region, transforms[i][0][0], ctx.mouse.position)) [[unlikely]] @@ -721,7 +721,7 @@ struct ViewSystem u32 i = z_ordering[z_i]; if (!is_hidden[i]) { - View &view = *views[i]; + View & view = *views[i]; if (is_scrollable[i] && view.hit(view.inner.region, transforms[i][0][0], ctx.mouse.position)) [[unlikely]] @@ -744,7 +744,7 @@ struct ViewSystem u32 i = z_ordering[z_i]; if (!is_hidden[i]) { - View &view = *views[i]; + View & view = *views[i]; if (is_pointable[i] && view.hit(view.inner.region, transforms[i][0][0], ctx.mouse.position)) [[unlikely]] @@ -869,7 +869,7 @@ struct ViewSystem return state[1].focused.text_input; } - void tick(ViewContext const &ctx, View &root, Canvas &canvas) + void tick(ViewContext const & ctx, View & root, Canvas & canvas) { clear(); build(ctx, root); @@ -898,4 +898,4 @@ struct ViewSystem } }; -} // namespace ash \ No newline at end of file +} // namespace ash diff --git a/ashura/engine/views.cc b/ashura/engine/views.cc index 4a43e2a8..41cceaee 100644 --- a/ashura/engine/views.cc +++ b/ashura/engine/views.cc @@ -5,7 +5,7 @@ namespace ash { -void ScalarDragBox::scalar_parse(Span text, ScalarState &styling) +void ScalarDragBox::scalar_parse(Span text, ScalarState & styling) { if (text.is_empty()) { @@ -42,4 +42,4 @@ void ScalarDragBox::scalar_parse(Span text, ScalarState &styling) } } -} // namespace ash \ No newline at end of file +} // namespace ash diff --git a/ashura/engine/views.h b/ashura/engine/views.h index 0618fe18..1b21ef4d 100644 --- a/ashura/engine/views.h +++ b/ashura/engine/views.h @@ -1,4 +1,3 @@ - /// SPDX-License-Identifier: MIT #pragma once @@ -25,7 +24,7 @@ struct FocusState bool out = false; bool focused = false; - void tick(ViewEvents const &events) + void tick(ViewEvents const & events) { in = events.focus_in; out = events.focus_out; @@ -51,7 +50,7 @@ struct PressState bool held = false; FocusState focus = {}; - void tick(ViewContext const &ctx, ViewEvents const &events) + void tick(ViewContext const & ctx, ViewEvents const & events) { focus.tick(events); @@ -102,7 +101,7 @@ struct DragState bool end = false; FocusState focus = {}; - void tick(ViewEvents const &events) + void tick(ViewEvents const & events) { focus.tick(events); in = events.mouse_in; @@ -150,49 +149,49 @@ struct FlexView : View Vec items{default_allocator}; } inner; - FlexView &axis(Axis a) + FlexView & axis(Axis a) { styling.axis = a; return *this; } - FlexView &wrap(bool w) + FlexView & wrap(bool w) { styling.wrap = w; return *this; } - FlexView &main_align(MainAlign align) + FlexView & main_align(MainAlign align) { styling.main_align = align; return *this; } - FlexView &cross_align(f32 align) + FlexView & cross_align(f32 align) { styling.cross_align = align; return *this; } - FlexView &frame(f32 width, f32 height, bool constrain = true) + FlexView & frame(f32 width, f32 height, bool constrain = true) { styling.frame = Frame{width, height, constrain}; return *this; } - FlexView &frame(Frame f) + FlexView & frame(Frame f) { styling.frame = f; return *this; } - FlexView &items(std::initializer_list list) + FlexView & items(std::initializer_list list) { inner.items.extend_copy(span(list)).unwrap(); return *this; } - FlexView &items(Span list) + FlexView & items(Span list) { inner.items.extend_copy(list).unwrap(); return *this; @@ -201,7 +200,7 @@ struct FlexView : View virtual ViewState tick(ViewContext const &, CRect const &, f32, ViewEvents, Fn build) override { - for (View *item : inner.items) + for (View * item : inner.items) { build(*item); } @@ -331,7 +330,7 @@ struct FlexView : View } // convert from cursor space [0, w] to parent space [-0.5w, 0.5w] - for (Vec2 ¢er : centers) + for (Vec2 & center : centers) { center -= span * 0.5F; } @@ -354,43 +353,43 @@ struct StackView : View Vec items{default_allocator}; } inner; - StackView &reverse(bool r) + StackView & reverse(bool r) { styling.reverse = r; return *this; } - StackView &align(f32 x, f32 y) + StackView & align(f32 x, f32 y) { styling.alignment = Vec2{x, y}; return *this; } - StackView &align(Vec2 a) + StackView & align(Vec2 a) { styling.alignment = a; return *this; } - StackView &frame(f32 width, f32 height, bool constrain = true) + StackView & frame(f32 width, f32 height, bool constrain = true) { styling.frame = Frame{width, height, constrain}; return *this; } - StackView &frame(Frame f) + StackView & frame(Frame f) { styling.frame = f; return *this; } - StackView &items(std::initializer_list list) + StackView & items(std::initializer_list list) { inner.items.extend_copy(span(list)).unwrap(); return *this; } - StackView &items(Span list) + StackView & items(Span list) { inner.items.extend_copy(list).unwrap(); return *this; @@ -414,7 +413,7 @@ struct StackView : View virtual ViewState tick(ViewContext const &, CRect const &, f32, ViewEvents, Fn build) override { - for (View *item : inner.items) + for (View * item : inner.items) { build(*item); } @@ -486,44 +485,44 @@ struct TextView : View virtual ~TextView() override = default; - TextView ©able(bool allow) + TextView & copyable(bool allow) { state.copyable = allow; return *this; } - TextView &highlight(TextHighlight highlight) + TextView & highlight(TextHighlight highlight) { inner.text.highlight(highlight); return *this; } - TextView &clear_highlights() + TextView & clear_highlights() { inner.text.clear_highlights(); return *this; } - TextView &cursor_highlight_style(TextHighlightStyle s) + TextView & cursor_highlight_style(TextHighlightStyle s) { styling.cursor_highlight = s; return *this; } - TextView &style(TextStyle const &style, FontStyle const &font, u32 first = 0, - u32 count = U32_MAX) + TextView & style(TextStyle const & style, FontStyle const & font, + u32 first = 0, u32 count = U32_MAX) { inner.text.style(style, font, first, count); return *this; } - TextView &text(Span t) + TextView & text(Span t) { inner.text.set_text(t); return *this; } - TextView &text(Span t) + TextView & text(Span t) { inner.text.set_text(t); return *this; @@ -534,8 +533,8 @@ struct TextView : View return inner.text.get_text(); } - virtual ViewState tick(ViewContext const &ctx, CRect const ®ion, f32 zoom, - ViewEvents events, Fn) override + virtual ViewState tick(ViewContext const & ctx, CRect const & region, + f32 zoom, ViewEvents events, Fn) override { TextCommand cmd = TextCommand::None; if (events.drag_start) @@ -561,8 +560,8 @@ struct TextView : View return {.extent = inner.text.inner.layout.extent}; } - virtual void render(Canvas &canvas, CRect const ®ion, f32 zoom, - CRect const &clip) override + virtual void render(Canvas & canvas, CRect const & region, f32 zoom, + CRect const & clip) override { highlight(TextHighlight{.slice = inner.compositor.get_cursor().as_slice( inner.text.get_text().size32()), @@ -630,100 +629,100 @@ struct TextInput : View virtual ~TextInput() override = default; - TextInput &multiline(bool e) + TextInput & multiline(bool e) { state.multiline = e; return *this; } - TextInput &enter_submits(bool e) + TextInput & enter_submits(bool e) { state.enter_submits = e; return *this; } - TextInput &tab_input(bool e) + TextInput & tab_input(bool e) { state.tab_input = e; return *this; } - TextInput &highlight(TextHighlight const &highlight) + TextInput & highlight(TextHighlight const & highlight) { inner.content.inner.highlights.push(highlight).unwrap(); return *this; } - TextInput &clear_highlights() + TextInput & clear_highlights() { inner.content.inner.highlights.clear(); return *this; } - TextInput &on_edit(Fn f) + TextInput & on_edit(Fn f) { cb.edit = f; return *this; } - TextInput &on_submit(Fn f) + TextInput & on_submit(Fn f) { cb.submit = f; return *this; } - TextInput &on_focus_in(Fn f) + TextInput & on_focus_in(Fn f) { cb.focus_in = f; return *this; } - TextInput &on_focus_out(Fn f) + TextInput & on_focus_out(Fn f) { cb.focus_out = f; return *this; } - TextInput &content(Span t) + TextInput & content(Span t) { inner.content.set_text(t); return *this; } - TextInput &content(Span t) + TextInput & content(Span t) { inner.content.set_text(t); return *this; } - TextInput &content_style(TextStyle const &style, FontStyle const &font, - u32 first = 0, u32 count = U32_MAX) + TextInput & content_style(TextStyle const & style, FontStyle const & font, + u32 first = 0, u32 count = U32_MAX) { inner.content.style(style, font, first, count); return *this; } - TextInput &stub(Span t) + TextInput & stub(Span t) { inner.stub.set_text(t); return *this; } - TextInput &stub(Span t) + TextInput & stub(Span t) { inner.stub.set_text(t); return *this; } - TextInput &stub_style(TextStyle const &style, FontStyle const &font, - u32 first = 0, u32 count = U32_MAX) + TextInput & stub_style(TextStyle const & style, FontStyle const & font, + u32 first = 0, u32 count = U32_MAX) { inner.stub.style(style, font, first, count); return *this; } - constexpr TextCommand command(ViewContext const &ctx) const + constexpr TextCommand command(ViewContext const & ctx) const { if (ctx.key_state(KeyCode::Escape)) { @@ -846,8 +845,8 @@ struct TextInput : View return TextCommand::None; } - virtual ViewState tick(ViewContext const &ctx, CRect const ®ion, f32 zoom, - ViewEvents events, Fn) override + virtual ViewState tick(ViewContext const & ctx, CRect const & region, + f32 zoom, ViewEvents events, Fn) override { bool edited = false; auto erase = [this, &edited](Slice32 styling) { @@ -960,8 +959,8 @@ struct TextInput : View return {.extent = inner.content.inner.layout.extent}; } - virtual void render(Canvas &canvas, CRect const ®ion, f32 zoom, - CRect const &clip) override + virtual void render(Canvas & canvas, CRect const & region, f32 zoom, + CRect const & clip) override { if (inner.content.inner.text.is_empty()) { @@ -1019,8 +1018,8 @@ struct Button : View Fn hovered = noop; } cb; - virtual ViewState tick(ViewContext const &ctx, CRect const &, f32, - ViewEvents events, Fn) override + virtual ViewState tick(ViewContext const & ctx, CRect const &, f32, + ViewEvents events, Fn) override { state.press.tick(ctx, events); @@ -1055,7 +1054,7 @@ struct Button : View 2 * styling.padding(allocated)}; } - virtual void render(Canvas &canvas, CRect const ®ion, f32, + virtual void render(Canvas & canvas, CRect const & region, f32, CRect const &) override { ColorGradient tint = (state.press.hovered && !state.press.held) ? @@ -1094,93 +1093,94 @@ struct TextButton : Button virtual ~TextButton() override = default; - TextButton &disable(bool d) + TextButton & disable(bool d) { state.disabled = d; return *this; } - TextButton &style(TextStyle const &style, FontStyle const &font, - u32 first = 0, u32 count = U32_MAX) + TextButton & style(TextStyle const & style, FontStyle const & font, + u32 first = 0, u32 count = U32_MAX) { inner.text.style(style, font, first, count); return *this; } - TextButton &text(Span t) + TextButton & text(Span t) { inner.text.text(t); return *this; } - TextButton &text(Span t) + TextButton & text(Span t) { inner.text.text(t); return *this; } - TextButton &color(ColorGradient c) + TextButton & color(ColorGradient c) { styling.color = c; return *this; } - TextButton &hovered_color(ColorGradient c) + TextButton & hovered_color(ColorGradient c) { styling.hovered_color = c; return *this; } - TextButton &disabled_color(ColorGradient c) + TextButton & disabled_color(ColorGradient c) { styling.disabled_color = c; return *this; } - TextButton &corner_radii(CornerRadii c) + TextButton & corner_radii(CornerRadii c) { styling.corner_radii = c; return *this; } - TextButton &frame(f32 width, f32 height, bool constrain = true) + TextButton & frame(f32 width, f32 height, bool constrain = true) { styling.frame = Frame{width, height, constrain}; return *this; } - TextButton &frame(Frame f) + TextButton & frame(Frame f) { styling.frame = f; return *this; } - TextButton &padding(f32 x, f32 y) + TextButton & padding(f32 x, f32 y) { styling.padding = Frame{x, y}; return *this; } - TextButton &padding(Frame p) + TextButton & padding(Frame p) { styling.padding = p; return *this; } - TextButton &on_pressed(Fn f) + TextButton & on_pressed(Fn f) { cb.pressed = f; return *this; } - TextButton &on_hovered(Fn f) + TextButton & on_hovered(Fn f) { cb.hovered = f; return *this; } - virtual ViewState tick(ViewContext const &ctx, CRect const ®ion, f32 zoom, - ViewEvents events, Fn build) override + virtual ViewState tick(ViewContext const & ctx, CRect const & region, + f32 zoom, ViewEvents events, + Fn build) override { ViewState state = Button::tick(ctx, region, zoom, events, build); build(inner.text); @@ -1215,74 +1215,74 @@ struct CheckBox : View Fn changed = noop; } cb; - CheckBox &disable(bool d) + CheckBox & disable(bool d) { state.disabled = d; return *this; } - CheckBox &box_color(ColorGradient c) + CheckBox & box_color(ColorGradient c) { styling.box_color = c; return *this; } - CheckBox &box_hovered_color(ColorGradient c) + CheckBox & box_hovered_color(ColorGradient c) { styling.box_hovered_color = c; return *this; } - CheckBox &tick_color(ColorGradient c) + CheckBox & tick_color(ColorGradient c) { styling.tick_color = c; return *this; } - CheckBox &stroke(f32 s) + CheckBox & stroke(f32 s) { styling.stroke = s; return *this; } - CheckBox &thickness(f32 t) + CheckBox & thickness(f32 t) { styling.thickness = t; return *this; } - CheckBox &tick_thickness(f32 t) + CheckBox & tick_thickness(f32 t) { styling.tick_thickness = t; return *this; } - CheckBox &corner_radii(CornerRadii r) + CheckBox & corner_radii(CornerRadii r) { styling.corner_radii = r; return *this; } - CheckBox &frame(f32 width, f32 height, bool constrain = true) + CheckBox & frame(f32 width, f32 height, bool constrain = true) { styling.frame = Frame{width, height, constrain}; return *this; } - CheckBox &frame(Frame f) + CheckBox & frame(Frame f) { styling.frame = f; return *this; } - CheckBox &on_changed(Fn f) + CheckBox & on_changed(Fn f) { cb.changed = f; return *this; } - virtual ViewState tick(ViewContext const &ctx, CRect const &, f32, - ViewEvents events, Fn) override + virtual ViewState tick(ViewContext const & ctx, CRect const &, f32, + ViewEvents events, Fn) override { state.press.tick(ctx, events); @@ -1303,7 +1303,7 @@ struct CheckBox : View return {.extent = Vec2::splat(min(extent.x, extent.y))}; } - virtual void render(Canvas &canvas, CRect const ®ion, f32, + virtual void render(Canvas & canvas, CRect const & region, f32, CRect const &) override { ColorGradient tint = @@ -1320,11 +1320,13 @@ struct CheckBox : View if (state.value) { canvas.line( - {.center = region.center, - .extent = region.extent, - .stroke = 0, - .thickness = styling.tick_thickness, - .tint = styling.tick_color}, + { + .center = region.center, + .extent = region.extent, + .stroke = 0, + .thickness = styling.tick_thickness, + .tint = styling.tick_color + }, span({{0.125F, 0.5F}, {0.374F, 0.75F}, {0.775F, 0.25F}})); } @@ -1372,104 +1374,104 @@ struct Slider : View Fn changed = noop; } cb; - Slider &range(f32 low, f32 high) + Slider & range(f32 low, f32 high) { state.low = low; state.high = high; return *this; } - Slider &interp(f32 t) + Slider & interp(f32 t) { state.t = t; return *this; } - Slider &axis(Axis a) + Slider & axis(Axis a) { styling.axis = a; return *this; } - Slider &frame(f32 width, f32 height, bool constrain = true) + Slider & frame(f32 width, f32 height, bool constrain = true) { styling.frame = Frame{width, height, constrain}; return *this; } - Slider &frame(Frame f) + Slider & frame(Frame f) { styling.frame = f; return *this; } - Slider &thumb_frame(f32 width, f32 height, bool constrain = true) + Slider & thumb_frame(f32 width, f32 height, bool constrain = true) { styling.thumb_frame = Frame{width, height, constrain}; return *this; } - Slider &thumb_frame(Frame f) + Slider & thumb_frame(Frame f) { styling.thumb_frame = f; return *this; } - Slider &track_frame(f32 width, f32 height, bool constrain = true) + Slider & track_frame(f32 width, f32 height, bool constrain = true) { styling.track_frame = Frame{width, height, constrain}; return *this; } - Slider &track_frame(Frame f) + Slider & track_frame(Frame f) { styling.track_frame = f; return *this; } - Slider &thumb_color(ColorGradient c) + Slider & thumb_color(ColorGradient c) { styling.thumb_color = c; return *this; } - Slider &thumb_hovered_color(ColorGradient c) + Slider & thumb_hovered_color(ColorGradient c) { styling.thumb_hovered_color = c; return *this; } - Slider &thumb_dragging_color(ColorGradient c) + Slider & thumb_dragging_color(ColorGradient c) { styling.thumb_dragging_color = c; return *this; } - Slider &thumb_corner_radii(CornerRadii c) + Slider & thumb_corner_radii(CornerRadii c) { styling.thumb_corner_radii = c; return *this; } - Slider &track_color(ColorGradient c) + Slider & track_color(ColorGradient c) { styling.track_color = c; return *this; } - Slider &track_corner_radii(CornerRadii c) + Slider & track_corner_radii(CornerRadii c) { styling.track_corner_radii = c; return *this; } - Slider &on_changed(Fn f) + Slider & on_changed(Fn f) { cb.changed = f; return *this; } - virtual ViewState tick(ViewContext const &ctx, CRect const ®ion, f32, + virtual ViewState tick(ViewContext const & ctx, CRect const & region, f32, ViewEvents events, Fn) override { u8 const main_axis = (styling.axis == Axis::X) ? 0 : 1; @@ -1513,7 +1515,7 @@ struct Slider : View return {.extent = styling.frame(allocated)}; } - virtual void render(Canvas &canvas, CRect const ®ion, f32, + virtual void render(Canvas & canvas, CRect const & region, f32, CRect const &) override { u8 const main_axis = (styling.axis == Axis::X) ? 0 : 1; @@ -1603,21 +1605,21 @@ struct Switch : View Fn changed = noop; } cb; - Switch &on() + Switch & on() { state.value = true; cb.changed(true); return *this; } - Switch &off() + Switch & off() { state.value = false; cb.changed(false); return *this; } - Switch &toggle() + Switch & toggle() { if (state.value) { @@ -1630,68 +1632,68 @@ struct Switch : View return *this; } - Switch &on_color(ColorGradient c) + Switch & on_color(ColorGradient c) { styling.on_color = c; return *this; } - Switch &on_hovered_color(ColorGradient c) + Switch & on_hovered_color(ColorGradient c) { styling.on_hovered_color = c; return *this; } - Switch &off_color(ColorGradient c) + Switch & off_color(ColorGradient c) { styling.off_color = c; return *this; } - Switch &off_hovered_color(ColorGradient c) + Switch & off_hovered_color(ColorGradient c) { styling.off_hovered_color = c; return *this; } - Switch &track_color(ColorGradient c) + Switch & track_color(ColorGradient c) { styling.track_color = c; return *this; } - Switch &corner_radii(CornerRadii r) + Switch & corner_radii(CornerRadii r) { styling.corner_radii = r; return *this; } - Switch &frame(f32 width, f32 height, bool constrain = true) + Switch & frame(f32 width, f32 height, bool constrain = true) { styling.frame = Frame{width, height, constrain}; return *this; } - Switch &frame(Frame f) + Switch & frame(Frame f) { styling.frame = f; return *this; } - Switch &thumb_frame(f32 width, f32 height, bool constrain = true) + Switch & thumb_frame(f32 width, f32 height, bool constrain = true) { styling.thumb_frame = Frame{width, height, constrain}; return *this; } - Switch &thumb_frame(Frame f) + Switch & thumb_frame(Frame f) { styling.thumb_frame = f; return *this; } - virtual ViewState tick(ViewContext const &ctx, CRect const &, f32, - ViewEvents events, Fn) override + virtual ViewState tick(ViewContext const & ctx, CRect const &, f32, + ViewEvents events, Fn) override { state.press.tick(ctx, events); @@ -1711,7 +1713,7 @@ struct Switch : View return {.extent = styling.frame(allocated)}; } - virtual void render(Canvas &canvas, CRect const ®ion, f32, + virtual void render(Canvas & canvas, CRect const & region, f32, CRect const &) override { Vec2 const thumb_extent = styling.thumb_frame(region.extent); @@ -1776,56 +1778,56 @@ struct RadioBox : View Fn changed = noop; } cb; - RadioBox &corner_radii(CornerRadii c) + RadioBox & corner_radii(CornerRadii c) { styling.corner_radii = c; return *this; } - RadioBox &thickness(f32 t) + RadioBox & thickness(f32 t) { styling.thickness = t; return *this; } - RadioBox &color(ColorGradient c) + RadioBox & color(ColorGradient c) { styling.color = c; return *this; } - RadioBox &inner_color(ColorGradient c) + RadioBox & inner_color(ColorGradient c) { styling.inner_color = c; return *this; } - RadioBox &inner_hovered_color(ColorGradient c) + RadioBox & inner_hovered_color(ColorGradient c) { styling.inner_hovered_color = c; return *this; } - RadioBox &frame(f32 width, f32 height, bool constrain = true) + RadioBox & frame(f32 width, f32 height, bool constrain = true) { styling.frame = Frame{width, height, constrain}; return *this; } - RadioBox &frame(Frame f) + RadioBox & frame(Frame f) { styling.frame = f; return *this; } - RadioBox &on_changed(Fn f) + RadioBox & on_changed(Fn f) { cb.changed = f; return *this; } - virtual ViewState tick(ViewContext const &ctx, CRect const &, f32, - ViewEvents events, Fn) override + virtual ViewState tick(ViewContext const & ctx, CRect const &, f32, + ViewEvents events, Fn) override { state.press.tick(ctx, events); @@ -1845,7 +1847,7 @@ struct RadioBox : View return {.extent = styling.frame(allocated)}; } - virtual void render(Canvas &canvas, CRect const ®ion, f32, + virtual void render(Canvas & canvas, CRect const & region, f32, CRect const &) override { canvas.rrect({.center = region.center, @@ -1892,13 +1894,15 @@ struct ScalarInput i32 i32 = 0; f32 f32; }; + ScalarInputType type = ScalarInputType::i32; }; namespace fmt { -inline bool push(Context const &ctx, Spec const &spec, ScalarInput const &value) +inline bool push(Context const & ctx, Spec const & spec, + ScalarInput const & value) { switch (value.type) { @@ -1980,18 +1984,22 @@ struct ScalarState constexpr ScalarState scalar(f32 base, f32 min, f32 max, f32 step) { - return ScalarState{.base = {.f32 = base, .type = ScalarInputType::i32}, - .min = {.f32 = min, .type = ScalarInputType::i32}, - .max = {.f32 = max, .type = ScalarInputType::i32}, - .step = {.f32 = step, .type = ScalarInputType::i32}}; + return ScalarState{ + .base = {.f32 = base, .type = ScalarInputType::i32}, + .min = {.f32 = min, .type = ScalarInputType::i32}, + .max = {.f32 = max, .type = ScalarInputType::i32}, + .step = {.f32 = step, .type = ScalarInputType::i32} + }; } constexpr ScalarState scalar(i32 base, i32 min, i32 max, i32 step) { - return ScalarState{.base = {.i32 = base, .type = ScalarInputType::i32}, - .min = {.i32 = min, .type = ScalarInputType::i32}, - .max = {.i32 = max, .type = ScalarInputType::i32}, - .step = {.i32 = step, .type = ScalarInputType::i32}}; + return ScalarState{ + .base = {.i32 = base, .type = ScalarInputType::i32}, + .min = {.i32 = min, .type = ScalarInputType::i32}, + .max = {.i32 = max, .type = ScalarInputType::i32}, + .step = {.i32 = step, .type = ScalarInputType::i32} + }; } struct ScalarDragBox : View @@ -2042,14 +2050,14 @@ struct ScalarDragBox : View { } - static void scalar_fmt(fmt::Context const &ctx, ScalarInput v) + static void scalar_fmt(fmt::Context const & ctx, ScalarInput v) { fmt::format(ctx, v); } - static void scalar_parse(Span text, ScalarState &styling); + static void scalar_parse(Span text, ScalarState & styling); - virtual ViewState tick(ViewContext const &ctx, CRect const ®ion, f32, + virtual ViewState tick(ViewContext const & ctx, CRect const & region, f32, ViewEvents events, Fn build) override { state.dragging = events.dragging; @@ -2113,7 +2121,7 @@ struct ScalarDragBox : View return {.extent = sizes[0] + 2 * styling.padding(allocated)}; } - virtual void render(Canvas &canvas, CRect const ®ion, f32, + virtual void render(Canvas & canvas, CRect const & region, f32, CRect const &) override { canvas.rrect({.center = region.center, @@ -2148,7 +2156,7 @@ struct ScalarDragBox : View } } - virtual Cursor cursor(CRect const ®ion, f32, Vec2 offset) override + virtual Cursor cursor(CRect const & region, f32, Vec2 offset) override { (void) region; (void) offset; @@ -2179,30 +2187,36 @@ struct ScalarBox : FlexView .frame(Frame{}.scale(1, 1)); inner.dec.text(U"-"_str) - .style(TextStyle{.shadow_scale = 1, - .shadow_offset = {1, 1}, - .foreground = DEFAULT_THEME.on_primary, - .shadow = colors::BLACK}, - FontStyle{.font = engine->default_font, - .font_height = DEFAULT_THEME.body_font_height, - .line_height = 1}) + .style( + TextStyle{ + .shadow_scale = 1, + .shadow_offset = {1, 1}, + .foreground = DEFAULT_THEME.on_primary, + .shadow = colors::BLACK + }, + FontStyle{.font = engine->default_font, + .font_height = DEFAULT_THEME.body_font_height, + .line_height = 1}) .on_pressed(fn(this, - [](ScalarBox *b) { + [](ScalarBox * b) { b->inner.drag.state.value.step_value(-1); b->cb.update(b->inner.drag.state.value.current); })) .padding(5, 5); inner.inc.text(U"+"_str) - .style(TextStyle{.shadow_scale = 1, - .shadow_offset = {1, 1}, - .foreground = DEFAULT_THEME.on_primary, - .shadow = colors::BLACK}, - FontStyle{.font = engine->default_font, - .font_height = DEFAULT_THEME.body_font_height, - .line_height = 1}) + .style( + TextStyle{ + .shadow_scale = 1, + .shadow_offset = {1, 1}, + .foreground = DEFAULT_THEME.on_primary, + .shadow = colors::BLACK + }, + FontStyle{.font = engine->default_font, + .font_height = DEFAULT_THEME.body_font_height, + .line_height = 1}) .on_pressed(fn(this, - [](ScalarBox *b) { + [](ScalarBox * b) { b->inner.drag.state.value.step_value(1); b->cb.update(b->inner.drag.state.value.current); })) @@ -2217,7 +2231,7 @@ struct ScalarBox : FlexView // inner.drag.cb.update = - fn(this, [](ScalarBox *b, ScalarInput in) { b->cb.update(in); }); + fn(this, [](ScalarBox * b, ScalarInput in) { b->cb.update(in); }); // [ ] set drag box style: create similar methods for it // [ ] all views must have these methods @@ -2228,19 +2242,19 @@ struct ScalarBox : FlexView // [ ] placeholder - ScalarBox &stroke(f32 s) + ScalarBox & stroke(f32 s) { inner.drag.styling.stroke = s; return *this; } - ScalarBox &thickness(f32 t) + ScalarBox & thickness(f32 t) { inner.drag.styling.thickness = t; return *this; } - ScalarBox &padding(f32 x, f32 y) + ScalarBox & padding(f32 x, f32 y) { inner.dec.padding(x, y); inner.inc.padding(x, y); @@ -2248,7 +2262,7 @@ struct ScalarBox : FlexView return *this; } - ScalarBox &padding(Frame p) + ScalarBox & padding(Frame p) { inner.dec.padding(p); inner.inc.padding(p); @@ -2256,7 +2270,7 @@ struct ScalarBox : FlexView return *this; } - ScalarBox &frame(f32 width, f32 height, bool constrain = true) + ScalarBox & frame(f32 width, f32 height, bool constrain = true) { inner.dec.frame(width, height, constrain); inner.inc.frame(width, height, constrain); @@ -2264,7 +2278,7 @@ struct ScalarBox : FlexView return *this; } - ScalarBox &frame(Frame f) + ScalarBox & frame(Frame f) { inner.dec.frame(f); inner.inc.frame(f); @@ -2272,7 +2286,7 @@ struct ScalarBox : FlexView return *this; } - ScalarBox &corner_radii(CornerRadii r) + ScalarBox & corner_radii(CornerRadii r) { inner.dec.corner_radii(r); inner.inc.corner_radii(r); @@ -2280,14 +2294,14 @@ struct ScalarBox : FlexView return *this; } - ScalarBox &on_update(Fn f) + ScalarBox & on_update(Fn f) { cb.update = f; return *this; } - ScalarBox &text_style(TextStyle const &style, FontStyle const &font, - u32 first, u32 count) + ScalarBox & text_style(TextStyle const & style, FontStyle const & font, + u32 first, u32 count) { inner.dec.style(style, font, first, count); inner.inc.style(style, font, first, count); @@ -2335,7 +2349,7 @@ struct ScrollBar : View Fn scrolled = noop; } cb; - virtual ViewState tick(ViewContext const &ctx, CRect const ®ion, f32, + virtual ViewState tick(ViewContext const & ctx, CRect const & region, f32, ViewEvents events, Fn) override { u8 const main_axis = (styling.axis == Axis::X) ? 0 : 1; @@ -2383,7 +2397,7 @@ struct ScrollBar : View return allocated + 1; } - virtual void render(Canvas &canvas, CRect const ®ion, f32, + virtual void render(Canvas & canvas, CRect const & region, f32, CRect const &) override { u8 const main_axis = (styling.axis == Axis::X) ? 0 : 1; @@ -2456,7 +2470,7 @@ struct ScrollViewFrame : View Option child = None; } inner; - virtual ViewState tick(ViewContext const &ctx, CRect const ®ion, f32, + virtual ViewState tick(ViewContext const & ctx, CRect const & region, f32, ViewEvents events, Fn build) override { if (inner.child) @@ -2529,7 +2543,7 @@ struct ScrollView : View virtual ~ScrollView() override = default; - ScrollView &disable(bool d) + ScrollView & disable(bool d) { state.disabled = d; inner.x_bar.state.disabled = d; @@ -2537,61 +2551,61 @@ struct ScrollView : View return *this; } - ScrollView &item(View &v) + ScrollView & item(View & v) { inner.view_frame.inner.child = Some{&v}; return *this; } - ScrollView &item(NoneType) + ScrollView & item(NoneType) { inner.view_frame.inner.child = None; return *this; } - ScrollView &thumb_color(ColorGradient c) + ScrollView & thumb_color(ColorGradient c) { inner.x_bar.styling.thumb_color = c; inner.y_bar.styling.thumb_color = c; return *this; } - ScrollView &thumb_hovered_color(ColorGradient c) + ScrollView & thumb_hovered_color(ColorGradient c) { inner.x_bar.styling.thumb_hovered_color = c; inner.y_bar.styling.thumb_hovered_color = c; return *this; } - ScrollView &thumb_dragging_color(ColorGradient c) + ScrollView & thumb_dragging_color(ColorGradient c) { inner.x_bar.styling.thumb_dragging_color = c; inner.y_bar.styling.thumb_dragging_color = c; return *this; } - ScrollView &thumb_corner_radii(CornerRadii c) + ScrollView & thumb_corner_radii(CornerRadii c) { inner.x_bar.styling.thumb_corner_radii = c; inner.y_bar.styling.thumb_corner_radii = c; return *this; } - ScrollView &track_color(ColorGradient c) + ScrollView & track_color(ColorGradient c) { inner.x_bar.styling.track_color = c; inner.y_bar.styling.track_color = c; return *this; } - ScrollView &track_corner_radii(CornerRadii c) + ScrollView & track_corner_radii(CornerRadii c) { inner.x_bar.styling.track_corner_radii = c; inner.y_bar.styling.track_corner_radii = c; return *this; } - ScrollView &axes(Axes a) + ScrollView & axes(Axes a) { styling.axes = a; inner.x_bar.state.hidden = has_bits(a, Axes::X); @@ -2599,26 +2613,26 @@ struct ScrollView : View return *this; } - ScrollView &frame(f32 width, f32 height, bool constrain) + ScrollView & frame(f32 width, f32 height, bool constrain) { styling.frame = Frame{width, height, constrain}; return *this; } - ScrollView &frame(Frame f) + ScrollView & frame(Frame f) { styling.frame = f; return *this; } - ScrollView &bar_size(f32 x, f32 y) + ScrollView & bar_size(f32 x, f32 y) { styling.x_bar_size = Size{.offset = x}; styling.y_bar_size = Size{.offset = y}; return *this; } - ScrollView &bar_size(Size x, Size y) + ScrollView & bar_size(Size x, Size y) { styling.x_bar_size = x; styling.y_bar_size = y; @@ -2706,7 +2720,7 @@ struct ComboBoxItem : View Option child = None; } inner; - virtual ViewState tick(ViewContext const &ctx, CRect const &, f32, + virtual ViewState tick(ViewContext const & ctx, CRect const &, f32, ViewEvents events, Fn build) override { state.press.tick(ctx, events); @@ -2742,7 +2756,7 @@ struct ComboBoxItem : View return {.extent = allocated}; } - virtual void render(Canvas &canvas, CRect const ®ion, f32, + virtual void render(Canvas & canvas, CRect const & region, f32, CRect const &) override { canvas.rrect({.center = region.center, @@ -2774,8 +2788,9 @@ struct TextComboBoxItem : ComboBoxItem inner.text.state.copyable = false; } - virtual ViewState tick(ViewContext const &ctx, CRect const ®ion, f32 zoom, - ViewEvents events, Fn build) override + virtual ViewState tick(ViewContext const & ctx, CRect const & region, + f32 zoom, ViewEvents events, + Fn build) override { build(inner.text); @@ -2807,10 +2822,10 @@ struct ComboBoxScrollView : View Vec items{default_allocator}; } inner; - virtual ViewState tick(ViewContext const &ctx, CRect const ®ion, f32, + virtual ViewState tick(ViewContext const & ctx, CRect const & region, f32, ViewEvents events, Fn build) override { - for (ComboBoxItem *item : inner.items) + for (ComboBoxItem * item : inner.items) { build(*item); } @@ -2836,7 +2851,7 @@ struct ComboBoxScrollView : View Vec2 size = styling.frame(allocated); f32 items_height = 0; - for (Vec2 const &styling : sizes) + for (Vec2 const & styling : sizes) { items_height += styling.y; } @@ -2859,7 +2874,7 @@ struct ComboBoxScrollView : View return allocated + 25; } - virtual void render(Canvas &canvas, CRect const ®ion, f32, + virtual void render(Canvas & canvas, CRect const & region, f32, CRect const &) override { canvas.rrect({.center = region.center, @@ -2904,72 +2919,72 @@ struct ComboBox : View virtual ~ComboBox() override = default; - ComboBox &disable(bool d) + ComboBox & disable(bool d) { state.disabled = d; return *this; } - ComboBox &color(ColorGradient c) + ComboBox & color(ColorGradient c) { styling.color = c; return *this; } - ComboBox &hovered_color(ColorGradient c) + ComboBox & hovered_color(ColorGradient c) { styling.hovered_color = c; return *this; } - ComboBox &alignment(f32 a) + ComboBox & alignment(f32 a) { styling.alignment = a; return *this; } - ComboBox &frame(f32 width, f32 height, bool constrain) + ComboBox & frame(f32 width, f32 height, bool constrain) { styling.frame = Frame{width, height, constrain}; return *this; } - ComboBox &frame(Frame f) + ComboBox & frame(Frame f) { styling.frame = f; return *this; } - ComboBox &align(f32 a) + ComboBox & align(f32 a) { styling.alignment = a; return *this; } - ComboBox &on_selected(Fn)> styling) + ComboBox & on_selected(Fn)> styling) { cb.selected = styling; return *this; } - ComboBox &add_item(ComboBoxItem &item) + ComboBox & add_item(ComboBoxItem & item) { u32 const index = inner.scroll_view.inner.items.size32(); item.state.index = index; item.style = Some{&styling.item}; item.cb.selected = - fn(this, [](ComboBox *b, Option item) { b->set_selected(item); }); + fn(this, [](ComboBox * b, Option item) { b->set_selected(item); }); item.state.selected = Some const *>{&state.selected}; inner.scroll_view.inner.items.push(&item).unwrap(); return *this; } - ComboBox &set_header(ComboBoxItem &item) + ComboBox & set_header(ComboBoxItem & item) { - inner.header = Some{&item}; - item.state.index = 0; - item.cb.selected = fn(this, [](ComboBox *b, Option) { b->open(); }); - item.style = Some{&styling.item}; + inner.header = Some{&item}; + item.state.index = 0; + item.cb.selected = fn(this, [](ComboBox * b, Option) { b->open(); }); + item.style = Some{&styling.item}; item.state.selected = None; return *this; } @@ -2979,7 +2994,7 @@ struct ComboBox : View return inner.scroll_view.inner.items.size32(); } - ComboBox &set_selected(Option item) + ComboBox & set_selected(Option item) { CHECK(!(item.is_some() && item.value_ > inner.scroll_view.inner.items.size32())); @@ -2998,19 +3013,19 @@ struct ComboBox : View return inner.scroll_view.state.opened; } - ComboBox &close() + ComboBox & close() { inner.scroll_view.state.opened = false; return *this; } - ComboBox &open() + ComboBox & open() { inner.scroll_view.state.opened = true; return *this; } - ComboBox &toggle() + ComboBox & toggle() { if (inner.scroll_view.state.opened) { @@ -3022,7 +3037,7 @@ struct ComboBox : View } } - virtual ViewState tick(ViewContext const &ctx, CRect const &, f32, + virtual ViewState tick(ViewContext const & ctx, CRect const &, f32, ViewEvents events, Fn build) override { state.press.tick(ctx, events); @@ -3065,7 +3080,7 @@ struct ComboBox : View return {.extent = frame}; } - virtual void render(Canvas &canvas, CRect const ®ion, f32, + virtual void render(Canvas & canvas, CRect const & region, f32, CRect const &) override { canvas.rrect( @@ -3125,4 +3140,4 @@ struct ProgressBar : View { }; -} // namespace ash \ No newline at end of file +} // namespace ash diff --git a/ashura/engine/window.cc b/ashura/engine/window.cc index 758e0566..afc5268e 100644 --- a/ashura/engine/window.cc +++ b/ashura/engine/window.cc @@ -20,11 +20,11 @@ struct WindowEventListener struct WindowImpl { - SDL_Window *win = nullptr; + SDL_Window * win = nullptr; gpu::Surface surface = nullptr; SDL_WindowID id = 0; SparseVec> listeners = {}; - gpu::Instance *instance = nullptr; + gpu::Instance * instance = nullptr; Fn hit_test = fn([](Vec2U) { return WindowRegion::Normal; }); }; @@ -37,12 +37,12 @@ struct SystemEventListener struct ClipBoardImpl : ClipBoard { - virtual Result<> get(Span mime, Vec &out) override + virtual Result<> get(Span mime, Vec & out) override { char mime_c_str[256]; CHECK(to_c_str(mime, mime_c_str)); - usize mime_data_len; - void *data = SDL_GetClipboardData(mime_c_str, &mime_data_len); + usize mime_data_len; + void * data = SDL_GetClipboardData(mime_c_str, &mime_data_len); if (data == nullptr) { return Err{}; @@ -68,27 +68,28 @@ struct ClipBoardImpl : ClipBoard char mime_c_str[256]; CHECK(to_c_str(mime, mime_c_str)); - char const *mime_types[] = {mime_c_str}; + char const * mime_types[] = {mime_c_str}; - Vec *data_ctx; + Vec * data_ctx; CHECK(default_allocator.nalloc(1, data_ctx)); new (data_ctx) Vec{}; data_ctx->extend_copy(data).unwrap(); bool failed = SDL_SetClipboardData( - [](void *userdata, const char *mime_type, usize *size) -> void const * { + [](void * userdata, char const * mime_type, + usize * size) -> void const * { if (mime_type == nullptr) { *size = 0; return nullptr; } - auto *ctx = reinterpret_cast *>(userdata); - *size = ctx->size(); + auto * ctx = reinterpret_cast *>(userdata); + *size = ctx->size(); return ctx->data(); }, - [](void *userdata) { - auto *ctx = reinterpret_cast *>(userdata); + [](void * userdata) { + auto * ctx = reinterpret_cast *>(userdata); ctx->uninit(); default_allocator.ndealloc(ctx, 1); }, @@ -108,15 +109,15 @@ struct WindowSystemImpl : WindowSystem SparseVec> listeners; ClipBoardImpl clipboard; - SDL_Window *hnd(Window window) + SDL_Window * hnd(Window window) { return ((WindowImpl *) window)->win; } - virtual Option create_window(gpu::Instance &instance, + virtual Option create_window(gpu::Instance & instance, Span title) override { - char *title_c_str; + char * title_c_str; if (!default_allocator.nalloc(title.size() + 1, title_c_str)) { return None; @@ -128,21 +129,21 @@ struct WindowSystemImpl : WindowSystem mem::copy(title, title_c_str); title_c_str[title.size()] = 0; - SDL_Window *window = SDL_CreateWindow( - title_c_str, 1920, 1080, SDL_WINDOW_VULKAN | SDL_WINDOW_RESIZABLE); + SDL_Window * window = SDL_CreateWindow( + title_c_str, 1'920, 1'080, SDL_WINDOW_VULKAN | SDL_WINDOW_RESIZABLE); CHECKSdl(window != nullptr); SDL_WindowID id = SDL_GetWindowID(window); CHECKSdl(id != 0); CHECK(instance.get_backend() == gpu::Backend::Vulkan); - vk::Instance &vk_instance = (vk::Instance &) instance; - VkSurfaceKHR surface; + vk::Instance & vk_instance = (vk::Instance &) instance; + VkSurfaceKHR surface; CHECKSdl(SDL_Vulkan_CreateSurface(window, vk_instance.vk_instance, nullptr, &surface)); - WindowImpl *impl; + WindowImpl * impl; CHECK(default_allocator.nalloc(1, impl)); @@ -161,7 +162,7 @@ struct WindowSystemImpl : WindowSystem { if (window != nullptr) { - WindowImpl *win = (WindowImpl *) window; + WindowImpl * win = (WindowImpl *) window; win->instance->uninit_surface(win->surface); SDL_DestroyWindow(win->win); win->listeners.reset(); @@ -171,7 +172,7 @@ struct WindowSystemImpl : WindowSystem virtual void set_title(Window window, Span title) override { - char *title_c_str; + char * title_c_str; CHECK(default_allocator.nalloc(title.size() + 1, title_c_str)); defer title_c_str_{ @@ -183,9 +184,9 @@ struct WindowSystemImpl : WindowSystem CHECKSdl(SDL_SetWindowTitle(hnd(window), title_c_str)); } - virtual char const *get_title(Window window) override + virtual char const * get_title(Window window) override { - char const *title = SDL_GetWindowTitle(hnd(window)); + char const * title = SDL_GetWindowTitle(hnd(window)); CHECKSdl(title != nullptr); return title; } @@ -281,7 +282,7 @@ struct WindowSystemImpl : WindowSystem CHECK_DESC(false, "unsupported image format"); } - SDL_Surface *icon = SDL_CreateSurfaceFrom( + SDL_Surface * icon = SDL_CreateSurfaceFrom( static_cast(image.width), static_cast(image.height), fmt, (void *) image.channels.data(), static_cast(image.pitch())); CHECKSdl(icon != nullptr); @@ -356,21 +357,21 @@ struct WindowSystemImpl : WindowSystem virtual u64 listen(Window window, WindowEventTypes event_types, Fn callback) override { - WindowImpl *pwin = (WindowImpl *) window; + WindowImpl * pwin = (WindowImpl *) window; return pwin->listeners.push(WindowEventListener{callback, event_types}) .unwrap(); } virtual void unlisten(Window window, u64 listener) override { - WindowImpl *pwin = (WindowImpl *) window; + WindowImpl * pwin = (WindowImpl *) window; pwin->listeners.erase(listener); } - static SDL_HitTestResult sdl_hit_test(SDL_Window *, SDL_Point const *area, - void *data) + static SDL_HitTestResult sdl_hit_test(SDL_Window *, SDL_Point const * area, + void * data) { - WindowImpl *win = (WindowImpl *) data; + WindowImpl * win = (WindowImpl *) data; WindowRegion region = win->hit_test(Vec2U{(u32) area->x, (u32) area->y}); switch (region) { @@ -402,8 +403,8 @@ struct WindowSystemImpl : WindowSystem virtual Result<> set_hit_test(Window window, Fn hit) override { - WindowImpl *pwin = (WindowImpl *) window; - pwin->hit_test = hit; + WindowImpl * pwin = (WindowImpl *) window; + pwin->hit_test = hit; if (SDL_SetWindowHitTest(pwin->win, sdl_hit_test, pwin) != 0) { return Err{}; @@ -414,20 +415,20 @@ struct WindowSystemImpl : WindowSystem virtual gpu::Surface get_surface(Window window) override { - WindowImpl *pwin = (WindowImpl *) window; + WindowImpl * pwin = (WindowImpl *) window; return pwin->surface; } - void push_window_event(SDL_WindowID window_id, WindowEvent const &event) + void push_window_event(SDL_WindowID window_id, WindowEvent const & event) { - SDL_Window *win = SDL_GetWindowFromID(window_id); + SDL_Window * win = SDL_GetWindowFromID(window_id); CHECK(win != nullptr); SDL_PropertiesID props_id = SDL_GetWindowProperties(win); - WindowImpl *impl = + WindowImpl * impl = (WindowImpl *) SDL_GetPointerProperty(props_id, "impl", nullptr); CHECK(impl != nullptr); - for (WindowEventListener const &listener : impl->listeners.dense.v0) + for (WindowEventListener const & listener : impl->listeners.dense.v0) { if (has_bits(listener.types, event.type)) { @@ -436,9 +437,9 @@ struct WindowSystemImpl : WindowSystem } } - void push_system_event(SystemEvent const &event) + void push_system_event(SystemEvent const & event) { - for (SystemEventListener const &listener : listeners.dense.v0) + for (SystemEventListener const & listener : listeners.dense.v0) { if (has_bits(listener.types, event.type)) { @@ -546,10 +547,11 @@ struct WindowSystemImpl : WindowSystem case SDL_EVENT_MOUSE_BUTTON_DOWN: case SDL_EVENT_MOUSE_BUTTON_UP: { - MouseClickEvent mouse_event{.id = event.button.which, - .position = - Vec2{event.button.x, event.button.y}, - .clicks = event.button.clicks}; + MouseClickEvent mouse_event{ + .id = event.button.which, + .position = Vec2{event.button.x, event.button.y}, + .clicks = event.button.clicks + }; switch (event.button.button) { case SDL_BUTTON_LEFT: @@ -597,11 +599,12 @@ struct WindowSystemImpl : WindowSystem WindowEvent{ .mouse_motion = MouseMotionEvent{ - .id = event.motion.which, - .position = Vec2{event.motion.x, event.motion.y}, - .translation = + .id = event.motion.which, + .position = Vec2{event.motion.x, event.motion.y}, + .translation = Vec2{event.motion.xrel, event.motion.yrel}}, - .type = WindowEventTypes::MouseMotion}); + .type = WindowEventTypes::MouseMotion + }); return; case SDL_EVENT_MOUSE_WHEEL: @@ -610,11 +613,12 @@ struct WindowSystemImpl : WindowSystem WindowEvent{ .mouse_wheel = MouseWheelEvent{ - .id = event.wheel.which, - .position = + .id = event.wheel.which, + .position = Vec2{event.wheel.mouse_x, event.wheel.mouse_y}, - .translation = Vec2{event.wheel.x, event.wheel.y}}, - .type = WindowEventTypes::MouseWheel}); + .translation = Vec2{event.wheel.x, event.wheel.y}}, + .type = WindowEventTypes::MouseWheel + }); return; case SDL_EVENT_KEY_DOWN: @@ -630,7 +634,8 @@ struct WindowSystemImpl : WindowSystem .action = event.type == SDL_EVENT_KEY_DOWN ? KeyAction::Press : KeyAction::Release}, - .type = WindowEventTypes::Key}); + .type = WindowEventTypes::Key + }); return; case SDL_EVENT_WINDOW_DESTROYED: @@ -725,13 +730,13 @@ struct WindowSystemImpl : WindowSystem } } - virtual ClipBoard &get_clipboard() override + virtual ClipBoard & get_clipboard() override { return clipboard; } }; -ASH_C_LINKAGE ASH_DLL_EXPORT WindowSystem *window_system = nullptr; +ASH_C_LINKAGE ASH_DLL_EXPORT WindowSystem * window_system = nullptr; void WindowSystem::init() { @@ -749,4 +754,4 @@ void WindowSystem::uninit() SDL_Quit(); } -} // namespace ash \ No newline at end of file +} // namespace ash diff --git a/ashura/engine/window.h b/ashura/engine/window.h index 534017a1..c6c3e73a 100644 --- a/ashura/engine/window.h +++ b/ashura/engine/window.h @@ -12,7 +12,7 @@ namespace ash { -typedef struct Window_T *Window; +typedef struct Window_T * Window; struct WindowSystem { @@ -22,14 +22,14 @@ struct WindowSystem virtual ~WindowSystem() = default; - virtual Option create_window(gpu::Instance &instance, + virtual Option create_window(gpu::Instance & instance, Span title) = 0; virtual void uninit_window(Window window) = 0; virtual void set_title(Window window, Span title) = 0; - virtual char const *get_title(Window window) = 0; + virtual char const * get_title(Window window) = 0; virtual void maximize(Window window) = 0; @@ -96,9 +96,9 @@ struct WindowSystem virtual void poll_events() = 0; - virtual ClipBoard &get_clipboard() = 0; + virtual ClipBoard & get_clipboard() = 0; }; -ASH_C_LINKAGE ASH_DLL_EXPORT WindowSystem *window_system; +ASH_C_LINKAGE ASH_DLL_EXPORT WindowSystem * window_system; -} // namespace ash \ No newline at end of file +} // namespace ash diff --git a/ashura/gpu/gpu.h b/ashura/gpu/gpu.h index 27150453..cb909abd 100644 --- a/ashura/gpu/gpu.h +++ b/ashura/gpu/gpu.h @@ -17,28 +17,28 @@ constexpr u32 REMAINING_MIP_LEVELS = ~0U; constexpr u32 REMAINING_ARRAY_LAYERS = ~0U; constexpr u64 WHOLE_SIZE = ~0ULL; -constexpr u32 MAX_IMAGE_EXTENT_1D = 8192; -constexpr u32 MAX_IMAGE_EXTENT_2D = 8192; -constexpr u32 MAX_IMAGE_EXTENT_3D = 2048; -constexpr u32 MAX_IMAGE_EXTENT_CUBE = 8192; -constexpr u32 MAX_IMAGE_ARRAY_LAYERS = 1024; -constexpr u32 MAX_VIEWPORT_EXTENT = 8192; -constexpr u32 MAX_FRAMEBUFFER_EXTENT = 8192; -constexpr u32 MAX_FRAMEBUFFER_LAYERS = 1024; +constexpr u32 MAX_IMAGE_EXTENT_1D = 8'192; +constexpr u32 MAX_IMAGE_EXTENT_2D = 8'192; +constexpr u32 MAX_IMAGE_EXTENT_3D = 2'048; +constexpr u32 MAX_IMAGE_EXTENT_CUBE = 8'192; +constexpr u32 MAX_IMAGE_ARRAY_LAYERS = 1'024; +constexpr u32 MAX_VIEWPORT_EXTENT = 8'192; +constexpr u32 MAX_FRAMEBUFFER_EXTENT = 8'192; +constexpr u32 MAX_FRAMEBUFFER_LAYERS = 1'024; constexpr u32 MAX_VERTEX_ATTRIBUTES = 16; constexpr u32 MAX_PUSH_CONSTANTS_SIZE = 128; -constexpr u32 MAX_UPDATE_BUFFER_SIZE = 65536; +constexpr u32 MAX_UPDATE_BUFFER_SIZE = 65'536; constexpr u32 MAX_PIPELINE_DESCRIPTOR_SETS = 8; constexpr u32 MAX_PIPELINE_DYNAMIC_UNIFORM_BUFFERS = 8; constexpr u32 MAX_PIPELINE_DYNAMIC_STORAGE_BUFFERS = 8; constexpr u32 MAX_PIPELINE_INPUT_ATTACHMENTS = 8; constexpr u32 MAX_PIPELINE_COLOR_ATTACHMENTS = 8; -constexpr u32 MAX_DESCRIPTOR_SET_DESCRIPTORS = 4096; -constexpr u32 MAX_BINDING_DESCRIPTORS = 4096; +constexpr u32 MAX_DESCRIPTOR_SET_DESCRIPTORS = 4'096; +constexpr u32 MAX_BINDING_DESCRIPTORS = 4'096; constexpr u32 MAX_DESCRIPTOR_SET_BINDINGS = 16; constexpr u32 MAX_FRAME_BUFFERING = 4; constexpr u32 MAX_SWAPCHAIN_IMAGES = 4; -constexpr u64 MAX_UNIFORM_BUFFER_RANGE = 65536; +constexpr u64 MAX_UNIFORM_BUFFER_RANGE = 65'536; constexpr f32 MAX_SAMPLER_ANISOTROPY = 16; constexpr u32 MAX_CLIP_DISTANCES = 8; constexpr u32 MAX_CULL_DISTANCES = 8; @@ -51,24 +51,24 @@ typedef Vec3U Offset3D; typedef Vec3U Extent3D; typedef u64 FrameId; -typedef struct Buffer_T *Buffer; -typedef struct BufferView_T *BufferView; -typedef struct Image_T *Image; -typedef struct ImageView_T *ImageView; -typedef struct Sampler_T *Sampler; -typedef struct Shader_T *Shader; -typedef struct DescriptorSetLayout_T *DescriptorSetLayout; -typedef struct DescriptorSet_T *DescriptorSet; -typedef struct PipelineCache_T *PipelineCache; -typedef struct ComputePipeline_T *ComputePipeline; -typedef struct GraphicsPipeline_T *GraphicsPipeline; -typedef struct TimestampQuery_T *TimeStampQuery; -typedef struct StatisticsQuery_T *StatisticsQuery; -typedef struct CommandEncoder CommandEncoder; -typedef struct Surface_T *Surface; -typedef struct Swapchain_T *Swapchain; -typedef struct Device Device; -typedef struct Instance Instance; +typedef struct Buffer_T * Buffer; +typedef struct BufferView_T * BufferView; +typedef struct Image_T * Image; +typedef struct ImageView_T * ImageView; +typedef struct Sampler_T * Sampler; +typedef struct Shader_T * Shader; +typedef struct DescriptorSetLayout_T * DescriptorSetLayout; +typedef struct DescriptorSet_T * DescriptorSet; +typedef struct PipelineCache_T * PipelineCache; +typedef struct ComputePipeline_T * ComputePipeline; +typedef struct GraphicsPipeline_T * GraphicsPipeline; +typedef struct TimestampQuery_T * TimeStampQuery; +typedef struct StatisticsQuery_T * StatisticsQuery; +typedef struct CommandEncoder CommandEncoder; +typedef struct Surface_T * Surface; +typedef struct Swapchain_T * Swapchain; +typedef struct Device Device; +typedef struct Instance Instance; enum class ObjectType : u32 { @@ -148,7 +148,7 @@ enum class [[nodiscard]] Status : i32 TooManyObjects = -10, FormatNotSupported = -11, Unknown = -13, - SurfaceLost = -1000000000 + SurfaceLost = -1'000'000'000 }; enum class Format : i32 @@ -343,20 +343,20 @@ enum class Format : i32 enum class ColorSpace : i32 { SRGB_NONLINEAR = 0, - DISPLAY_P3_NONLINEAR = 1000104001, - EXTENDED_SRGB_LINEAR = 1000104002, - DISPLAY_P3_LINEAR = 1000104003, - DCI_P3_NONLINEAR = 1000104004, - BT709_LINEAR = 1000104005, - BT709_NONLINEAR = 1000104006, - BT2020_LINEAR = 1000104007, - HDR10_ST2084 = 1000104008, - DOLBYVISION = 1000104009, - HDR10_HLG = 1000104010, - ADOBERGB_LINEAR = 1000104011, - ADOBERGB_NONLINEAR = 1000104012, - PASS_THROUGH = 1000104013, - EXTENDED_SRGB_NONLINEAR = 1000104014 + DISPLAY_P3_NONLINEAR = 1'000'104'001, + EXTENDED_SRGB_LINEAR = 1'000'104'002, + DISPLAY_P3_LINEAR = 1'000'104'003, + DCI_P3_NONLINEAR = 1'000'104'004, + BT709_LINEAR = 1'000'104'005, + BT709_NONLINEAR = 1'000'104'006, + BT2020_LINEAR = 1'000'104'007, + HDR10_ST2084 = 1'000'104'008, + DOLBYVISION = 1'000'104'009, + HDR10_HLG = 1'000'104'010, + ADOBERGB_LINEAR = 1'000'104'011, + ADOBERGB_NONLINEAR = 1'000'104'012, + PASS_THROUGH = 1'000'104'013, + EXTENDED_SRGB_NONLINEAR = 1'000'104'014 }; enum class FormatFeatures : u32 @@ -698,10 +698,10 @@ struct Object { union { - void *handle = nullptr; - Instance *instance; - Device *device; - CommandEncoder *command_encoder; + void * handle = nullptr; + Instance * instance; + Device * device; + CommandEncoder * command_encoder; Buffer buffer; BufferView buffer_view; Image image; @@ -718,6 +718,7 @@ struct Object Surface surface; Swapchain swapchain; }; + ObjectType type = ObjectType::None; }; @@ -1259,7 +1260,7 @@ struct CommandEncoder virtual void end_compute_pass() = 0; - virtual void begin_rendering(RenderingInfo const &info) = 0; + virtual void begin_rendering(RenderingInfo const & info) = 0; virtual void end_rendering() = 0; @@ -1277,7 +1278,7 @@ struct CommandEncoder virtual void dispatch_indirect(Buffer buffer, u64 offset) = 0; - virtual void set_graphics_state(GraphicsState const &state) = 0; + virtual void set_graphics_state(GraphicsState const & state) = 0; virtual void bind_vertex_buffers(Span vertex_buffers, Span offsets) = 0; @@ -1300,11 +1301,11 @@ struct CommandEncoder struct FrameContext { - u32 buffering = 0; - FrameId tail = 0; - FrameId current = 0; - Span encoders = {}; - u32 ring_index = 0; + u32 buffering = 0; + FrameId tail = 0; + FrameId current = 0; + Span encoders = {}; + u32 ring_index = 0; }; struct Device @@ -1314,38 +1315,38 @@ struct Device virtual Result get_format_properties(Format format) = 0; - virtual Result create_buffer(BufferInfo const &info) = 0; + virtual Result create_buffer(BufferInfo const & info) = 0; virtual Result - create_buffer_view(BufferViewInfo const &info) = 0; + create_buffer_view(BufferViewInfo const & info) = 0; - virtual Result create_image(ImageInfo const &info) = 0; + virtual Result create_image(ImageInfo const & info) = 0; virtual Result - create_image_view(ImageViewInfo const &info) = 0; + create_image_view(ImageViewInfo const & info) = 0; - virtual Result create_sampler(SamplerInfo const &info) = 0; + virtual Result create_sampler(SamplerInfo const & info) = 0; - virtual Result create_shader(ShaderInfo const &info) = 0; + virtual Result create_shader(ShaderInfo const & info) = 0; virtual Result - create_descriptor_set_layout(DescriptorSetLayoutInfo const &info) = 0; + create_descriptor_set_layout(DescriptorSetLayoutInfo const & info) = 0; virtual Result create_descriptor_set(DescriptorSetLayout layout, Span variable_lengths) = 0; virtual Result - create_pipeline_cache(PipelineCacheInfo const &info) = 0; + create_pipeline_cache(PipelineCacheInfo const & info) = 0; virtual Result - create_compute_pipeline(ComputePipelineInfo const &info) = 0; + create_compute_pipeline(ComputePipelineInfo const & info) = 0; virtual Result - create_graphics_pipeline(GraphicsPipelineInfo const &info) = 0; + create_graphics_pipeline(GraphicsPipelineInfo const & info) = 0; virtual Result - create_swapchain(Surface surface, SwapchainInfo const &info) = 0; + create_swapchain(Surface surface, SwapchainInfo const & info) = 0; virtual Result create_timestamp_query() = 0; @@ -1395,23 +1396,23 @@ struct Device get_pipeline_cache_size(PipelineCache cache) = 0; virtual Result get_pipeline_cache_data(PipelineCache cache, - Vec &out) = 0; + Vec & out) = 0; virtual Result merge_pipeline_cache(PipelineCache dst, Span srcs) = 0; - virtual void update_descriptor_set(DescriptorSetUpdate const &update) = 0; + virtual void update_descriptor_set(DescriptorSetUpdate const & update) = 0; virtual Result wait_idle() = 0; virtual Result wait_queue_idle() = 0; virtual Result - get_surface_formats(Surface surface, Vec &formats) = 0; + get_surface_formats(Surface surface, Vec & formats) = 0; virtual Result - get_surface_present_modes(Surface surface, Vec &modes) = 0; + get_surface_present_modes(Surface surface, Vec & modes) = 0; virtual Result get_surface_capabilities(Surface surface) = 0; @@ -1420,7 +1421,7 @@ struct Device get_swapchain_state(Swapchain swapchain) = 0; virtual Result - invalidate_swapchain(Swapchain swapchain, SwapchainInfo const &info) = 0; + invalidate_swapchain(Swapchain swapchain, SwapchainInfo const & info) = 0; virtual Result begin_frame(Swapchain swapchain) = 0; @@ -1443,7 +1444,7 @@ struct Instance virtual Backend get_backend() = 0; - virtual void uninit_device(Device *device) = 0; + virtual void uninit_device(Device * device) = 0; virtual void uninit_surface(Surface surface) = 0; }; diff --git a/ashura/gpu/vulkan.cc b/ashura/gpu/vulkan.cc index 2ac00046..ab255997 100644 --- a/ashura/gpu/vulkan.cc +++ b/ashura/gpu/vulkan.cc @@ -26,13 +26,13 @@ VkResult DebugMarkerSetObjectTagEXT_Stub(VkDevice, VkResult DebugMarkerSetObjectNameEXT_Stub(VkDevice, - const VkDebugMarkerObjectNameInfoEXT *) + VkDebugMarkerObjectNameInfoEXT const *) { return VK_SUCCESS; } void CmdDebugMarkerBeginEXT_Stub(VkCommandBuffer, - const VkDebugMarkerMarkerInfoEXT *) + VkDebugMarkerMarkerInfoEXT const *) { } @@ -41,19 +41,19 @@ void CmdDebugMarkerEndEXT_Stub(VkCommandBuffer) } void CmdDebugMarkerInsertEXT_Stub(VkCommandBuffer, - const VkDebugMarkerMarkerInfoEXT *) + VkDebugMarkerMarkerInfoEXT const *) { } VkResult SetDebugUtilsObjectNameEXT_Stub(VkDevice, - const VkDebugUtilsObjectNameInfoEXT *) + VkDebugUtilsObjectNameInfoEXT const *) { return VK_SUCCESS; } bool load_instance_table(VkInstance instance, PFN_vkGetInstanceProcAddr GetInstanceProcAddr, - InstanceTable &vk_table, bool validation_enabled) + InstanceTable & vk_table, bool validation_enabled) { bool all_loaded = true; @@ -100,8 +100,8 @@ bool load_instance_table(VkInstance instance, return all_loaded; } -bool load_device_table(VkDevice dev, InstanceTable const &instance_table, - DeviceTable &vk_table, bool debug_marker_enabled) +bool load_device_table(VkDevice dev, InstanceTable const & instance_table, + DeviceTable & vk_table, bool debug_marker_enabled) { mem::zero(&vk_table, 1); bool all_loaded = true; @@ -268,8 +268,9 @@ bool load_device_table(VkDevice dev, InstanceTable const &instance_table, return all_loaded; } -void load_vma_table(InstanceTable const &instance_table, - DeviceTable const &vk_table, VmaVulkanFunctions &vma_table) +void load_vma_table(InstanceTable const & instance_table, + DeviceTable const & vk_table, + VmaVulkanFunctions & vma_table) { mem::zero(&vma_table, 1); #define SET_VMA_INST(function) vma_table.vk##function = instance_table.function @@ -298,9 +299,9 @@ void load_vma_table(InstanceTable const &instance_table, } static VkBool32 VKAPI_ATTR VKAPI_CALL - debug_callback(VkDebugUtilsMessageSeverityFlagBitsEXT message_severity, - VkDebugUtilsMessageTypeFlagsEXT message_type, - VkDebugUtilsMessengerCallbackDataEXT const *data, void *) + debug_callback(VkDebugUtilsMessageSeverityFlagBitsEXT message_severity, + VkDebugUtilsMessageTypeFlagsEXT message_type, + VkDebugUtilsMessengerCallbackDataEXT const * data, void *) { LogLevels level = LogLevels::Trace; if (message_severity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) @@ -380,10 +381,10 @@ constexpr bool has_write_access(VkAccessFlags access) VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_NV)); } -inline bool sync_buffer_state(BufferState &state, BufferAccess request, - VkBufferMemoryBarrier &barrier, - VkPipelineStageFlags &src_stages, - VkPipelineStageFlags &dst_stages) +inline bool sync_buffer_state(BufferState & state, BufferAccess request, + VkBufferMemoryBarrier & barrier, + VkPipelineStageFlags & src_stages, + VkPipelineStageFlags & dst_stages) { bool const has_write = has_write_access(request.access); bool const has_read = has_read_access(request.access); @@ -539,10 +540,10 @@ inline bool sync_buffer_state(BufferState &state, BufferAccess request, // perform reads // // if their scopes don't line-up, they won't observe the effects same -inline bool sync_image_state(ImageState &state, ImageAccess request, - VkImageMemoryBarrier &barrier, - VkPipelineStageFlags &src_stages, - VkPipelineStageFlags &dst_stages) +inline bool sync_image_state(ImageState & state, ImageAccess request, + VkImageMemoryBarrier & barrier, + VkPipelineStageFlags & src_stages, + VkPipelineStageFlags & dst_stages) { VkImageLayout const current_layout = state.access[0].layout; bool const needs_layout_transition = current_layout != request.layout; @@ -789,7 +790,7 @@ Result, Status> create_instance(AllocatorImpl allocator, return Err{(Status) result}; } - VkExtensionProperties *exts; + VkExtensionProperties * exts; if (!allocator.nalloc(num_exts, exts)) { return Err{Status::OutOfHostMemory}; @@ -818,7 +819,7 @@ Result, Status> create_instance(AllocatorImpl allocator, return Err{(Status) result}; } - VkLayerProperties *layers; + VkLayerProperties * layers; if (!allocator.nalloc(num_layers, layers)) { @@ -841,7 +842,7 @@ Result, Status> create_instance(AllocatorImpl allocator, logger->trace("Available Extensions:"); - for (VkExtensionProperties const &ext : Span{exts, num_exts}) + for (VkExtensionProperties const & ext : Span{exts, num_exts}) { logger->trace(ext.extensionName, "\t\t(spec version ", VK_API_VERSION_MAJOR(ext.specVersion), ".", @@ -852,7 +853,7 @@ Result, Status> create_instance(AllocatorImpl allocator, logger->trace("Available Layers:"); - for (VkLayerProperties const &layer : Span{layers, num_layers}) + for (VkLayerProperties const & layer : Span{layers, num_layers}) { logger->trace(layer.layerName, "\t\t(spec version ", VK_API_VERSION_MAJOR(layer.specVersion), ".", @@ -863,10 +864,10 @@ Result, Status> create_instance(AllocatorImpl allocator, ")"); } - char const *load_exts[16]; - u32 num_load_exts = 0; + char const * load_exts[16]; + u32 num_load_exts = 0; - constexpr char const *OPTIONAL_EXTS[] = {"VK_KHR_surface", + constexpr char const * OPTIONAL_EXTS[] = {"VK_KHR_surface", "VK_KHR_android_surface", "VK_MVK_ios_surface", "VK_MVK_macos_surface", @@ -912,9 +913,9 @@ Result, Status> create_instance(AllocatorImpl allocator, } } - char const *load_layers[16]; - u32 num_load_layers = 0; - bool has_validation_layer = false; + char const * load_layers[16]; + u32 num_load_layers = 0; + bool has_validation_layer = false; for (u32 i = 0; i < num_layers; i++) { @@ -1031,7 +1032,7 @@ Result, Status> create_instance(AllocatorImpl allocator, vk_instance = nullptr; - gpu::Instance *p_instance = static_cast(instance.get()); + gpu::Instance * p_instance = static_cast(instance.get()); return Ok{transmute(std::move(instance), p_instance)}; } @@ -1120,7 +1121,7 @@ Result return Err{Status::DeviceLost}; } - VkPhysicalDevice *vk_phy_devs; + VkPhysicalDevice * vk_phy_devs; if (!allocator.nalloc(num_devs, vk_phy_devs)) { @@ -1142,7 +1143,7 @@ Result CHECK(num_read_devs == num_devs); } - PhysicalDevice *physical_devs; + PhysicalDevice * physical_devs; if (!allocator.nalloc(num_devs, physical_devs)) { return Err{Status::OutOfHostMemory}; @@ -1152,7 +1153,7 @@ Result for (u32 i = 0; i < num_devs; i++) { - PhysicalDevice &dev = physical_devs[i]; + PhysicalDevice & dev = physical_devs[i]; VkPhysicalDevice vk_dev = vk_phy_devs[i]; dev.vk_phy_dev = vk_dev; vk_table.GetPhysicalDeviceFeatures(vk_dev, &dev.vk_features); @@ -1164,8 +1165,8 @@ Result logger->trace("Available Devices:"); for (u32 i = 0; i < num_devs; i++) { - PhysicalDevice const &dev = physical_devs[i]; - VkPhysicalDeviceProperties const &properties = dev.vk_properties; + PhysicalDevice const & dev = physical_devs[i]; + VkPhysicalDeviceProperties const & properties = dev.vk_properties; logger->trace("[Device: ", i, "] ", string_VkPhysicalDeviceType(properties.deviceType), " ", properties.deviceName, " Vulkan API version ", @@ -1211,7 +1212,7 @@ Result { for (u32 idev = 0; idev < num_devs && selected_dev_idx == num_devs; idev++) { - PhysicalDevice const &dev = physical_devs[idev]; + PhysicalDevice const & dev = physical_devs[idev]; u32 num_queue_families; vk_table.GetPhysicalDeviceQueueFamilyProperties( @@ -1271,7 +1272,7 @@ Result return Err{(Status) result}; } - VkExtensionProperties *exts; + VkExtensionProperties * exts; if (!allocator.nalloc(num_exts, exts)) { @@ -1300,7 +1301,7 @@ Result return Err{(Status) result}; } - VkLayerProperties *layers; + VkLayerProperties * layers; if (!allocator.nalloc(num_layers, layers)) { @@ -1324,7 +1325,7 @@ Result for (u32 i = 0; i < num_exts; i++) { - VkExtensionProperties const &ext = exts[i]; + VkExtensionProperties const & ext = exts[i]; logger->trace("\t\t", ext.extensionName, " (spec version: ", VK_API_VERSION_MAJOR(ext.specVersion), ".", VK_API_VERSION_MINOR(ext.specVersion), ".", @@ -1336,7 +1337,7 @@ Result for (u32 i = 0; i < num_layers; i++) { - VkLayerProperties const &layer = layers[i]; + VkLayerProperties const & layer = layers[i]; logger->trace("\t\t", layer.layerName, " (spec version: ", VK_API_VERSION_MAJOR(layer.specVersion), @@ -1348,7 +1349,7 @@ Result layer.implementationVersion, ")"); } - constexpr char const *required_exts[] = { + constexpr char const * required_exts[] = { VK_KHR_SWAPCHAIN_EXTENSION_NAME, VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME, VK_EXT_EXTENDED_DYNAMIC_STATE_EXTENSION_NAME, @@ -1379,8 +1380,8 @@ Result } } - char const *load_exts[16]; - u32 num_load_exts = 0; + char const * load_exts[16]; + u32 num_load_exts = 0; // optional, stubbed if (has_debug_marker_ext) @@ -1418,8 +1419,8 @@ Result } } - char const *load_layers[8]; - u32 num_load_layers = 0; + char const * load_layers[8]; + u32 num_load_layers = 0; // optional if (vk_debug_messenger != nullptr && has_validation_layer) @@ -1602,7 +1603,7 @@ Result } }}; - Device *dev; + Device * dev; if (!allocator.nalloc(1, dev)) { @@ -1643,7 +1644,7 @@ Result return Err{status}; } - Device *out = dev; + Device * out = dev; vma_allocator = nullptr; vk_dev = nullptr; dev = nullptr; @@ -1656,9 +1657,9 @@ gpu::Backend Instance::get_backend() return gpu::Backend::Vulkan; } -void Instance::uninit_device(gpu::Device *device_) +void Instance::uninit_device(gpu::Device * device_) { - Device *const dev = (Device *) device_; + Device * const dev = (Device *) device_; if (dev == nullptr) { @@ -1677,7 +1678,7 @@ void Instance::uninit_surface(gpu::Surface surface) vk_table.DestroySurfaceKHR(vk_instance, (Surface) surface, nullptr); } -void Device::set_resource_name(Span label, void const *resource, +void Device::set_resource_name(Span label, void const * resource, VkObjectType type, VkDebugReportObjectTypeEXT debug_type) { @@ -1699,7 +1700,7 @@ void Device::set_resource_name(Span label, void const *resource, vk_table.DebugMarkerSetObjectNameEXT(vk_dev, &debug_info); } -void Device::uninit_descriptor_heap(DescriptorHeap *heap) +void Device::uninit_descriptor_heap(DescriptorHeap * heap) { for (u32 i = heap->num_pools; i-- > 0;) { @@ -1712,8 +1713,8 @@ void Device::uninit_descriptor_heap(DescriptorHeap *heap) gpu::DeviceProperties Device::get_device_properties() { - VkPhysicalDeviceFeatures const &vk_features = phy_dev.vk_features; - VkPhysicalDeviceProperties const &vk_properties = phy_dev.vk_properties; + VkPhysicalDeviceFeatures const & vk_features = phy_dev.vk_features; + VkPhysicalDeviceProperties const & vk_properties = phy_dev.vk_properties; bool has_uma = false; for (u32 i = 0; i < phy_dev.vk_memory_properties.memoryTypeCount; i++) @@ -1747,7 +1748,8 @@ gpu::DeviceProperties Device::get_device_properties() .max_compute_work_group_invocations = vk_properties.limits.maxComputeWorkGroupInvocations, .max_compute_shared_memory_size = - vk_properties.limits.maxComputeSharedMemorySize}; + vk_properties.limits.maxComputeSharedMemorySize + }; mem::copy(Span{vk_properties.limits.maxComputeWorkGroupCount, 3}, properties.max_compute_work_group_count); @@ -1771,7 +1773,7 @@ Result .buffer_features = (gpu::FormatFeatures) props.bufferFeatures}); } -Result Device::create_buffer(gpu::BufferInfo const &info) +Result Device::create_buffer(gpu::BufferInfo const & info) { CHECK(info.size != 0); CHECK(info.usage != gpu::BufferUsage::None); @@ -1810,7 +1812,7 @@ Result Device::create_buffer(gpu::BufferInfo const &info) set_resource_name(info.label, vk_buffer, VK_OBJECT_TYPE_BUFFER, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT); - Buffer *buffer; + Buffer * buffer; if (!allocator.nalloc(1, buffer)) { vmaDestroyBuffer(vma_allocator, vk_buffer, vma_allocation); @@ -1824,9 +1826,9 @@ Result Device::create_buffer(gpu::BufferInfo const &info) } Result - Device::create_buffer_view(gpu::BufferViewInfo const &info) + Device::create_buffer_view(gpu::BufferViewInfo const & info) { - Buffer *const buffer = (Buffer *) info.buffer; + Buffer * const buffer = (Buffer *) info.buffer; CHECK(buffer != nullptr); CHECK(has_any_bit(buffer->info.usage, @@ -1860,7 +1862,7 @@ Result set_resource_name(info.label, vk_view, VK_OBJECT_TYPE_BUFFER_VIEW, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_VIEW_EXT); - BufferView *view; + BufferView * view; if (!allocator.nalloc(1, view)) { @@ -1875,7 +1877,7 @@ Result return Ok{(gpu::BufferView) view}; } -Result Device::create_image(gpu::ImageInfo const &info) +Result Device::create_image(gpu::ImageInfo const & info) { CHECK(info.format != gpu::Format::Undefined); CHECK(info.usage != gpu::ImageUsage::None); @@ -1913,24 +1915,25 @@ Result Device::create_image(gpu::ImageInfo const &info) break; } - VkImageCreateInfo create_info{.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, - .pNext = nullptr, - .flags = 0, - .imageType = (VkImageType) info.type, - .format = (VkFormat) info.format, - .extent = VkExtent3D{.width = info.extent.x, - .height = info.extent.y, - .depth = info.extent.z}, - .mipLevels = info.mip_levels, - .arrayLayers = info.array_layers, - .samples = - (VkSampleCountFlagBits) info.sample_count, - .tiling = VK_IMAGE_TILING_OPTIMAL, - .usage = (VkImageUsageFlags) info.usage, - .sharingMode = VK_SHARING_MODE_EXCLUSIVE, - .queueFamilyIndexCount = 0, - .pQueueFamilyIndices = nullptr, - .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED}; + VkImageCreateInfo create_info{ + .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, + .pNext = nullptr, + .flags = 0, + .imageType = (VkImageType) info.type, + .format = (VkFormat) info.format, + .extent = VkExtent3D{.width = info.extent.x, + .height = info.extent.y, + .depth = info.extent.z}, + .mipLevels = info.mip_levels, + .arrayLayers = info.array_layers, + .samples = (VkSampleCountFlagBits) info.sample_count, + .tiling = VK_IMAGE_TILING_OPTIMAL, + .usage = (VkImageUsageFlags) info.usage, + .sharingMode = VK_SHARING_MODE_EXCLUSIVE, + .queueFamilyIndexCount = 0, + .pQueueFamilyIndices = nullptr, + .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED + }; VmaAllocationCreateInfo vma_allocation_create_info{ .flags = 0, .usage = VMA_MEMORY_USAGE_AUTO, @@ -1955,7 +1958,7 @@ Result Device::create_image(gpu::ImageInfo const &info) set_resource_name(info.label, vk_image, VK_OBJECT_TYPE_IMAGE, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT); - Image *image; + Image * image; if (!allocator.nalloc(1, image)) { @@ -1982,9 +1985,9 @@ Result Device::create_image(gpu::ImageInfo const &info) } Result - Device::create_image_view(gpu::ImageViewInfo const &info) + Device::create_image_view(gpu::ImageViewInfo const & info) { - Image *const src_image = (Image *) info.image; + Image * const src_image = (Image *) info.image; CHECK(info.image != nullptr); CHECK(info.view_format != gpu::Format::Undefined); @@ -2016,11 +2019,12 @@ Result .b = (VkComponentSwizzle) info.mapping.b, .a = (VkComponentSwizzle) info.mapping.a}, .subresourceRange = VkImageSubresourceRange{ - .aspectMask = (VkImageAspectFlags) info.aspects, - .baseMipLevel = info.first_mip_level, - .levelCount = info.num_mip_levels, - .baseArrayLayer = info.first_array_layer, - .layerCount = info.num_array_layers}}; + .aspectMask = (VkImageAspectFlags) info.aspects, + .baseMipLevel = info.first_mip_level, + .levelCount = info.num_mip_levels, + .baseArrayLayer = info.first_array_layer, + .layerCount = info.num_array_layers} + }; VkImageView vk_view; VkResult result = @@ -2033,7 +2037,7 @@ Result set_resource_name(info.label, vk_view, VK_OBJECT_TYPE_IMAGE_VIEW, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT); - ImageView *view; + ImageView * view; if (!allocator.nalloc(1, view)) { vk_table.DestroyImageView(vk_dev, vk_view, nullptr); @@ -2049,7 +2053,7 @@ Result } Result - Device::create_sampler(gpu::SamplerInfo const &info) + Device::create_sampler(gpu::SamplerInfo const & info) { CHECK(!(info.anisotropy_enable && (info.max_anisotropy > gpu::MAX_SAMPLER_ANISOTROPY))); @@ -2089,7 +2093,7 @@ Result return Ok{(gpu::Sampler) vk_sampler}; } -Result Device::create_shader(gpu::ShaderInfo const &info) +Result Device::create_shader(gpu::ShaderInfo const & info) { CHECK(info.spirv_code.size_bytes() > 0); @@ -2115,14 +2119,14 @@ Result Device::create_shader(gpu::ShaderInfo const &info) } Result Device::create_descriptor_set_layout( - gpu::DescriptorSetLayoutInfo const &info) + gpu::DescriptorSetLayoutInfo const & info) { u32 const num_bindings = info.bindings.size32(); u32 num_descriptors = 0; u32 num_variable_length = 0; u32 sizing[NUM_DESCRIPTOR_TYPES] = {}; - for (gpu::DescriptorBindingInfo const &info : info.bindings) + for (gpu::DescriptorBindingInfo const & info : info.bindings) { num_descriptors += info.count; sizing[(u32) info.type] += info.count; @@ -2159,8 +2163,8 @@ Result Device::create_descriptor_set_layout( for (u32 i = 0; i < num_bindings; i++) { - gpu::DescriptorBindingInfo const &binding = info.bindings[i]; - VkShaderStageFlags stage_flags = + gpu::DescriptorBindingInfo const & binding = info.bindings[i]; + VkShaderStageFlags stage_flags = (VkShaderStageFlags) (binding.type == gpu::DescriptorType::InputAttachment ? VK_SHADER_STAGE_FRAGMENT_BIT : @@ -2214,7 +2218,7 @@ Result Device::create_descriptor_set_layout( set_resource_name(info.label, vk_layout, VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT); - DescriptorSetLayout *layout; + DescriptorSetLayout * layout; if (!allocator.nalloc(1, layout)) { return Err{Status::OutOfHostMemory}; @@ -2235,8 +2239,8 @@ Result Device::create_descriptor_set(gpu::DescriptorSetLayout layout_, Span variable_lengths) { - DescriptorSetLayout *const layout = (DescriptorSetLayout *) layout_; - DescriptorHeap &heap = descriptor_heap; + DescriptorSetLayout * const layout = (DescriptorSetLayout *) layout_; + DescriptorHeap & heap = descriptor_heap; CHECK(variable_lengths.size() == layout->num_variable_length); { @@ -2258,8 +2262,8 @@ Result u32 vla_idx = 0; for (u32 i = 0; i < layout->num_bindings; i++) { - gpu::DescriptorBindingInfo const &info = layout->bindings[i]; - u32 count = 0; + gpu::DescriptorBindingInfo const & info = layout->bindings[i]; + u32 count = 0; if (!info.is_variable_length) { count = info.count; @@ -2324,7 +2328,7 @@ Result return Err{Status::OutOfHostMemory}; } - DescriptorPool *pool = heap.pools + heap.num_pools; + DescriptorPool * pool = heap.pools + heap.num_pools; fill(pool->avail, heap.pool_size); pool->vk_pool = vk_pool; @@ -2348,9 +2352,9 @@ Result for (; num_bindings < layout->num_bindings; num_bindings++) { - gpu::DescriptorBindingInfo const &info = layout->bindings[num_bindings]; - void **sync_resources = nullptr; - u32 count = bindings_sizes[num_bindings]; + gpu::DescriptorBindingInfo const & info = layout->bindings[num_bindings]; + void ** sync_resources = nullptr; + u32 count = bindings_sizes[num_bindings]; switch (info.type) { @@ -2409,7 +2413,7 @@ Result heap.pools[ipool].avail[i] -= descriptor_usage[i]; } - DescriptorSet *set; + DescriptorSet * set; if (!heap.allocator.nalloc(1, set)) { @@ -2426,7 +2430,7 @@ Result } Result - Device::create_pipeline_cache(gpu::PipelineCacheInfo const &info) + Device::create_pipeline_cache(gpu::PipelineCacheInfo const & info) { VkPipelineCacheCreateInfo create_info{ .sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, @@ -2450,7 +2454,7 @@ Result } Result - Device::create_compute_pipeline(gpu::ComputePipelineInfo const &info) + Device::create_compute_pipeline(gpu::ComputePipelineInfo const & info) { u32 const num_descriptor_sets = info.descriptor_set_layouts.size32(); @@ -2537,7 +2541,7 @@ Result set_resource_name(info.label, vk_layout, VK_OBJECT_TYPE_PIPELINE_LAYOUT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT); - ComputePipeline *pipeline; + ComputePipeline * pipeline; if (!allocator.nalloc(1, pipeline)) { vk_table.DestroyPipelineLayout(vk_dev, vk_layout, nullptr); @@ -2555,7 +2559,7 @@ Result } Result - Device::create_graphics_pipeline(gpu::GraphicsPipelineInfo const &info) + Device::create_graphics_pipeline(gpu::GraphicsPipelineInfo const & info) { u32 const num_descriptor_sets = info.descriptor_set_layouts.size32(); u32 const num_input_bindings = info.vertex_input_bindings.size32(); @@ -2620,7 +2624,8 @@ Result .stage = VK_SHADER_STAGE_FRAGMENT_BIT, .module = (Shader) info.fragment_shader.shader, .pName = fs_entry_point, - .pSpecializationInfo = &vk_fs_specialization}}; + .pSpecializationInfo = &vk_fs_specialization} + }; VkPushConstantRange push_constants_range{.stageFlags = VK_SHADER_STAGE_ALL, .offset = 0, @@ -2648,7 +2653,7 @@ Result VkVertexInputBindingDescription input_bindings[gpu::MAX_VERTEX_ATTRIBUTES]; for (u32 ibinding = 0; ibinding < num_input_bindings; ibinding++) { - gpu::VertexInputBinding const &binding = + gpu::VertexInputBinding const & binding = info.vertex_input_bindings[ibinding]; input_bindings[ibinding] = VkVertexInputBindingDescription{ .binding = binding.binding, @@ -2659,7 +2664,7 @@ Result VkVertexInputAttributeDescription attributes[gpu::MAX_VERTEX_ATTRIBUTES]; for (u32 iattribute = 0; iattribute < num_attributes; iattribute++) { - gpu::VertexAttribute const &attribute = info.vertex_attributes[iattribute]; + gpu::VertexAttribute const & attribute = info.vertex_attributes[iattribute]; attributes[iattribute] = VkVertexInputAttributeDescription{.location = attribute.location, .binding = attribute.binding, @@ -2685,7 +2690,10 @@ Result VkViewport viewport{ .x = 0, .y = 0, .width = 0, .height = 0, .minDepth = 0, .maxDepth = 1}; - VkRect2D scissor{.offset = {0, 0}, .extent = {0, 0}}; + VkRect2D scissor{ + .offset = {0, 0}, + .extent = {0, 0} + }; VkPipelineViewportStateCreateInfo viewport_state{ .sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO, @@ -2738,40 +2746,41 @@ Result (VkBool32) info.depth_stencil_state.stencil_test_enable, .front = VkStencilOpState{ - .failOp = + .failOp = (VkStencilOp) info.depth_stencil_state.front_stencil.fail_op, - .passOp = + .passOp = (VkStencilOp) info.depth_stencil_state.front_stencil.pass_op, - .depthFailOp = (VkStencilOp) info.depth_stencil_state + .depthFailOp = (VkStencilOp) info.depth_stencil_state .front_stencil.depth_fail_op, - .compareOp = (VkCompareOp) info.depth_stencil_state.front_stencil + .compareOp = (VkCompareOp) info.depth_stencil_state.front_stencil .compare_op, - .compareMask = + .compareMask = info.depth_stencil_state.front_stencil.compare_mask, - .writeMask = info.depth_stencil_state.front_stencil.write_mask, - .reference = info.depth_stencil_state.front_stencil.reference}, + .writeMask = info.depth_stencil_state.front_stencil.write_mask, + .reference = info.depth_stencil_state.front_stencil.reference }, .back = VkStencilOpState{ - .failOp = + .failOp = (VkStencilOp) info.depth_stencil_state.back_stencil.fail_op, - .passOp = + .passOp = (VkStencilOp) info.depth_stencil_state.back_stencil.pass_op, - .depthFailOp = (VkStencilOp) info.depth_stencil_state.back_stencil + .depthFailOp = (VkStencilOp) info.depth_stencil_state.back_stencil .depth_fail_op, - .compareOp = (VkCompareOp) + .compareOp = (VkCompareOp) info.depth_stencil_state.back_stencil.compare_op, - .compareMask = info.depth_stencil_state.back_stencil.compare_mask, - .writeMask = info.depth_stencil_state.back_stencil.write_mask, - .reference = info.depth_stencil_state.back_stencil.reference}, + .compareMask = info.depth_stencil_state.back_stencil.compare_mask, + .writeMask = info.depth_stencil_state.back_stencil.write_mask, + .reference = info.depth_stencil_state.back_stencil.reference}, .minDepthBounds = info.depth_stencil_state.min_depth_bounds, - .maxDepthBounds = info.depth_stencil_state.max_depth_bounds}; + .maxDepthBounds = info.depth_stencil_state.max_depth_bounds + }; VkPipelineColorBlendAttachmentState attachment_states[gpu::MAX_PIPELINE_COLOR_ATTACHMENTS]; for (u32 i = 0; i < num_blend_color_attachments; i++) { - gpu::ColorBlendAttachmentState const &state = + gpu::ColorBlendAttachmentState const & state = info.color_blend_state.attachments[i]; attachment_states[i] = VkPipelineColorBlendAttachmentState{ .blendEnable = (VkBool32) state.blend_enable, @@ -2795,7 +2804,8 @@ Result .blendConstants = {info.color_blend_state.blend_constant.x, info.color_blend_state.blend_constant.y, info.color_blend_state.blend_constant.z, - info.color_blend_state.blend_constant.w}}; + info.color_blend_state.blend_constant.w} + }; constexpr VkDynamicState dynamic_states[] = { VK_DYNAMIC_STATE_VIEWPORT, @@ -2880,7 +2890,7 @@ Result set_resource_name(info.label, vk_layout, VK_OBJECT_TYPE_PIPELINE_LAYOUT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT); - GraphicsPipeline *pipeline; + GraphicsPipeline * pipeline; if (!allocator.nalloc(1, pipeline)) { vk_table.DestroyPipelineLayout(vk_dev, vk_layout, nullptr); @@ -2906,7 +2916,7 @@ Result /// old swapchain will be retired and destroyed irregardless of whether new /// swapchain recreation fails. -VkResult Device::recreate_swapchain(Swapchain *swapchain) +VkResult Device::recreate_swapchain(Swapchain * swapchain) { CHECK(swapchain->info.preferred_extent.x > 0); CHECK(swapchain->info.preferred_extent.y > 0); @@ -2956,8 +2966,8 @@ VkResult Device::recreate_swapchain(Swapchain *swapchain) VkExtent2D vk_extent; - if (surface_capabilities.currentExtent.width == 0xFFFFFFFFU && - surface_capabilities.currentExtent.height == 0xFFFFFFFFU) + if (surface_capabilities.currentExtent.width == 0xFFFF'FFFFU && + surface_capabilities.currentExtent.height == 0xFFFF'FFFFU) { vk_extent.width = clamp(swapchain->info.preferred_extent.x, surface_capabilities.minImageExtent.width, @@ -3048,7 +3058,8 @@ VkResult Device::recreate_swapchain(Swapchain *swapchain) .vma_allocation = nullptr, .vma_allocation_info = {}, .states = {}, - .num_aspects = 1}; + .num_aspects = 1 + }; swapchain->images[i] = (gpu::Image)(swapchain->image_impls + i); } @@ -3079,7 +3090,7 @@ VkResult Device::recreate_swapchain(Swapchain *swapchain) return VK_SUCCESS; } -Status Device::init_command_encoder(CommandEncoder *enc) +Status Device::init_command_encoder(CommandEncoder * enc) { VkCommandPoolCreateInfo command_pool_create_info{ .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, @@ -3135,7 +3146,7 @@ Status Device::init_command_encoder(CommandEncoder *enc) return Status::Success; } -void Device::uninit_command_encoder(CommandEncoder *enc) +void Device::uninit_command_encoder(CommandEncoder * enc) { enc->render_ctx.commands.reset(); vk_table.DestroyCommandPool(vk_dev, enc->vk_command_pool, nullptr); @@ -3143,15 +3154,15 @@ void Device::uninit_command_encoder(CommandEncoder *enc) Status Device::init_frame_context(u32 buffering) { - FrameContext &ctx = frame_ctx; - ctx.tail_frame = 0; - ctx.current_frame = 0; - ctx.ring_index = 0; - ctx.tail_frame = 0; - u32 num_encs = 0; - u32 num_acquire_s = 0; - u32 num_submit_f = 0; - u32 num_submit_s = 0; + FrameContext & ctx = frame_ctx; + ctx.tail_frame = 0; + ctx.current_frame = 0; + ctx.ring_index = 0; + ctx.tail_frame = 0; + u32 num_encs = 0; + u32 num_acquire_s = 0; + u32 num_submit_f = 0; + u32 num_submit_s = 0; defer encs_{[&] { for (u32 i = num_encs; i-- > 0;) @@ -3276,13 +3287,13 @@ void Device::uninit_frame_context() } Result - Device::create_swapchain(gpu::Surface surface, - gpu::SwapchainInfo const &info) + Device::create_swapchain(gpu::Surface surface, + gpu::SwapchainInfo const & info) { CHECK(info.preferred_extent.x > 0); CHECK(info.preferred_extent.y > 0); - Swapchain *swapchain; + Swapchain * swapchain; if (!allocator.nalloc(1, swapchain)) { return Err{Status::OutOfHostMemory}; @@ -3366,7 +3377,7 @@ Result Device::create_statistics_query() void Device::uninit_buffer(gpu::Buffer buffer_) { - Buffer *const buffer = (Buffer *) buffer_; + Buffer * const buffer = (Buffer *) buffer_; if (buffer == nullptr) { @@ -3379,7 +3390,7 @@ void Device::uninit_buffer(gpu::Buffer buffer_) void Device::uninit_buffer_view(gpu::BufferView buffer_view_) { - BufferView *const buffer_view = (BufferView *) buffer_view_; + BufferView * const buffer_view = (BufferView *) buffer_view_; if (buffer_view == nullptr) { @@ -3392,7 +3403,7 @@ void Device::uninit_buffer_view(gpu::BufferView buffer_view_) void Device::uninit_image(gpu::Image image_) { - Image *const image = (Image *) image_; + Image * const image = (Image *) image_; if (image == nullptr) { @@ -3407,7 +3418,7 @@ void Device::uninit_image(gpu::Image image_) void Device::uninit_image_view(gpu::ImageView image_view_) { - ImageView *const image_view = (ImageView *) image_view_; + ImageView * const image_view = (ImageView *) image_view_; if (image_view == nullptr) { @@ -3430,7 +3441,7 @@ void Device::uninit_shader(gpu::Shader shader_) void Device::uninit_descriptor_set_layout(gpu::DescriptorSetLayout layout_) { - DescriptorSetLayout *const layout = (DescriptorSetLayout *) layout_; + DescriptorSetLayout * const layout = (DescriptorSetLayout *) layout_; if (layout == nullptr) { @@ -3443,16 +3454,16 @@ void Device::uninit_descriptor_set_layout(gpu::DescriptorSetLayout layout_) void Device::uninit_descriptor_set(gpu::DescriptorSet set_) { - DescriptorSet *const set = (DescriptorSet *) set_; - DescriptorHeap &heap = descriptor_heap; + DescriptorSet * const set = (DescriptorSet *) set_; + DescriptorHeap & heap = descriptor_heap; if (set == nullptr) { return; } - DescriptorPool *pool = heap.pools + set->pool; - VkResult result = + DescriptorPool * pool = heap.pools + set->pool; + VkResult result = vk_table.FreeDescriptorSets(vk_dev, pool->vk_pool, 1, &set->vk_set); CHECK(result == VK_SUCCESS); @@ -3480,7 +3491,7 @@ void Device::uninit_pipeline_cache(gpu::PipelineCache cache_) void Device::uninit_compute_pipeline(gpu::ComputePipeline pipeline_) { - ComputePipeline *const pipeline = (ComputePipeline *) pipeline_; + ComputePipeline * const pipeline = (ComputePipeline *) pipeline_; if (pipeline == nullptr) { @@ -3494,7 +3505,7 @@ void Device::uninit_compute_pipeline(gpu::ComputePipeline pipeline_) void Device::uninit_graphics_pipeline(gpu::GraphicsPipeline pipeline_) { - GraphicsPipeline *const pipeline = (GraphicsPipeline *) pipeline_; + GraphicsPipeline * const pipeline = (GraphicsPipeline *) pipeline_; if (pipeline == nullptr) { @@ -3508,7 +3519,7 @@ void Device::uninit_graphics_pipeline(gpu::GraphicsPipeline pipeline_) void Device::uninit_swapchain(gpu::Swapchain swapchain_) { - Swapchain *const swapchain = (Swapchain *) swapchain_; + Swapchain * const swapchain = (Swapchain *) swapchain_; if (swapchain == nullptr) { @@ -3535,20 +3546,21 @@ void Device::uninit_statistics_query(gpu::StatisticsQuery query_) gpu::FrameContext Device::get_frame_context() { - return gpu::FrameContext{.buffering = frame_ctx.buffering, - .tail = frame_ctx.tail_frame, - .current = frame_ctx.current_frame, - .encoders = - Span{frame_ctx.encs_impl, frame_ctx.buffering}, - .ring_index = frame_ctx.ring_index}; + return gpu::FrameContext{ + .buffering = frame_ctx.buffering, + .tail = frame_ctx.tail_frame, + .current = frame_ctx.current_frame, + .encoders = Span{frame_ctx.encs_impl, frame_ctx.buffering}, + .ring_index = frame_ctx.ring_index + }; } Result Device::map_buffer_memory(gpu::Buffer buffer_) { - Buffer *const buffer = (Buffer *) buffer_; + Buffer * const buffer = (Buffer *) buffer_; CHECK(buffer->info.host_mapped); - void *map; + void * map; VkResult result = vmaMapMemory(vma_allocator, buffer->vma_allocation, &map); if (result != VK_SUCCESS) { @@ -3560,7 +3572,7 @@ Result Device::map_buffer_memory(gpu::Buffer buffer_) void Device::unmap_buffer_memory(gpu::Buffer buffer_) { - Buffer *const buffer = (Buffer *) buffer_; + Buffer * const buffer = (Buffer *) buffer_; CHECK(buffer->info.host_mapped); @@ -3571,7 +3583,7 @@ Result Device::invalidate_mapped_buffer_memory(gpu::Buffer buffer_, gpu::MemoryRange range) { - Buffer *const buffer = (Buffer *) buffer_; + Buffer * const buffer = (Buffer *) buffer_; CHECK(buffer->info.host_mapped); CHECK(range.offset < buffer->info.size); @@ -3590,7 +3602,7 @@ Result Result Device::flush_mapped_buffer_memory(gpu::Buffer buffer_, gpu::MemoryRange range) { - Buffer *const buffer = (Buffer *) buffer_; + Buffer * const buffer = (Buffer *) buffer_; CHECK(buffer->info.host_mapped); CHECK(range.offset < buffer->info.size); @@ -3620,7 +3632,7 @@ Result Device::get_pipeline_cache_size(gpu::PipelineCache cache) } Result Device::get_pipeline_cache_data(gpu::PipelineCache cache, - Vec &out) + Vec & out) { usize size = 0; @@ -3674,17 +3686,17 @@ Result return Ok{Void{}}; } -void Device::update_descriptor_set(gpu::DescriptorSetUpdate const &update) +void Device::update_descriptor_set(gpu::DescriptorSetUpdate const & update) { - DescriptorHeap *const heap = &descriptor_heap; - DescriptorSet *const set = (DescriptorSet *) update.set; - u64 const ubo_offset_alignment = + DescriptorHeap * const heap = &descriptor_heap; + DescriptorSet * const set = (DescriptorSet *) update.set; + u64 const ubo_offset_alignment = phy_dev.vk_properties.limits.minUniformBufferOffsetAlignment; u64 const ssbo_offset_alignment = phy_dev.vk_properties.limits.minStorageBufferOffsetAlignment; CHECK(update.binding < set->num_bindings); - DescriptorBinding &binding = set->bindings[update.binding]; + DescriptorBinding & binding = set->bindings[update.binding]; CHECK(update.element < binding.count); usize info_size = 0; u32 count = 0; @@ -3695,8 +3707,8 @@ void Device::update_descriptor_set(gpu::DescriptorSetUpdate const &update) case gpu::DescriptorType::StorageBuffer: for (u32 i = 0; i < update.buffers.size(); i++) { - gpu::BufferBinding const &b = update.buffers[i]; - Buffer *buffer = (Buffer *) b.buffer; + gpu::BufferBinding const & b = update.buffers[i]; + Buffer * buffer = (Buffer *) b.buffer; if (buffer != nullptr) { CHECK(has_bits(buffer->info.usage, gpu::BufferUsage::StorageBuffer)); @@ -3710,8 +3722,8 @@ void Device::update_descriptor_set(gpu::DescriptorSetUpdate const &update) case gpu::DescriptorType::UniformBuffer: for (u32 i = 0; i < update.buffers.size(); i++) { - gpu::BufferBinding const &b = update.buffers[i]; - Buffer *buffer = (Buffer *) b.buffer; + gpu::BufferBinding const & b = update.buffers[i]; + Buffer * buffer = (Buffer *) b.buffer; if (buffer != nullptr) { CHECK(has_bits(buffer->info.usage, gpu::BufferUsage::UniformBuffer)); @@ -3730,10 +3742,10 @@ void Device::update_descriptor_set(gpu::DescriptorSetUpdate const &update) { for (u32 i = 0; i < update.images.size(); i++) { - ImageView *view = (ImageView *) update.images[i].image_view; + ImageView * view = (ImageView *) update.images[i].image_view; if (view != nullptr) { - Image *image = (Image *) view->info.image; + Image * image = (Image *) view->info.image; CHECK(has_bits(image->info.usage, gpu::ImageUsage::Sampled)); } } @@ -3744,10 +3756,10 @@ void Device::update_descriptor_set(gpu::DescriptorSetUpdate const &update) { for (u32 i = 0; i < update.images.size(); i++) { - ImageView *view = (ImageView *) update.images[i].image_view; + ImageView * view = (ImageView *) update.images[i].image_view; if (view != nullptr) { - Image *image = (Image *) view->info.image; + Image * image = (Image *) view->info.image; CHECK(has_bits(image->info.usage, gpu::ImageUsage::Storage)); } } @@ -3757,10 +3769,10 @@ void Device::update_descriptor_set(gpu::DescriptorSetUpdate const &update) case gpu::DescriptorType::StorageTexelBuffer: for (u32 i = 0; i < update.texel_buffers.size(); i++) { - BufferView *view = (BufferView *) update.texel_buffers[i]; + BufferView * view = (BufferView *) update.texel_buffers[i]; if (view != nullptr) { - Buffer *buffer = (Buffer *) view->info.buffer; + Buffer * buffer = (Buffer *) view->info.buffer; CHECK(has_bits(buffer->info.usage, gpu::BufferUsage::StorageTexelBuffer)); } @@ -3770,10 +3782,10 @@ void Device::update_descriptor_set(gpu::DescriptorSetUpdate const &update) case gpu::DescriptorType::UniformTexelBuffer: for (u32 i = 0; i < update.texel_buffers.size(); i++) { - BufferView *view = (BufferView *) update.texel_buffers[i]; + BufferView * view = (BufferView *) update.texel_buffers[i]; if (view != nullptr) { - Buffer *buffer = (Buffer *) view->info.buffer; + Buffer * buffer = (Buffer *) view->info.buffer; CHECK(has_bits(buffer->info.usage, gpu::BufferUsage::UniformTexelBuffer)); } @@ -3828,9 +3840,9 @@ void Device::update_descriptor_set(gpu::DescriptorSetUpdate const &update) heap->scratch_size = info_size; } - VkDescriptorImageInfo *pImageInfo = nullptr; - VkDescriptorBufferInfo *pBufferInfo = nullptr; - VkBufferView *pTexelBufferView = nullptr; + VkDescriptorImageInfo * pImageInfo = nullptr; + VkDescriptorBufferInfo * pBufferInfo = nullptr; + VkBufferView * pTexelBufferView = nullptr; switch (binding.type) { @@ -3842,12 +3854,12 @@ void Device::update_descriptor_set(gpu::DescriptorSetUpdate const &update) pBufferInfo = (VkDescriptorBufferInfo *) heap->scratch; for (u32 i = 0; i < update.buffers.size(); i++) { - gpu::BufferBinding const &b = update.buffers[i]; - Buffer *buffer = (Buffer *) b.buffer; - pBufferInfo[i] = VkDescriptorBufferInfo{ - .buffer = (buffer == nullptr) ? nullptr : buffer->vk_buffer, - .offset = b.offset, - .range = b.size}; + gpu::BufferBinding const & b = update.buffers[i]; + Buffer * buffer = (Buffer *) b.buffer; + pBufferInfo[i] = VkDescriptorBufferInfo{ + .buffer = (buffer == nullptr) ? nullptr : buffer->vk_buffer, + .offset = b.offset, + .range = b.size}; } } break; @@ -3870,11 +3882,11 @@ void Device::update_descriptor_set(gpu::DescriptorSetUpdate const &update) pImageInfo = (VkDescriptorImageInfo *) heap->scratch; for (u32 i = 0; i < update.images.size(); i++) { - ImageView *view = (ImageView *) update.images[i].image_view; - pImageInfo[i] = VkDescriptorImageInfo{ - .sampler = nullptr, - .imageView = (view == nullptr) ? nullptr : view->vk_view, - .imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}; + ImageView * view = (ImageView *) update.images[i].image_view; + pImageInfo[i] = VkDescriptorImageInfo{ + .sampler = nullptr, + .imageView = (view == nullptr) ? nullptr : view->vk_view, + .imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}; } } break; @@ -3884,12 +3896,12 @@ void Device::update_descriptor_set(gpu::DescriptorSetUpdate const &update) pImageInfo = (VkDescriptorImageInfo *) heap->scratch; for (u32 i = 0; i < update.images.size(); i++) { - gpu::ImageBinding const &b = update.images[i]; - ImageView *view = (ImageView *) b.image_view; - pImageInfo[i] = VkDescriptorImageInfo{ - .sampler = (Sampler) b.sampler, - .imageView = (view == nullptr) ? nullptr : view->vk_view, - .imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}; + gpu::ImageBinding const & b = update.images[i]; + ImageView * view = (ImageView *) b.image_view; + pImageInfo[i] = VkDescriptorImageInfo{ + .sampler = (Sampler) b.sampler, + .imageView = (view == nullptr) ? nullptr : view->vk_view, + .imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}; } } break; @@ -3899,11 +3911,11 @@ void Device::update_descriptor_set(gpu::DescriptorSetUpdate const &update) pImageInfo = (VkDescriptorImageInfo *) heap->scratch; for (u32 i = 0; i < update.images.size(); i++) { - ImageView *view = (ImageView *) update.images[i].image_view; - pImageInfo[i] = VkDescriptorImageInfo{ - .sampler = nullptr, - .imageView = (view == nullptr) ? nullptr : view->vk_view, - .imageLayout = VK_IMAGE_LAYOUT_GENERAL}; + ImageView * view = (ImageView *) update.images[i].image_view; + pImageInfo[i] = VkDescriptorImageInfo{ + .sampler = nullptr, + .imageView = (view == nullptr) ? nullptr : view->vk_view, + .imageLayout = VK_IMAGE_LAYOUT_GENERAL}; } } break; @@ -3913,11 +3925,11 @@ void Device::update_descriptor_set(gpu::DescriptorSetUpdate const &update) pImageInfo = (VkDescriptorImageInfo *) heap->scratch; for (u32 i = 0; i < update.images.size(); i++) { - ImageView *view = (ImageView *) update.images[i].image_view; - pImageInfo[i] = VkDescriptorImageInfo{ - .sampler = nullptr, - .imageView = (view == nullptr) ? nullptr : view->vk_view, - .imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}; + ImageView * view = (ImageView *) update.images[i].image_view; + pImageInfo[i] = VkDescriptorImageInfo{ + .sampler = nullptr, + .imageView = (view == nullptr) ? nullptr : view->vk_view, + .imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}; } } break; @@ -3928,7 +3940,7 @@ void Device::update_descriptor_set(gpu::DescriptorSetUpdate const &update) pTexelBufferView = (VkBufferView *) heap->scratch; for (u32 i = 0; i < update.texel_buffers.size(); i++) { - BufferView *view = (BufferView *) update.texel_buffers[i]; + BufferView * view = (BufferView *) update.texel_buffers[i]; pTexelBufferView[i] = (view == nullptr) ? nullptr : view->vk_view; } } @@ -3969,7 +3981,7 @@ void Device::update_descriptor_set(gpu::DescriptorSetUpdate const &update) case gpu::DescriptorType::UniformTexelBuffer: for (u32 i = 0; i < update.texel_buffers.size(); i++) { - BufferView *view = (BufferView *) update.texel_buffers[i]; + BufferView * view = (BufferView *) update.texel_buffers[i]; binding.buffers[update.element + i] = (view == nullptr) ? nullptr : (Buffer *) view->info.buffer; } @@ -3983,7 +3995,7 @@ void Device::update_descriptor_set(gpu::DescriptorSetUpdate const &update) case gpu::DescriptorType::InputAttachment: for (u32 i = 0; i < update.images.size(); i++) { - ImageView *view = (ImageView *) update.images[i].image_view; + ImageView * view = (ImageView *) update.images[i].image_view; binding.images[update.element + i] = (view == nullptr) ? nullptr : (Image *) view->info.image; } @@ -4017,8 +4029,8 @@ Result Device::wait_queue_idle() } Result - Device::get_surface_formats(gpu::Surface surface_, - Vec &formats) + Device::get_surface_formats(gpu::Surface surface_, + Vec & formats) { VkSurfaceKHR const surface = (VkSurfaceKHR) surface_; @@ -4031,7 +4043,7 @@ Result return Err{(Status) result}; } - VkSurfaceFormatKHR *vk_formats; + VkSurfaceFormatKHR * vk_formats; if (!allocator.nalloc(num_supported, vk_formats)) { return Err{Status::OutOfHostMemory}; @@ -4070,8 +4082,8 @@ Result } Result - Device::get_surface_present_modes(gpu::Surface surface_, - Vec &modes) + Device::get_surface_present_modes(gpu::Surface surface_, + Vec & modes) { VkSurfaceKHR const surface = (VkSurfaceKHR) surface_; @@ -4084,7 +4096,7 @@ Result return Err{(Status) result}; } - VkPresentModeKHR *vk_present_modes; + VkPresentModeKHR * vk_present_modes; if (!allocator.nalloc(num_supported, vk_present_modes)) { return Err{Status::OutOfHostMemory}; @@ -4134,21 +4146,24 @@ Result return Err{(Status) result}; } - return Ok{gpu::SurfaceCapabilities{ - .image_usage = (gpu::ImageUsage) capabilities.supportedUsageFlags, - .composite_alpha = - (gpu::CompositeAlpha) capabilities.supportedCompositeAlpha}}; + return Ok{ + gpu::SurfaceCapabilities{ + .image_usage = (gpu::ImageUsage) capabilities.supportedUsageFlags, + .composite_alpha = + (gpu::CompositeAlpha) capabilities.supportedCompositeAlpha} + }; } Result Device::get_swapchain_state(gpu::Swapchain swapchain_) { - Swapchain *const swapchain = (Swapchain *) swapchain_; + Swapchain * const swapchain = (Swapchain *) swapchain_; - gpu::SwapchainState state{.extent = swapchain->extent, - .format = swapchain->info.format, - .images = - Span{swapchain->images, swapchain->num_images}}; + gpu::SwapchainState state{ + .extent = swapchain->extent, + .format = swapchain->info.format, + .images = Span{swapchain->images, swapchain->num_images} + }; if (swapchain->is_zero_sized) { @@ -4162,23 +4177,23 @@ Result } Result - Device::invalidate_swapchain(gpu::Swapchain swapchain_, - gpu::SwapchainInfo const &info) + Device::invalidate_swapchain(gpu::Swapchain swapchain_, + gpu::SwapchainInfo const & info) { CHECK(info.preferred_extent.x > 0); CHECK(info.preferred_extent.y > 0); - Swapchain *const swapchain = (Swapchain *) swapchain_; - swapchain->is_optimal = false; - swapchain->info = info; + Swapchain * const swapchain = (Swapchain *) swapchain_; + swapchain->is_optimal = false; + swapchain->info = info; return Ok{Void{}}; } Result Device::begin_frame(gpu::Swapchain swapchain_) { - FrameContext &ctx = frame_ctx; - Swapchain *const swapchain = (Swapchain *) swapchain_; - VkFence submit_fence = ctx.submit_f[ctx.ring_index]; - CommandEncoder &enc = ctx.encs[ctx.ring_index]; + FrameContext & ctx = frame_ctx; + Swapchain * const swapchain = (Swapchain *) swapchain_; + VkFence submit_fence = ctx.submit_f[ctx.ring_index]; + CommandEncoder & enc = ctx.encs[ctx.ring_index]; CHECK(!enc.is_recording()); @@ -4244,10 +4259,10 @@ Result Device::begin_frame(gpu::Swapchain swapchain_) Result Device::submit_frame(gpu::Swapchain swapchain_) { - FrameContext &ctx = frame_ctx; - Swapchain *const swapchain = (Swapchain *) swapchain_; + FrameContext & ctx = frame_ctx; + Swapchain * const swapchain = (Swapchain *) swapchain_; VkFence const submit_fence = ctx.submit_f[ctx.ring_index]; - CommandEncoder &enc = ctx.encs[ctx.ring_index]; + CommandEncoder & enc = ctx.encs[ctx.ring_index]; VkCommandBuffer const command_buffer = enc.vk_command_buffer; VkSemaphore const submit_semaphore = ctx.submit_s[ctx.ring_index]; VkSemaphore const acquire_semaphore = ctx.acquire_s[ctx.ring_index]; @@ -4434,7 +4449,8 @@ void CommandEncoder::begin_debug_marker(Span region_name, .sType = VK_STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT, .pNext = nullptr, .pMarkerName = region_name_cstr, - .color = {color.x, color.y, color.z, color.w}}; + .color = {color.x, color.y, color.z, color.w} + }; dev->vk_table.CmdDebugMarkerBeginEXT(vk_command_buffer, &info); } @@ -4449,7 +4465,7 @@ void CommandEncoder::fill_buffer(gpu::Buffer dst_, u64 offset, u64 size, u32 data) { ENCODE_PRELUDE(); - Buffer *const dst = (Buffer *) dst_; + Buffer * const dst = (Buffer *) dst_; CHECK(!is_in_pass()); CHECK(has_bits(dst->info.usage, gpu::BufferUsage::TransferDst)); @@ -4466,21 +4482,21 @@ void CommandEncoder::copy_buffer(gpu::Buffer src_, gpu::Buffer dst_, Span copies) { ENCODE_PRELUDE(); - Buffer *const src = (Buffer *) src_; - Buffer *const dst = (Buffer *) dst_; - u32 const num_copies = copies.size32(); + Buffer * const src = (Buffer *) src_; + Buffer * const dst = (Buffer *) dst_; + u32 const num_copies = copies.size32(); CHECK(!is_in_pass()); CHECK(has_bits(src->info.usage, gpu::BufferUsage::TransferSrc)); CHECK(has_bits(dst->info.usage, gpu::BufferUsage::TransferDst)); CHECK(num_copies > 0); - for (gpu::BufferCopy const © : copies) + for (gpu::BufferCopy const & copy : copies) { CHECK(is_valid_buffer_access(src->info.size, copy.src_offset, copy.size)); CHECK(is_valid_buffer_access(dst->info.size, copy.dst_offset, copy.size)); } - VkBufferCopy *vk_copies; + VkBufferCopy * vk_copies; if (!arg_pool.nalloc(num_copies, vk_copies)) { @@ -4490,10 +4506,10 @@ void CommandEncoder::copy_buffer(gpu::Buffer src_, gpu::Buffer dst_, for (u32 i = 0; i < num_copies; i++) { - gpu::BufferCopy const © = copies[i]; - vk_copies[i] = VkBufferCopy{.srcOffset = copy.src_offset, - .dstOffset = copy.dst_offset, - .size = copy.size}; + gpu::BufferCopy const & copy = copies[i]; + vk_copies[i] = VkBufferCopy{.srcOffset = copy.src_offset, + .dstOffset = copy.dst_offset, + .size = copy.size}; } access_buffer(*src, VK_PIPELINE_STAGE_TRANSFER_BIT, @@ -4509,8 +4525,8 @@ void CommandEncoder::update_buffer(Span src, u64 dst_offset, gpu::Buffer dst_) { ENCODE_PRELUDE(); - Buffer *const dst = (Buffer *) dst_; - u64 const copy_size = src.size_bytes(); + Buffer * const dst = (Buffer *) dst_; + u64 const copy_size = src.size_bytes(); CHECK(!is_in_pass()); CHECK(has_bits(dst->info.usage, gpu::BufferUsage::TransferDst)); @@ -4530,8 +4546,8 @@ void CommandEncoder::clear_color_image( Span ranges) { ENCODE_PRELUDE(); - Image *const dst = (Image *) dst_; - u32 const num_ranges = ranges.size32(); + Image * const dst = (Image *) dst_; + u32 const num_ranges = ranges.size32(); static_assert(sizeof(gpu::Color) == sizeof(VkClearColorValue)); CHECK(!is_in_pass()); @@ -4539,14 +4555,14 @@ void CommandEncoder::clear_color_image( CHECK(num_ranges > 0); for (u32 i = 0; i < num_ranges; i++) { - gpu::ImageSubresourceRange const &range = ranges[i]; + gpu::ImageSubresourceRange const & range = ranges[i]; CHECK(is_valid_image_access( dst->info.aspects, dst->info.mip_levels, dst->info.array_layers, range.aspects, range.first_mip_level, range.num_mip_levels, range.first_array_layer, range.num_array_layers)); } - VkImageSubresourceRange *vk_ranges; + VkImageSubresourceRange * vk_ranges; if (!arg_pool.nalloc(num_ranges, vk_ranges)) { status = Status::OutOfHostMemory; @@ -4555,13 +4571,13 @@ void CommandEncoder::clear_color_image( for (u32 i = 0; i < num_ranges; i++) { - gpu::ImageSubresourceRange const &range = ranges[i]; - vk_ranges[i] = VkImageSubresourceRange{ - .aspectMask = (VkImageAspectFlags) range.aspects, - .baseMipLevel = range.first_mip_level, - .levelCount = range.num_mip_levels, - .baseArrayLayer = range.first_array_layer, - .layerCount = range.num_array_layers}; + gpu::ImageSubresourceRange const & range = ranges[i]; + vk_ranges[i] = VkImageSubresourceRange{ + .aspectMask = (VkImageAspectFlags) range.aspects, + .baseMipLevel = range.first_mip_level, + .levelCount = range.num_mip_levels, + .baseArrayLayer = range.first_array_layer, + .layerCount = range.num_array_layers}; } access_image_all_aspects(*dst, VK_PIPELINE_STAGE_TRANSFER_BIT, @@ -4581,8 +4597,8 @@ void CommandEncoder::clear_depth_stencil_image( Span ranges) { ENCODE_PRELUDE(); - Image *const dst = (Image *) dst_; - u32 const num_ranges = ranges.size32(); + Image * const dst = (Image *) dst_; + u32 const num_ranges = ranges.size32(); static_assert(sizeof(gpu::DepthStencil) == sizeof(VkClearDepthStencilValue)); CHECK(!is_in_pass()); @@ -4590,14 +4606,14 @@ void CommandEncoder::clear_depth_stencil_image( CHECK(has_bits(dst->info.usage, gpu::ImageUsage::TransferDst)); for (u32 i = 0; i < num_ranges; i++) { - gpu::ImageSubresourceRange const &range = ranges[i]; + gpu::ImageSubresourceRange const & range = ranges[i]; CHECK(is_valid_image_access( dst->info.aspects, dst->info.mip_levels, dst->info.array_layers, range.aspects, range.first_mip_level, range.num_mip_levels, range.first_array_layer, range.num_array_layers)); } - VkImageSubresourceRange *vk_ranges; + VkImageSubresourceRange * vk_ranges; if (!arg_pool.nalloc(num_ranges, vk_ranges)) { status = Status::OutOfHostMemory; @@ -4606,13 +4622,13 @@ void CommandEncoder::clear_depth_stencil_image( for (u32 i = 0; i < num_ranges; i++) { - gpu::ImageSubresourceRange const &range = ranges[i]; - vk_ranges[i] = VkImageSubresourceRange{ - .aspectMask = (VkImageAspectFlags) range.aspects, - .baseMipLevel = range.first_mip_level, - .levelCount = range.num_mip_levels, - .baseArrayLayer = range.first_array_layer, - .layerCount = range.num_array_layers}; + gpu::ImageSubresourceRange const & range = ranges[i]; + vk_ranges[i] = VkImageSubresourceRange{ + .aspectMask = (VkImageAspectFlags) range.aspects, + .baseMipLevel = range.first_mip_level, + .levelCount = range.num_mip_levels, + .baseArrayLayer = range.first_array_layer, + .layerCount = range.num_array_layers}; } access_image_all_aspects(*dst, VK_PIPELINE_STAGE_TRANSFER_BIT, @@ -4632,9 +4648,9 @@ void CommandEncoder::copy_image(gpu::Image src_, gpu::Image dst_, Span copies) { ENCODE_PRELUDE(); - Image *const src = (Image *) src_; - Image *const dst = (Image *) dst_; - u32 const num_copies = copies.size32(); + Image * const src = (Image *) src_; + Image * const dst = (Image *) dst_; + u32 const num_copies = copies.size32(); CHECK(!is_in_pass()); CHECK(num_copies > 0); @@ -4642,7 +4658,7 @@ void CommandEncoder::copy_image(gpu::Image src_, gpu::Image dst_, CHECK(has_bits(dst->info.usage, gpu::ImageUsage::TransferDst)); for (u32 i = 0; i < num_copies; i++) { - gpu::ImageCopy const © = copies[i]; + gpu::ImageCopy const & copy = copies[i]; CHECK(is_valid_image_access( src->info.aspects, src->info.mip_levels, src->info.array_layers, @@ -4674,7 +4690,7 @@ void CommandEncoder::copy_image(gpu::Image src_, gpu::Image dst_, CHECK((copy.dst_offset.z + copy.extent.z) <= dst_extent.z); } - VkImageCopy *vk_copies; + VkImageCopy * vk_copies; if (!arg_pool.nalloc(num_copies, vk_copies)) { status = Status::OutOfHostMemory; @@ -4683,7 +4699,7 @@ void CommandEncoder::copy_image(gpu::Image src_, gpu::Image dst_, for (u32 i = 0; i < num_copies; i++) { - gpu::ImageCopy const © = copies[i]; + gpu::ImageCopy const & copy = copies[i]; VkImageSubresourceLayers src_subresource{ .aspectMask = (VkImageAspectFlags) copy.src_layers.aspects, .mipLevel = copy.src_layers.mip_level, @@ -4724,9 +4740,9 @@ void CommandEncoder::copy_buffer_to_image( gpu::Buffer src_, gpu::Image dst_, Span copies) { ENCODE_PRELUDE(); - Buffer *const src = (Buffer *) src_; - Image *const dst = (Image *) dst_; - u32 const num_copies = copies.size32(); + Buffer * const src = (Buffer *) src_; + Image * const dst = (Image *) dst_; + u32 const num_copies = copies.size32(); CHECK(!is_in_pass()); CHECK(num_copies > 0); @@ -4734,7 +4750,7 @@ void CommandEncoder::copy_buffer_to_image( CHECK(has_bits(dst->info.usage, gpu::ImageUsage::TransferDst)); for (u32 i = 0; i < num_copies; i++) { - gpu::BufferImageCopy const © = copies[i]; + gpu::BufferImageCopy const & copy = copies[i]; CHECK(is_valid_buffer_access(src->info.size, copy.buffer_offset, gpu::WHOLE_SIZE)); @@ -4757,7 +4773,7 @@ void CommandEncoder::copy_buffer_to_image( CHECK((copy.image_offset.z + copy.image_extent.z) <= dst_extent.z); } - VkBufferImageCopy *vk_copies; + VkBufferImageCopy * vk_copies; if (!arg_pool.nalloc(num_copies, vk_copies)) { status = Status::OutOfHostMemory; @@ -4766,12 +4782,12 @@ void CommandEncoder::copy_buffer_to_image( for (u32 i = 0; i < num_copies; i++) { - gpu::BufferImageCopy const © = copies[i]; - VkImageSubresourceLayers image_subresource{ - .aspectMask = (VkImageAspectFlags) copy.image_layers.aspects, - .mipLevel = copy.image_layers.mip_level, - .baseArrayLayer = copy.image_layers.first_array_layer, - .layerCount = copy.image_layers.num_array_layers}; + gpu::BufferImageCopy const & copy = copies[i]; + VkImageSubresourceLayers image_subresource{ + .aspectMask = (VkImageAspectFlags) copy.image_layers.aspects, + .mipLevel = copy.image_layers.mip_level, + .baseArrayLayer = copy.image_layers.first_array_layer, + .layerCount = copy.image_layers.num_array_layers}; vk_copies[i] = VkBufferImageCopy{ .bufferOffset = copy.buffer_offset, .bufferRowLength = copy.buffer_row_length, @@ -4780,8 +4796,9 @@ void CommandEncoder::copy_buffer_to_image( .imageOffset = VkOffset3D{(i32) copy.image_offset.x, (i32) copy.image_offset.y, (i32) copy.image_offset.z}, - .imageExtent = VkExtent3D{copy.image_extent.x, copy.image_extent.y, - copy.image_extent.z}}; + .imageExtent = VkExtent3D{copy.image_extent.x, copy.image_extent.y, + copy.image_extent.z } + }; } access_buffer(*src, VK_PIPELINE_STAGE_TRANSFER_BIT, @@ -4800,9 +4817,9 @@ void CommandEncoder::blit_image(gpu::Image src_, gpu::Image dst_, gpu::Filter filter) { ENCODE_PRELUDE(); - Image *const src = (Image *) src_; - Image *const dst = (Image *) dst_; - u32 const num_blits = blits.size32(); + Image * const src = (Image *) src_; + Image * const dst = (Image *) dst_; + u32 const num_blits = blits.size32(); CHECK(!is_in_pass()); CHECK(num_blits > 0); @@ -4810,7 +4827,7 @@ void CommandEncoder::blit_image(gpu::Image src_, gpu::Image dst_, CHECK(has_bits(dst->info.usage, gpu::ImageUsage::TransferDst)); for (u32 i = 0; i < num_blits; i++) { - gpu::ImageBlit const &blit = blits[i]; + gpu::ImageBlit const & blit = blits[i]; CHECK(is_valid_image_access( src->info.aspects, src->info.mip_levels, src->info.array_layers, @@ -4850,7 +4867,7 @@ void CommandEncoder::blit_image(gpu::Image src_, gpu::Image dst_, (blit.src_offsets[0].z != 0 || blit.dst_offsets[1].z != 1))); } - VkImageBlit *vk_blits; + VkImageBlit * vk_blits; if (!arg_pool.nalloc(num_blits, vk_blits)) { status = Status::OutOfHostMemory; @@ -4859,7 +4876,7 @@ void CommandEncoder::blit_image(gpu::Image src_, gpu::Image dst_, for (u32 i = 0; i < num_blits; i++) { - gpu::ImageBlit const &blit = blits[i]; + gpu::ImageBlit const & blit = blits[i]; VkImageSubresourceLayers src_subresource{ .aspectMask = (VkImageAspectFlags) blit.src_layers.aspects, .mipLevel = blit.src_layers.mip_level, @@ -4880,10 +4897,11 @@ void CommandEncoder::blit_image(gpu::Image src_, gpu::Image dst_, (i32) blit.src_offsets[1].z}}, .dstSubresource = dst_subresource, .dstOffsets = { - VkOffset3D{(i32) blit.dst_offsets[0].x, (i32) blit.dst_offsets[0].y, + VkOffset3D{(i32) blit.dst_offsets[0].x, (i32) blit.dst_offsets[0].y, (i32) blit.dst_offsets[0].z}, - VkOffset3D{(i32) blit.dst_offsets[1].x, (i32) blit.dst_offsets[1].y, - (i32) blit.dst_offsets[1].z}}}; + VkOffset3D{(i32) blit.dst_offsets[1].x, (i32) blit.dst_offsets[1].y, + (i32) blit.dst_offsets[1].z} } + }; } access_image_all_aspects(*src, VK_PIPELINE_STAGE_TRANSFER_BIT, @@ -4902,9 +4920,9 @@ void CommandEncoder::resolve_image(gpu::Image src_, gpu::Image dst_, Span resolves) { ENCODE_PRELUDE(); - Image *const src = (Image *) src_; - Image *const dst = (Image *) dst_; - u32 const num_resolves = resolves.size32(); + Image * const src = (Image *) src_; + Image * const dst = (Image *) dst_; + u32 const num_resolves = resolves.size32(); CHECK(!is_in_pass()); CHECK(num_resolves > 0); @@ -4914,7 +4932,7 @@ void CommandEncoder::resolve_image(gpu::Image src_, gpu::Image dst_, for (u32 i = 0; i < num_resolves; i++) { - gpu::ImageResolve const &resolve = resolves[i]; + gpu::ImageResolve const & resolve = resolves[i]; CHECK(is_valid_image_access( src->info.aspects, src->info.mip_levels, src->info.array_layers, @@ -4948,7 +4966,7 @@ void CommandEncoder::resolve_image(gpu::Image src_, gpu::Image dst_, CHECK((resolve.dst_offset.z + resolve.extent.z) <= dst_extent.z); } - VkImageResolve *vk_resolves; + VkImageResolve * vk_resolves; if (!arg_pool.nalloc(num_resolves, vk_resolves)) { status = Status::OutOfHostMemory; @@ -4957,12 +4975,12 @@ void CommandEncoder::resolve_image(gpu::Image src_, gpu::Image dst_, for (u32 i = 0; i < num_resolves; i++) { - gpu::ImageResolve const &resolve = resolves[i]; - VkImageSubresourceLayers src_subresource{ - .aspectMask = (VkImageAspectFlags) resolve.src_layers.aspects, - .mipLevel = resolve.src_layers.mip_level, - .baseArrayLayer = resolve.src_layers.first_array_layer, - .layerCount = resolve.src_layers.num_array_layers}; + gpu::ImageResolve const & resolve = resolves[i]; + VkImageSubresourceLayers src_subresource{ + .aspectMask = (VkImageAspectFlags) resolve.src_layers.aspects, + .mipLevel = resolve.src_layers.mip_level, + .baseArrayLayer = resolve.src_layers.first_array_layer, + .layerCount = resolve.src_layers.num_array_layers}; VkOffset3D src_offset{(i32) resolve.src_offset.x, (i32) resolve.src_offset.y, (i32) resolve.src_offset.z}; @@ -5012,7 +5030,7 @@ void CommandEncoder::end_compute_pass() reset_context(); } -void validate_attachment(gpu::RenderingAttachment const &info, +void validate_attachment(gpu::RenderingAttachment const & info, gpu::ImageAspects aspects, gpu::ImageUsage usage) { CHECK( @@ -5036,7 +5054,7 @@ void validate_attachment(gpu::RenderingAttachment const &info, } } -void CommandEncoder::begin_rendering(gpu::RenderingInfo const &info) +void CommandEncoder::begin_rendering(gpu::RenderingInfo const & info) { ENCODE_PRELUDE(); u32 const num_color_attachments = info.color_attachments.size32(); @@ -5051,19 +5069,19 @@ void CommandEncoder::begin_rendering(gpu::RenderingInfo const &info) CHECK(info.render_area.extent.y > 0); CHECK(info.num_layers > 0); - for (gpu::RenderingAttachment const &attachment : info.color_attachments) + for (gpu::RenderingAttachment const & attachment : info.color_attachments) { validate_attachment(attachment, gpu::ImageAspects::Color, gpu::ImageUsage::ColorAttachment); } - for (gpu::RenderingAttachment const &attachment : info.depth_attachment) + for (gpu::RenderingAttachment const & attachment : info.depth_attachment) { validate_attachment(attachment, gpu::ImageAspects::Depth, gpu::ImageUsage::DepthStencilAttachment); } - for (gpu::RenderingAttachment const &attachment : info.stencil_attachment) + for (gpu::RenderingAttachment const & attachment : info.stencil_attachment) { validate_attachment(attachment, gpu::ImageAspects::Stencil, gpu::ImageUsage::DepthStencilAttachment); @@ -5082,7 +5100,7 @@ void CommandEncoder::begin_rendering(gpu::RenderingInfo const &info) } constexpr VkAccessFlags - color_attachment_access(gpu::RenderingAttachment const &attachment) + color_attachment_access(gpu::RenderingAttachment const & attachment) { VkAccessFlags access = VK_ACCESS_NONE; @@ -5102,7 +5120,7 @@ constexpr VkAccessFlags } constexpr VkAccessFlags - depth_attachment_access(gpu::RenderingAttachment const &attachment) + depth_attachment_access(gpu::RenderingAttachment const & attachment) { VkAccessFlags access = VK_ACCESS_NONE; @@ -5123,7 +5141,7 @@ constexpr VkAccessFlags } constexpr VkAccessFlags - stencil_attachment_access(gpu::RenderingAttachment const &attachment) + stencil_attachment_access(gpu::RenderingAttachment const & attachment) { return depth_attachment_access(attachment); } @@ -5131,12 +5149,12 @@ constexpr VkAccessFlags void CommandEncoder::end_rendering() { ENCODE_PRELUDE(); - RenderPassContext &ctx = render_ctx; - DeviceTable const *t = &dev->vk_table; + RenderPassContext & ctx = render_ctx; + DeviceTable const * t = &dev->vk_table; CHECK(is_in_render_pass()); - for (Command const &cmd : render_ctx.commands) + for (Command const & cmd : render_ctx.commands) { switch (cmd.type) { @@ -5195,7 +5213,7 @@ void CommandEncoder::end_rendering() for (u32 i = 0; i < ctx.num_color_attachments; i++) { - gpu::RenderingAttachment const &attachment = ctx.color_attachments[i]; + gpu::RenderingAttachment const & attachment = ctx.color_attachments[i]; VkAccessFlags access = color_attachment_access(attachment); VkImageView vk_view = nullptr; VkImageView vk_resolve = nullptr; @@ -5213,9 +5231,9 @@ void CommandEncoder::end_rendering() if (attachment.view != nullptr) { - ImageView *view = (ImageView *) attachment.view; - ImageView *resolve = (ImageView *) attachment.resolve; - vk_view = view->vk_view; + ImageView * view = (ImageView *) attachment.view; + ImageView * resolve = (ImageView *) attachment.resolve; + vk_view = view->vk_view; if (attachment.resolve_mode != gpu::ResolveModes::None) { vk_resolve = resolve->vk_view; @@ -5243,7 +5261,7 @@ void CommandEncoder::end_rendering() for (u32 i = 0; i < ctx.num_depth_attachments; i++) { - gpu::RenderingAttachment const &attachment = ctx.depth_attachment[i]; + gpu::RenderingAttachment const & attachment = ctx.depth_attachment[i]; VkAccessFlags access = depth_attachment_access(attachment); VkImageView vk_view = nullptr; VkImageView vk_resolve = nullptr; @@ -5272,9 +5290,9 @@ void CommandEncoder::end_rendering() if (attachment.view != nullptr) { - ImageView *view = (ImageView *) attachment.view; - ImageView *resolve = (ImageView *) attachment.resolve; - vk_view = view->vk_view; + ImageView * view = (ImageView *) attachment.view; + ImageView * resolve = (ImageView *) attachment.resolve; + vk_view = view->vk_view; if (attachment.resolve_mode != gpu::ResolveModes::None) { vk_resolve = resolve->vk_view; @@ -5302,7 +5320,7 @@ void CommandEncoder::end_rendering() for (u32 i = 0; i < ctx.num_stencil_attachments; i++) { - gpu::RenderingAttachment const &attachment = ctx.stencil_attachment[i]; + gpu::RenderingAttachment const & attachment = ctx.stencil_attachment[i]; VkAccessFlags access = stencil_attachment_access(attachment); VkImageView vk_view = nullptr; VkImageView vk_resolve = nullptr; @@ -5332,9 +5350,9 @@ void CommandEncoder::end_rendering() if (attachment.view != nullptr) { - ImageView *view = (ImageView *) attachment.view; - ImageView *resolve = (ImageView *) attachment.resolve; - vk_view = view->vk_view; + ImageView * view = (ImageView *) attachment.view; + ImageView * resolve = (ImageView *) attachment.resolve; + vk_view = view->vk_view; if (attachment.resolve_mode != gpu::ResolveModes::None) { vk_resolve = resolve->vk_view; @@ -5377,14 +5395,15 @@ void CommandEncoder::end_rendering() (ctx.num_depth_attachments == 0) ? nullptr : vk_depth_attachment, .pStencilAttachment = (ctx.num_stencil_attachments == 0) ? nullptr : - vk_stencil_attachment}; + vk_stencil_attachment + }; t->CmdBeginRenderingKHR(vk_command_buffer, &begin_info); } - GraphicsPipeline *pipeline = nullptr; + GraphicsPipeline * pipeline = nullptr; - for (Command const &cmd : ctx.commands) + for (Command const & cmd : ctx.commands) { switch (cmd.type) { @@ -5418,12 +5437,13 @@ void CommandEncoder::end_rendering() break; case CommandType::SetGraphicsState: { - gpu::GraphicsState const &s = cmd.state; + gpu::GraphicsState const & s = cmd.state; VkRect2D vk_scissor{ .offset = VkOffset2D{(i32) s.scissor.offset.x, (i32) s.scissor.offset.y}, - .extent = VkExtent2D{s.scissor.extent.x, s.scissor.extent.y}}; + .extent = VkExtent2D{s.scissor.extent.x, s.scissor.extent.y } + }; t->CmdSetScissor(vk_command_buffer, 0, 1, &vk_scissor); VkViewport vk_viewport{.x = s.viewport.offset.x, @@ -5529,7 +5549,7 @@ void CommandEncoder::end_rendering() void CommandEncoder::bind_compute_pipeline(gpu::ComputePipeline pipeline) { ENCODE_PRELUDE(); - ComputePassContext &ctx = compute_ctx; + ComputePassContext & ctx = compute_ctx; CHECK(is_in_compute_pass()); @@ -5545,8 +5565,8 @@ void CommandEncoder::validate_render_pass_compatible( gpu::GraphicsPipeline pipeline_) { - RenderPassContext const &ctx = render_ctx; - GraphicsPipeline *pipeline = (GraphicsPipeline *) pipeline_; + RenderPassContext const & ctx = render_ctx; + GraphicsPipeline * pipeline = (GraphicsPipeline *) pipeline_; CHECK(pipeline->num_colors == ctx.num_color_attachments); CHECK(pipeline->num_depths == ctx.num_depth_attachments); @@ -5583,7 +5603,7 @@ void CommandEncoder::validate_render_pass_compatible( } } -void CommandEncoder::access_buffer(Buffer &buffer, VkPipelineStageFlags stages, +void CommandEncoder::access_buffer(Buffer & buffer, VkPipelineStageFlags stages, VkAccessFlags access) { VkBufferMemoryBarrier barrier; @@ -5606,7 +5626,7 @@ void CommandEncoder::access_buffer(Buffer &buffer, VkPipelineStageFlags stages, } void CommandEncoder::access_image_aspect( - Image &image, VkPipelineStageFlags stages, VkAccessFlags access, + Image & image, VkPipelineStageFlags stages, VkAccessFlags access, VkImageLayout layout, gpu::ImageAspects aspects, u32 aspect_index) { VkImageMemoryBarrier barrier; @@ -5632,7 +5652,7 @@ void CommandEncoder::access_image_aspect( } } -void CommandEncoder::access_image_all_aspects(Image &image, +void CommandEncoder::access_image_all_aspects(Image & image, VkPipelineStageFlags stages, VkAccessFlags access, VkImageLayout layout) @@ -5651,11 +5671,11 @@ void CommandEncoder::access_image_all_aspects(Image &image, } } -void CommandEncoder::access_compute_bindings(DescriptorSet const &set) +void CommandEncoder::access_compute_bindings(DescriptorSet const & set) { for (u32 ibinding = 0; ibinding < set.num_bindings; ibinding++) { - DescriptorBinding const &binding = set.bindings[ibinding]; + DescriptorBinding const & binding = set.bindings[ibinding]; switch (binding.type) { case gpu::DescriptorType::CombinedImageSampler: @@ -5722,11 +5742,11 @@ void CommandEncoder::access_compute_bindings(DescriptorSet const &set) } } -void CommandEncoder::access_graphics_bindings(DescriptorSet const &set) +void CommandEncoder::access_graphics_bindings(DescriptorSet const & set) { for (u32 ibinding = 0; ibinding < set.num_bindings; ibinding++) { - DescriptorBinding const &binding = set.bindings[ibinding]; + DescriptorBinding const & binding = set.bindings[ibinding]; switch (binding.type) { case gpu::DescriptorType::CombinedImageSampler: @@ -5802,8 +5822,8 @@ void CommandEncoder::access_graphics_bindings(DescriptorSet const &set) void CommandEncoder::bind_graphics_pipeline(gpu::GraphicsPipeline pipeline_) { ENCODE_PRELUDE(); - RenderPassContext &ctx = render_ctx; - GraphicsPipeline *pipeline = (GraphicsPipeline *) pipeline_; + RenderPassContext & ctx = render_ctx; + GraphicsPipeline * pipeline = (GraphicsPipeline *) pipeline_; CHECK(is_in_render_pass()); CHECK(pipeline != nullptr); @@ -5860,13 +5880,13 @@ void CommandEncoder::bind_descriptor_sets( { CHECK(render_ctx.pipeline != nullptr); CHECK(render_ctx.pipeline->num_sets == num_sets); - DescriptorSet **sets; + DescriptorSet ** sets; if (!render_ctx.arg_pool.nalloc(num_sets, sets)) { status = Status::OutOfHostMemory; return; } - u32 *offsets; + u32 * offsets; if (!render_ctx.arg_pool.nalloc(num_dynamic_offsets, offsets)) { render_ctx.arg_pool.ndealloc(sets, num_sets); @@ -5875,9 +5895,10 @@ void CommandEncoder::bind_descriptor_sets( } mem::copy(descriptor_sets, (gpu::DescriptorSet *) sets); mem::copy(dynamic_offsets, offsets); - if (!render_ctx.commands.push( - Command{.type = CommandType::BindDescriptorSets, - .set = {sets, num_sets, offsets, num_dynamic_offsets}})) + if (!render_ctx.commands.push(Command{ + .type = CommandType::BindDescriptorSets, + .set = {sets, num_sets, offsets, num_dynamic_offsets} + })) { render_ctx.arg_pool.ndealloc(offsets, num_dynamic_offsets); render_ctx.arg_pool.ndealloc(sets, num_sets); @@ -5908,12 +5929,13 @@ void CommandEncoder::push_constants(Span push_constants_data) { CHECK(render_ctx.pipeline != nullptr); CHECK(push_constants_size == render_ctx.pipeline->push_constants_size); - u8 *data; + u8 * data; CHECK(render_ctx.arg_pool.nalloc(push_constants_size, data)); mem::copy(push_constants_data, data); - if (!render_ctx.commands.push( - Command{.type = CommandType::PushConstants, - .push_constant = {data, push_constants_size}})) + if (!render_ctx.commands.push(Command{ + .type = CommandType::PushConstants, + .push_constant = {data, push_constants_size} + })) { status = Status::OutOfHostMemory; return; @@ -5925,7 +5947,7 @@ void CommandEncoder::dispatch(u32 group_count_x, u32 group_count_y, u32 group_count_z) { ENCODE_PRELUDE(); - ComputePassContext &ctx = compute_ctx; + ComputePassContext & ctx = compute_ctx; CHECK(is_in_compute_pass()); @@ -5949,8 +5971,8 @@ void CommandEncoder::dispatch(u32 group_count_x, u32 group_count_y, void CommandEncoder::dispatch_indirect(gpu::Buffer buffer_, u64 offset) { ENCODE_PRELUDE(); - ComputePassContext &ctx = compute_ctx; - Buffer *const buffer = (Buffer *) buffer_; + ComputePassContext & ctx = compute_ctx; + Buffer * const buffer = (Buffer *) buffer_; CHECK(is_in_compute_pass()); CHECK(ctx.pipeline != nullptr); @@ -5967,10 +5989,10 @@ void CommandEncoder::dispatch_indirect(gpu::Buffer buffer_, u64 offset) offset); } -void CommandEncoder::set_graphics_state(gpu::GraphicsState const &state) +void CommandEncoder::set_graphics_state(gpu::GraphicsState const & state) { ENCODE_PRELUDE(); - RenderPassContext &ctx = render_ctx; + RenderPassContext & ctx = render_ctx; CHECK(is_in_render_pass()); CHECK(state.viewport.min_depth >= 0.0F); @@ -5991,7 +6013,7 @@ void CommandEncoder::bind_vertex_buffers(Span vertex_buffers, Span offsets) { ENCODE_PRELUDE(); - RenderPassContext &ctx = render_ctx; + RenderPassContext & ctx = render_ctx; CHECK(is_in_render_pass()); u32 const num_vertex_buffers = vertex_buffers.size32(); @@ -6000,8 +6022,8 @@ void CommandEncoder::bind_vertex_buffers(Span vertex_buffers, CHECK(offsets.size() == vertex_buffers.size()); for (u32 i = 0; i < num_vertex_buffers; i++) { - u64 const offset = offsets[i]; - Buffer *const buffer = (Buffer *) vertex_buffers[i]; + u64 const offset = offsets[i]; + Buffer * const buffer = (Buffer *) vertex_buffers[i]; CHECK(offset < buffer->info.size); CHECK(has_bits(buffer->info.usage, gpu::BufferUsage::VertexBuffer)); } @@ -6010,7 +6032,8 @@ void CommandEncoder::bind_vertex_buffers(Span vertex_buffers, { if (!ctx.commands.push(Command{ .type = CommandType::BindVertexBuffer, - .vertex_buffer = {i, (Buffer *) vertex_buffers[i], offsets[i]}})) + .vertex_buffer = {i, (Buffer *) vertex_buffers[i], offsets[i]} + })) { status = Status::OutOfHostMemory; return; @@ -6022,9 +6045,9 @@ void CommandEncoder::bind_index_buffer(gpu::Buffer index_buffer_, u64 offset, gpu::IndexType index_type) { ENCODE_PRELUDE(); - RenderPassContext &ctx = render_ctx; - Buffer *const index_buffer = (Buffer *) index_buffer_; - u64 const index_size = index_type_size(index_type); + RenderPassContext & ctx = render_ctx; + Buffer * const index_buffer = (Buffer *) index_buffer_; + u64 const index_size = index_type_size(index_type); CHECK(is_in_render_pass()); CHECK(offset < index_buffer->info.size); @@ -6034,9 +6057,10 @@ void CommandEncoder::bind_index_buffer(gpu::Buffer index_buffer_, u64 offset, ctx.index_buffer = index_buffer; ctx.index_type = index_type; ctx.index_buffer_offset = offset; - if (!ctx.commands.push( - Command{.type = CommandType::BindIndexBuffer, - .index_buffer = {index_buffer, offset, index_type}})) + if (!ctx.commands.push(Command{ + .type = CommandType::BindIndexBuffer, + .index_buffer = {index_buffer, offset, index_type} + })) { status = Status::OutOfHostMemory; return; @@ -6047,15 +6071,17 @@ void CommandEncoder::draw(u32 vertex_count, u32 instance_count, u32 first_vertex_id, u32 first_instance_id) { ENCODE_PRELUDE(); - RenderPassContext &ctx = render_ctx; + RenderPassContext & ctx = render_ctx; CHECK(is_in_render_pass()); CHECK(ctx.pipeline != nullptr); CHECK(ctx.has_state); - if (!ctx.commands.push(Command{.type = CommandType::Draw, - .draw = {vertex_count, instance_count, - first_vertex_id, first_instance_id}})) + if (!ctx.commands.push(Command{ + .type = CommandType::Draw, + .draw = {vertex_count, instance_count, first_vertex_id, + first_instance_id} + })) { status = Status::OutOfHostMemory; return; @@ -6067,7 +6093,7 @@ void CommandEncoder::draw_indexed(u32 first_index, u32 num_indices, u32 num_instances) { ENCODE_PRELUDE(); - RenderPassContext &ctx = render_ctx; + RenderPassContext & ctx = render_ctx; CHECK(is_in_render_pass()); CHECK(ctx.pipeline != nullptr); @@ -6079,10 +6105,11 @@ void CommandEncoder::draw_indexed(u32 first_index, u32 num_indices, ctx.index_buffer->info.size); CHECK(ctx.has_state); - if (!ctx.commands.push( - Command{.type = CommandType::DrawIndexed, - .draw_indexed = {first_index, num_indices, vertex_offset, - first_instance_id, num_instances}})) + if (!ctx.commands.push(Command{ + .type = CommandType::DrawIndexed, + .draw_indexed = {first_index, num_indices, vertex_offset, + first_instance_id, num_instances} + })) { status = Status::OutOfHostMemory; return; @@ -6093,8 +6120,8 @@ void CommandEncoder::draw_indirect(gpu::Buffer buffer_, u64 offset, u32 draw_count, u32 stride) { ENCODE_PRELUDE(); - RenderPassContext &ctx = render_ctx; - Buffer *const buffer = (Buffer *) buffer_; + RenderPassContext & ctx = render_ctx; + Buffer * const buffer = (Buffer *) buffer_; CHECK(is_in_render_pass()); CHECK(ctx.pipeline != nullptr); @@ -6105,9 +6132,10 @@ void CommandEncoder::draw_indirect(gpu::Buffer buffer_, u64 offset, CHECK(stride >= sizeof(gpu::DrawCommand)); CHECK(ctx.has_state); - if (!ctx.commands.push( - Command{.type = CommandType::DrawIndirect, - .draw_indirect = {buffer, offset, draw_count, stride}})) + if (!ctx.commands.push(Command{ + .type = CommandType::DrawIndirect, + .draw_indirect = {buffer, offset, draw_count, stride} + })) { status = Status::OutOfHostMemory; return; @@ -6118,8 +6146,8 @@ void CommandEncoder::draw_indexed_indirect(gpu::Buffer buffer_, u64 offset, u32 draw_count, u32 stride) { ENCODE_PRELUDE(); - RenderPassContext &ctx = render_ctx; - Buffer *const buffer = (Buffer *) buffer_; + RenderPassContext & ctx = render_ctx; + Buffer * const buffer = (Buffer *) buffer_; CHECK(is_in_render_pass()); CHECK(ctx.pipeline != nullptr); @@ -6131,9 +6159,10 @@ void CommandEncoder::draw_indexed_indirect(gpu::Buffer buffer_, u64 offset, CHECK(stride >= sizeof(gpu::DrawIndexedCommand)); CHECK(ctx.has_state); - if (!ctx.commands.push( - Command{.type = CommandType::DrawIndexedIndirect, - .draw_indirect = {buffer, offset, draw_count, stride}})) + if (!ctx.commands.push(Command{ + .type = CommandType::DrawIndexedIndirect, + .draw_indirect = {buffer, offset, draw_count, stride} + })) { status = Status::OutOfHostMemory; return; diff --git a/ashura/gpu/vulkan.h b/ashura/gpu/vulkan.h index 75466dcb..1c39479b 100644 --- a/ashura/gpu/vulkan.h +++ b/ashura/gpu/vulkan.h @@ -1,8 +1,8 @@ /// SPDX-License-Identifier: MIT #pragma once -#define VMA_STATIC_VULKAN_FUNCTIONS 0 +#define VMA_STATIC_VULKAN_FUNCTIONS 0 #define VMA_DYNAMIC_VULKAN_FUNCTIONS 0 -#define VMA_VULKAN_VERSION 1000000 +#define VMA_VULKAN_VERSION 1'000'000 #include "ashura/gpu/gpu.h" #include "ashura/std/allocator.h" @@ -19,10 +19,10 @@ namespace vk using gpu::Status; -constexpr char const *ENGINE_NAME = "Ash"; -constexpr u32 ENGINE_VERSION = VK_MAKE_API_VERSION(0, 0, 0, 1); -constexpr char const *CLIENT_NAME = "Ash Client"; -constexpr u32 CLIENT_VERSION = VK_MAKE_API_VERSION(0, 0, 0, 1); +constexpr char const * ENGINE_NAME = "Ash"; +constexpr u32 ENGINE_VERSION = VK_MAKE_API_VERSION(0, 0, 0, 1); +constexpr char const * CLIENT_NAME = "Ash Client"; +constexpr u32 CLIENT_VERSION = VK_MAKE_API_VERSION(0, 0, 0, 1); constexpr u32 MAX_MEMORY_HEAP_PROPERTIES = 32; constexpr u32 MAX_MEMORY_HEAPS = 16; @@ -306,10 +306,11 @@ struct DescriptorBinding { union { - void **sync_resources = nullptr; - Image **images; - Buffer **buffers; + void ** sync_resources = nullptr; + Image ** images; + Buffer ** buffers; }; + u32 count = 0; gpu::DescriptorType type = gpu::DescriptorType::Sampler; bool is_variable_length = false; @@ -333,12 +334,12 @@ struct DescriptorPool /// @param pool_size each pool will have `pool_size` of each descriptor type struct DescriptorHeap { - AllocatorImpl allocator = {}; - DescriptorPool *pools = nullptr; - u32 pool_size = 0; - u8 *scratch = nullptr; - u32 num_pools = 0; - usize scratch_size = 0; + AllocatorImpl allocator = {}; + DescriptorPool * pools = nullptr; + u32 pool_size = 0; + u8 * scratch = nullptr; + u32 num_pools = 0; + usize scratch_size = 0; }; struct ComputePipeline @@ -372,11 +373,14 @@ struct Instance final : gpu::Instance bool validation_enabled = false; // [ ] fix - explicit Instance() {}; - Instance(Instance const &) = delete; - Instance &operator=(Instance const &) = delete; - Instance(Instance &&) = delete; - Instance &operator=(Instance &&) = delete; + explicit Instance() + { + } + + Instance(Instance const &) = delete; + Instance & operator=(Instance const &) = delete; + Instance(Instance &&) = delete; + Instance & operator=(Instance &&) = delete; virtual ~Instance() override; virtual Result @@ -386,7 +390,7 @@ struct Instance final : gpu::Instance virtual gpu::Backend get_backend() override; - virtual void uninit_device(gpu::Device *device) override; + virtual void uninit_device(gpu::Device * device) override; virtual void uninit_surface(gpu::Surface surface) override; }; @@ -453,11 +457,12 @@ enum class CommandType : usize struct Command { CommandType type = CommandType::None; + union { char none_ = 0; Tuple set; - GraphicsPipeline *pipeline; + GraphicsPipeline * pipeline; gpu::GraphicsState state; Tuple push_constant; Tuple vertex_buffer; @@ -482,12 +487,12 @@ struct RenderPassContext ArenaPool arg_pool = {}; ArenaPool command_pool = {}; Vec commands = {}; - Buffer *vertex_buffers[gpu::MAX_VERTEX_ATTRIBUTES] = {}; + Buffer * vertex_buffers[gpu::MAX_VERTEX_ATTRIBUTES] = {}; u32 num_vertex_buffers = 0; - Buffer *index_buffer = nullptr; + Buffer * index_buffer = nullptr; gpu::IndexType index_type = gpu::IndexType::Uint16; u64 index_buffer_offset = 0; - GraphicsPipeline *pipeline = nullptr; + GraphicsPipeline * pipeline = nullptr; bool has_state = false; void reset() @@ -510,9 +515,9 @@ struct RenderPassContext struct ComputePassContext { - DescriptorSet *sets[gpu::MAX_PIPELINE_DESCRIPTOR_SETS] = {}; - u32 num_sets = 0; - ComputePipeline *pipeline = nullptr; + DescriptorSet * sets[gpu::MAX_PIPELINE_DESCRIPTOR_SETS] = {}; + u32 num_sets = 0; + ComputePipeline * pipeline = nullptr; void reset() { @@ -524,7 +529,7 @@ struct ComputePassContext struct CommandEncoder final : gpu::CommandEncoder { AllocatorImpl allocator = {}; - Device *dev = nullptr; + Device * dev = nullptr; ArenaPool arg_pool = {}; VkCommandPool vk_command_pool = nullptr; VkCommandBuffer vk_command_buffer = nullptr; @@ -557,33 +562,33 @@ struct CommandEncoder final : gpu::CommandEncoder void validate_render_pass_compatible(gpu::GraphicsPipeline pipeline); - void access_image_aspect(Image &image, VkPipelineStageFlags stages, + void access_image_aspect(Image & image, VkPipelineStageFlags stages, VkAccessFlags access, VkImageLayout layout, gpu::ImageAspects aspects, u32 aspect_index); - void access_buffer(Buffer &buffer, VkPipelineStageFlags stages, + void access_buffer(Buffer & buffer, VkPipelineStageFlags stages, VkAccessFlags access); - void access_image_all_aspects(Image &image, VkPipelineStageFlags stages, + void access_image_all_aspects(Image & image, VkPipelineStageFlags stages, VkAccessFlags access, VkImageLayout layout); - void access_image_depth(Image &image, VkPipelineStageFlags stages, + void access_image_depth(Image & image, VkPipelineStageFlags stages, VkAccessFlags access, VkImageLayout layout) { access_image_aspect(image, stages, access, layout, gpu::ImageAspects::Depth, DEPTH_ASPECT_IDX); } - void access_image_stencil(Image &image, VkPipelineStageFlags stages, + void access_image_stencil(Image & image, VkPipelineStageFlags stages, VkAccessFlags access, VkImageLayout layout) { access_image_aspect(image, stages, access, layout, gpu::ImageAspects::Stencil, STENCIL_ASPECT_IDX); } - void access_compute_bindings(DescriptorSet const &set); + void access_compute_bindings(DescriptorSet const & set); - void access_graphics_bindings(DescriptorSet const &set); + void access_graphics_bindings(DescriptorSet const & set); void reset_context() { @@ -642,7 +647,7 @@ struct CommandEncoder final : gpu::CommandEncoder virtual void end_compute_pass() override; - virtual void begin_rendering(gpu::RenderingInfo const &info) override; + virtual void begin_rendering(gpu::RenderingInfo const & info) override; virtual void end_rendering() override; @@ -661,7 +666,7 @@ struct CommandEncoder final : gpu::CommandEncoder virtual void dispatch_indirect(gpu::Buffer buffer, u64 offset) override; - virtual void set_graphics_state(gpu::GraphicsState const &state) override; + virtual void set_graphics_state(gpu::GraphicsState const & state) override; virtual void bind_vertex_buffers(Span vertex_buffers, Span offsets) override; @@ -684,22 +689,22 @@ struct CommandEncoder final : gpu::CommandEncoder struct FrameContext { - gpu::FrameId tail_frame = 0; - gpu::FrameId current_frame = 0; - u32 ring_index = 0; - u32 buffering = 0; - CommandEncoder encs[gpu::MAX_FRAME_BUFFERING] = {}; - gpu::CommandEncoder *encs_impl[gpu::MAX_FRAME_BUFFERING] = {}; - VkSemaphore acquire_s[gpu::MAX_FRAME_BUFFERING] = {}; - VkFence submit_f[gpu::MAX_FRAME_BUFFERING] = {}; - VkSemaphore submit_s[gpu::MAX_FRAME_BUFFERING] = {}; - Swapchain *swapchain = nullptr; + gpu::FrameId tail_frame = 0; + gpu::FrameId current_frame = 0; + u32 ring_index = 0; + u32 buffering = 0; + CommandEncoder encs[gpu::MAX_FRAME_BUFFERING] = {}; + gpu::CommandEncoder * encs_impl[gpu::MAX_FRAME_BUFFERING] = {}; + VkSemaphore acquire_s[gpu::MAX_FRAME_BUFFERING] = {}; + VkFence submit_f[gpu::MAX_FRAME_BUFFERING] = {}; + VkSemaphore submit_s[gpu::MAX_FRAME_BUFFERING] = {}; + Swapchain * swapchain = nullptr; }; struct Device final : gpu::Device { AllocatorImpl allocator = {}; - Instance *instance = nullptr; + Instance * instance = nullptr; PhysicalDevice phy_dev = {}; DeviceTable vk_table = {}; VmaVulkanFunctions vma_table = {}; @@ -710,17 +715,17 @@ struct Device final : gpu::Device FrameContext frame_ctx = {}; DescriptorHeap descriptor_heap = {}; - void set_resource_name(Span label, void const *resource, + void set_resource_name(Span label, void const * resource, VkObjectType type, VkDebugReportObjectTypeEXT debug_type); - void uninit_descriptor_heap(DescriptorHeap *heap); + void uninit_descriptor_heap(DescriptorHeap * heap); - VkResult recreate_swapchain(Swapchain *swapchain); + VkResult recreate_swapchain(Swapchain * swapchain); - Status init_command_encoder(CommandEncoder *enc); + Status init_command_encoder(CommandEncoder * enc); - void uninit_command_encoder(CommandEncoder *enc); + void uninit_command_encoder(CommandEncoder * enc); Status init_frame_context(u32 buffering); @@ -732,42 +737,42 @@ struct Device final : gpu::Device get_format_properties(gpu::Format format) override; virtual Result - create_buffer(gpu::BufferInfo const &info) override; + create_buffer(gpu::BufferInfo const & info) override; virtual Result - create_buffer_view(gpu::BufferViewInfo const &info) override; + create_buffer_view(gpu::BufferViewInfo const & info) override; virtual Result - create_image(gpu::ImageInfo const &info) override; + create_image(gpu::ImageInfo const & info) override; virtual Result - create_image_view(gpu::ImageViewInfo const &info) override; + create_image_view(gpu::ImageViewInfo const & info) override; virtual Result - create_sampler(gpu::SamplerInfo const &info) override; + create_sampler(gpu::SamplerInfo const & info) override; virtual Result - create_shader(gpu::ShaderInfo const &info) override; + create_shader(gpu::ShaderInfo const & info) override; virtual Result create_descriptor_set_layout( - gpu::DescriptorSetLayoutInfo const &info) override; + gpu::DescriptorSetLayoutInfo const & info) override; virtual Result create_descriptor_set(gpu::DescriptorSetLayout layout, Span variable_lengths) override; virtual Result - create_pipeline_cache(gpu::PipelineCacheInfo const &info) override; + create_pipeline_cache(gpu::PipelineCacheInfo const & info) override; virtual Result - create_compute_pipeline(gpu::ComputePipelineInfo const &info) override; + create_compute_pipeline(gpu::ComputePipelineInfo const & info) override; virtual Result - create_graphics_pipeline(gpu::GraphicsPipelineInfo const &info) override; + create_graphics_pipeline(gpu::GraphicsPipelineInfo const & info) override; virtual Result - create_swapchain(gpu::Surface surface, - gpu::SwapchainInfo const &info) override; + create_swapchain(gpu::Surface surface, + gpu::SwapchainInfo const & info) override; virtual Result create_timestamp_query() override; @@ -822,26 +827,26 @@ struct Device final : gpu::Device get_pipeline_cache_size(gpu::PipelineCache cache) override; virtual Result get_pipeline_cache_data(gpu::PipelineCache cache, - Vec &out) override; + Vec & out) override; virtual Result merge_pipeline_cache(gpu::PipelineCache dst, Span srcs) override; virtual void - update_descriptor_set(gpu::DescriptorSetUpdate const &update) override; + update_descriptor_set(gpu::DescriptorSetUpdate const & update) override; virtual Result wait_idle() override; virtual Result wait_queue_idle() override; virtual Result - get_surface_formats(gpu::Surface surface, - Vec &formats) override; + get_surface_formats(gpu::Surface surface, + Vec & formats) override; virtual Result - get_surface_present_modes(gpu::Surface surface, - Vec &modes) override; + get_surface_present_modes(gpu::Surface surface, + Vec & modes) override; virtual Result get_surface_capabilities(gpu::Surface surface) override; @@ -850,8 +855,8 @@ struct Device final : gpu::Device get_swapchain_state(gpu::Swapchain swapchain) override; virtual Result - invalidate_swapchain(gpu::Swapchain swapchain, - gpu::SwapchainInfo const &info) override; + invalidate_swapchain(gpu::Swapchain swapchain, + gpu::SwapchainInfo const & info) override; virtual Result begin_frame(gpu::Swapchain swapchain) override; diff --git a/ashura/std/alias_count.h b/ashura/std/alias_count.h index 6c55e177..8cc27a70 100644 --- a/ashura/std/alias_count.h +++ b/ashura/std/alias_count.h @@ -81,4 +81,4 @@ struct AliasCount } }; -} // namespace ash \ No newline at end of file +} // namespace ash diff --git a/ashura/std/allocator.cc b/ashura/std/allocator.cc index a6a75651..ac612016 100644 --- a/ashura/std/allocator.cc +++ b/ashura/std/allocator.cc @@ -1,4 +1,3 @@ - /// SPDX-License-Identifier: MIT #include "ashura/std/allocator.h" #include "ashura/std/cfg.h" @@ -34,7 +33,7 @@ namespace ash NoopAllocator noop_allocator_impl{}; HeapAllocator heap_allocator_impl{}; -bool HeapAllocator::alloc(usize alignment, usize size, u8 *&mem) +bool HeapAllocator::alloc(usize alignment, usize size, u8 *& mem) { if (size == 0) { @@ -44,7 +43,7 @@ bool HeapAllocator::alloc(usize alignment, usize size, u8 *&mem) if (alignment <= MAX_STANDARD_ALIGNMENT) { - if (u8 *m = (u8 *) std::malloc(size); m != nullptr) + if (u8 * m = (u8 *) std::malloc(size); m != nullptr) { mem = m; return true; @@ -54,7 +53,7 @@ bool HeapAllocator::alloc(usize alignment, usize size, u8 *&mem) } #if USE_WIN32CRT_ALIGNED_ALLOC - if (u8 *m = (u8 *) _aligned_malloc(size, alignment); m != nullptr) + if (u8 * m = (u8 *) _aligned_malloc(size, alignment); m != nullptr) { mem = m; return true; @@ -64,7 +63,7 @@ bool HeapAllocator::alloc(usize alignment, usize size, u8 *&mem) #endif #if USE_STDC_ALIGNED_ALLOC - if (u8 *m = (u8 *) std::aligned_alloc(alignment, size); m != nullptr) + if (u8 * m = (u8 *) std::aligned_alloc(alignment, size); m != nullptr) { mem = m; return true; @@ -83,7 +82,7 @@ bool HeapAllocator::alloc(usize alignment, usize size, u8 *&mem) #endif } -bool HeapAllocator::alloc_zeroed(usize alignment, usize size, u8 *&mem) +bool HeapAllocator::alloc_zeroed(usize alignment, usize size, u8 *& mem) { if (size == 0) { @@ -93,7 +92,7 @@ bool HeapAllocator::alloc_zeroed(usize alignment, usize size, u8 *&mem) if (alignment <= MAX_STANDARD_ALIGNMENT) { - if (u8 *m = (u8 *) std::calloc(size, 1); m != nullptr) + if (u8 * m = (u8 *) std::calloc(size, 1); m != nullptr) { mem = m; return true; @@ -103,7 +102,7 @@ bool HeapAllocator::alloc_zeroed(usize alignment, usize size, u8 *&mem) } #if USE_WIN32CRT_ALIGNED_ALLOC - if (u8 *m = (u8 *) _aligned_malloc(size, alignment); m != nullptr) + if (u8 * m = (u8 *) _aligned_malloc(size, alignment); m != nullptr) { std::memset(m, 0, size); mem = m; @@ -114,7 +113,7 @@ bool HeapAllocator::alloc_zeroed(usize alignment, usize size, u8 *&mem) #endif #if USE_STDC_ALIGNED_ALLOC - if (u8 *m = (u8 *) std::aligned_alloc(alignment, size); m != nullptr) + if (u8 * m = (u8 *) std::aligned_alloc(alignment, size); m != nullptr) { std::memset(m, 0, size); mem = m; @@ -136,7 +135,7 @@ bool HeapAllocator::alloc_zeroed(usize alignment, usize size, u8 *&mem) } bool HeapAllocator::realloc(usize alignment, usize old_size, usize new_size, - u8 *&mem) + u8 *& mem) { if (new_size == 0) { @@ -149,7 +148,7 @@ bool HeapAllocator::realloc(usize alignment, usize old_size, usize new_size, if (alignment <= MAX_STANDARD_ALIGNMENT) { - if (u8 *m = (u8 *) std::realloc(mem, new_size); m != nullptr) + if (u8 * m = (u8 *) std::realloc(mem, new_size); m != nullptr) { mem = m; return true; @@ -158,7 +157,7 @@ bool HeapAllocator::realloc(usize alignment, usize old_size, usize new_size, } #if USE_WIN32CRT_ALIGNED_ALLOC - if (u8 *m = (u8 *) _aligned_realloc(mem, new_size, alignment); m != nullptr) + if (u8 * m = (u8 *) _aligned_realloc(mem, new_size, alignment); m != nullptr) { mem = m; return true; @@ -168,7 +167,7 @@ bool HeapAllocator::realloc(usize alignment, usize old_size, usize new_size, #if USE_STDC_ALIGNED_ALLOC // stdc realloc doesn't guarantee preservation of alignment - if (u8 *m = (u8 *) std::aligned_alloc(alignment, new_size); m != nullptr) + if (u8 * m = (u8 *) std::aligned_alloc(alignment, new_size); m != nullptr) { (void) std::memcpy(m, mem, old_size); std::free(mem); @@ -187,7 +186,7 @@ bool HeapAllocator::realloc(usize alignment, usize old_size, usize new_size, #endif } -void HeapAllocator::dealloc(usize alignment, u8 *mem, usize size) +void HeapAllocator::dealloc(usize alignment, u8 * mem, usize size) { (void) alignment; (void) mem; diff --git a/ashura/std/allocator.h b/ashura/std/allocator.h index 3705cd0a..ce3d80d6 100644 --- a/ashura/std/allocator.h +++ b/ashura/std/allocator.h @@ -23,36 +23,36 @@ namespace ash /// struct Allocator { - virtual bool alloc(usize alignment, usize size, u8 *&mem) = 0; + virtual bool alloc(usize alignment, usize size, u8 *& mem) = 0; - virtual bool alloc_zeroed(usize alignment, usize size, u8 *&mem) = 0; + virtual bool alloc_zeroed(usize alignment, usize size, u8 *& mem) = 0; virtual bool realloc(usize alignment, usize old_size, usize new_size, - u8 *&mem) = 0; + u8 *& mem) = 0; - virtual void dealloc(usize alignment, u8 *mem, usize size) = 0; + virtual void dealloc(usize alignment, u8 * mem, usize size) = 0; template - [[nodiscard]] constexpr bool nalloc(usize num, T *&mem) + [[nodiscard]] constexpr bool nalloc(usize num, T *& mem) { return alloc(alignof(T), sizeof(T) * num, (u8 *&) mem); } template - [[nodiscard]] constexpr bool nalloc_zeroed(usize num, T *&mem) + [[nodiscard]] constexpr bool nalloc_zeroed(usize num, T *& mem) { return alloc_zeroed(alignof(T), sizeof(T) * num, (u8 *&) mem); } template - [[nodiscard]] constexpr bool nrealloc(usize old_num, usize new_num, T *&mem) + [[nodiscard]] constexpr bool nrealloc(usize old_num, usize new_num, T *& mem) { return realloc(alignof(T), sizeof(T) * old_num, sizeof(T) * new_num, (u8 *&) mem); } template - constexpr void ndealloc(T *mem, usize num) + constexpr void ndealloc(T * mem, usize num) { dealloc(alignof(T), (u8 *) mem, sizeof(T) * num); } @@ -85,14 +85,14 @@ struct NoopAllocator final : Allocator /// available and supported it can allocate over-aligned memory. struct HeapAllocator final : Allocator { - virtual bool alloc(usize alignment, usize size, u8 *&mem) override; + virtual bool alloc(usize alignment, usize size, u8 *& mem) override; - virtual bool alloc_zeroed(usize alignment, usize size, u8 *&mem) override; + virtual bool alloc_zeroed(usize alignment, usize size, u8 *& mem) override; virtual bool realloc(usize alignment, usize old_size, usize new_size, - u8 *&mem) override; + u8 *& mem) override; - virtual void dealloc(usize alignment, u8 *mem, usize size) override; + virtual void dealloc(usize alignment, u8 * mem, usize size) override; }; extern NoopAllocator noop_allocator_impl; @@ -100,53 +100,53 @@ extern HeapAllocator heap_allocator_impl; struct AllocatorImpl { - Allocator *self = &heap_allocator_impl; + Allocator * self = &heap_allocator_impl; [[nodiscard]] constexpr bool alloc(usize alignment, usize size, - u8 *&mem) const + u8 *& mem) const { return self->alloc(alignment, size, mem); } [[nodiscard]] constexpr bool alloc_zeroed(usize alignment, usize size, - u8 *&mem) const + u8 *& mem) const { return self->alloc_zeroed(alignment, size, mem); } [[nodiscard]] constexpr bool realloc(usize alignment, usize old_size, - usize new_size, u8 *&mem) const + usize new_size, u8 *& mem) const { return self->realloc(alignment, old_size, new_size, mem); } - constexpr void dealloc(usize alignment, u8 *mem, usize size) const + constexpr void dealloc(usize alignment, u8 * mem, usize size) const { self->dealloc(alignment, mem, size); } template - [[nodiscard]] constexpr bool nalloc(usize num, T *&mem) const + [[nodiscard]] constexpr bool nalloc(usize num, T *& mem) const { return self->alloc(alignof(T), sizeof(T) * num, (u8 *&) mem); } template - [[nodiscard]] constexpr bool nalloc_zeroed(usize num, T *&mem) const + [[nodiscard]] constexpr bool nalloc_zeroed(usize num, T *& mem) const { return self->alloc_zeroed(alignof(T), sizeof(T) * num, (u8 *&) mem); } template [[nodiscard]] constexpr bool nrealloc(usize old_num, usize new_num, - T *&mem) const + T *& mem) const { return self->realloc(alignof(T), sizeof(T) * old_num, sizeof(T) * new_num, (u8 *&) mem); } template - constexpr void ndealloc(T *mem, usize num) const + constexpr void ndealloc(T * mem, usize num) const { self->dealloc(alignof(T), (u8 *) mem, sizeof(T) * num); } diff --git a/ashura/std/allocators.h b/ashura/std/allocators.h index 5fb78901..88afbc6d 100644 --- a/ashura/std/allocators.h +++ b/ashura/std/allocators.h @@ -12,28 +12,30 @@ namespace ash /// @param alignment actual alignment requested from allocator struct Arena final : Allocator { - u8 *begin; - u8 *end; - u8 *offset; + u8 * begin; + u8 * end; + u8 * offset; constexpr Arena() : begin{nullptr}, end{nullptr}, offset{nullptr} { } - constexpr Arena(u8 *begin, u8 *end, u8 *offset) : - begin{begin}, end{end}, offset{offset} + constexpr Arena(u8 * begin, u8 * end, u8 * offset) : + begin{begin}, + end{end}, + offset{offset} { } - constexpr Arena(u8 *begin, u8 *end) : begin{begin}, end{end}, offset{begin} + constexpr Arena(u8 * begin, u8 * end) : begin{begin}, end{end}, offset{begin} { } - constexpr Arena(Arena const &) = default; - constexpr Arena(Arena &&) = default; - constexpr Arena &operator=(Arena const &) = default; - constexpr Arena &operator=(Arena &&) = default; - constexpr ~Arena() = default; + constexpr Arena(Arena const &) = default; + constexpr Arena(Arena &&) = default; + constexpr Arena & operator=(Arena const &) = default; + constexpr Arena & operator=(Arena &&) = default; + constexpr ~Arena() = default; [[nodiscard]] constexpr usize size() const { @@ -56,7 +58,7 @@ struct Arena final : Allocator } [[nodiscard]] virtual bool alloc(usize alignment, usize size, - u8 *&mem) override + u8 *& mem) override { if (size == 0) { @@ -64,8 +66,8 @@ struct Arena final : Allocator return true; } - u8 *aligned = align_ptr(alignment, offset); - u8 *new_offset = aligned + size; + u8 * aligned = align_ptr(alignment, offset); + u8 * new_offset = aligned + size; if (new_offset > end) { mem = nullptr; @@ -78,7 +80,7 @@ struct Arena final : Allocator } [[nodiscard]] virtual bool alloc_zeroed(usize alignment, usize size, - u8 *&mem) override + u8 *& mem) override { if (size == 0) { @@ -97,7 +99,7 @@ struct Arena final : Allocator } [[nodiscard]] virtual bool realloc(usize alignment, usize old_size, - usize new_size, u8 *&mem) override + usize new_size, u8 *& mem) override { // if it is the last allocation, just extend the offset if (((mem + old_size) == offset) && ((mem + new_size) <= end)) @@ -106,7 +108,7 @@ struct Arena final : Allocator return true; } - u8 *new_mem; + u8 * new_mem; if (!alloc(alignment, new_size, new_mem)) { @@ -119,7 +121,7 @@ struct Arena final : Allocator return true; } - virtual void dealloc(usize alignment, u8 *mem, usize size) override + virtual void dealloc(usize alignment, u8 * mem, usize size) override { (void) alignment; // best-case: stack allocation, we can free memory by adjusting to the @@ -168,23 +170,24 @@ struct ArenaPoolCfg struct ArenaPool final : Allocator { AllocatorImpl source = {}; - Arena *arenas = nullptr; + Arena * arenas = nullptr; usize num_arenas = 0; usize current_arena = 0; ArenaPoolCfg cfg = {}; ArenaPool() = default; - explicit ArenaPool(AllocatorImpl source, ArenaPoolCfg const &cfg = {}) : - source{source}, cfg{cfg} + explicit ArenaPool(AllocatorImpl source, ArenaPoolCfg const & cfg = {}) : + source{source}, + cfg{cfg} { } ArenaPool(ArenaPool const &) = delete; - ArenaPool &operator=(ArenaPool const &) = delete; + ArenaPool & operator=(ArenaPool const &) = delete; - ArenaPool(ArenaPool &&other) : + ArenaPool(ArenaPool && other) : source{other.source}, arenas{other.arenas}, num_arenas{other.num_arenas}, @@ -197,7 +200,7 @@ struct ArenaPool final : Allocator other.current_arena = 0; } - ArenaPool &operator=(ArenaPool &&other) + ArenaPool & operator=(ArenaPool && other) { if (this == &other) [[unlikely]] { @@ -274,7 +277,7 @@ struct ArenaPool final : Allocator } [[nodiscard]] virtual bool alloc(usize alignment, usize size, - u8 *&mem) override + u8 *& mem) override { if (size == 0) { @@ -309,7 +312,7 @@ struct ArenaPool final : Allocator return false; } - u8 *arena_mem; + u8 * arena_mem; if (!source.alloc(cfg.arena_alignment, arena_size, arena_mem)) { @@ -324,7 +327,7 @@ struct ArenaPool final : Allocator return false; } - Arena *arena = new (arenas + num_arenas) + Arena * arena = new (arenas + num_arenas) Arena{arena_mem, arena_mem + arena_size, arena_mem}; current_arena = num_arenas; @@ -340,7 +343,7 @@ struct ArenaPool final : Allocator } [[nodiscard]] virtual bool alloc_zeroed(usize alignment, usize size, - u8 *&mem) override + u8 *& mem) override { if (!alloc(alignment, size, mem)) { @@ -351,7 +354,7 @@ struct ArenaPool final : Allocator } [[nodiscard]] virtual bool realloc(usize alignment, usize old_size, - usize new_size, u8 *&mem) override + usize new_size, u8 *& mem) override { if (new_size > cfg.max_arena_size) { @@ -360,7 +363,7 @@ struct ArenaPool final : Allocator if (num_arenas != 0) { - Arena &arena = arenas[current_arena]; + Arena & arena = arenas[current_arena]; if (arena.offset == (mem + old_size)) { // try to change the allocation if it was the last allocation @@ -385,7 +388,7 @@ struct ArenaPool final : Allocator } } - u8 *new_mem; + u8 * new_mem; if (!alloc(alignment, new_size, new_mem)) { return false; @@ -397,7 +400,7 @@ struct ArenaPool final : Allocator return true; } - virtual void dealloc(usize alignment, u8 *mem, usize size) override + virtual void dealloc(usize alignment, u8 * mem, usize size) override { (void) alignment; if (mem == nullptr || size == 0 || num_arenas == 0) @@ -407,7 +410,7 @@ struct ArenaPool final : Allocator // we can try to reclaim some memory, although we'd lose alignment padding. // best case: if is at end of arena, shrink arena. - Arena &arena = arenas[current_arena]; + Arena & arena = arenas[current_arena]; if (arena.begin == mem && arena.offset == (mem + size)) { arena.reclaim(); diff --git a/ashura/std/async.cc b/ashura/std/async.cc index fafa29c8..cb1ba513 100644 --- a/ashura/std/async.cc +++ b/ashura/std/async.cc @@ -32,7 +32,8 @@ struct TaskArena { return Flex{ {layout>, - Layout{.alignment = MAX_STANDARD_ALIGNMENT, .size = TASK_ARENA_SIZE}}}; + Layout{.alignment = MAX_STANDARD_ALIGNMENT, .size = TASK_ARENA_SIZE}} + }; } }; @@ -67,11 +68,13 @@ struct Task Uninit uninit = noop; /// @brief arena this task was allocated from. always non-null. - ListNode *arena = nullptr; + ListNode * arena = nullptr; static constexpr auto node_flex(Layout frame_layout) { - return Flex{{layout>, frame_layout}}; + return Flex{ + {layout>, frame_layout} + }; } }; @@ -113,11 +116,11 @@ struct TaskAllocator SpinLock lock{}; List list{}; - ListNode *pop() + ListNode * pop() { - LockGuard guard{lock}; + LockGuard guard{lock}; // return the most recently used arena - ListNode *arena = list.pop_back(); + ListNode * arena = list.pop_back(); return arena; } @@ -128,8 +131,8 @@ struct TaskAllocator /// allocate a new arena and make it the current arena. struct alignas(CACHELINE_ALIGNMENT) { - SpinLock lock{}; - ListNode *node = nullptr; + SpinLock lock{}; + ListNode * node = nullptr; } current_arena{}; @@ -141,9 +144,9 @@ struct TaskAllocator TaskAllocator(TaskAllocator &&) = default; - TaskAllocator &operator=(TaskAllocator const &) = delete; + TaskAllocator & operator=(TaskAllocator const &) = delete; - TaskAllocator &operator=(TaskAllocator &&) = default; + TaskAllocator & operator=(TaskAllocator &&) = default; ~TaskAllocator() { @@ -158,7 +161,7 @@ struct TaskAllocator } } - void release_arena(ListNode *arena) + void release_arena(ListNode * arena) { // decrease alias count of arena, if only alias left, add to the arena // free list. @@ -170,19 +173,19 @@ struct TaskAllocator } } - bool alloc_arena(ListNode *&arena) + bool alloc_arena(ListNode *& arena) { Flex const flex = TaskArena::node_flex(); Layout const layout = flex.layout(); - u8 *head; + u8 * head; if (!source.alloc(layout.alignment, layout.size, head)) { return false; } - u8 *memory; + u8 * memory; flex.unpack(head, arena, memory); new (arena) ListNode{ @@ -191,17 +194,17 @@ struct TaskAllocator return true; } - void dealloc_arena(ListNode *arena) + void dealloc_arena(ListNode * arena) { Flex const flex = TaskArena::node_flex(); Layout const layout = flex.layout(); source.dealloc(layout.alignment, (u8 *) arena, layout.size); } - bool request_arena(ListNode *&arena) + bool request_arena(ListNode *& arena) { /// get from free list, otherwise allocate a new arena - ListNode *a = free_list.pop(); + ListNode * a = free_list.pop(); if (a != nullptr) { arena = a; @@ -210,13 +213,13 @@ struct TaskAllocator return alloc_arena(arena); } - static bool alloc_task(ListNode &arena, TaskInfo const &info, - ListNode *&task) + static bool alloc_task(ListNode & arena, TaskInfo const & info, + ListNode *& task) { Flex const flex = Task::node_flex(info.frame_layout); Layout const layout = flex.layout(); - u8 *head; + u8 * head; if (!arena.v.arena.alloc(layout.alignment, layout.size, head)) { @@ -225,37 +228,39 @@ struct TaskAllocator arena.v.ac.alias(); - u8 *ctx; + u8 * ctx; flex.unpack(head, task, ctx); - new (task) ListNode{.v{.frame_layout = info.frame_layout, - .poll = info.poll, - .run = info.run, - .uninit = info.uninit, - .arena = &arena}}; + new (task) ListNode{ + .v{.frame_layout = info.frame_layout, + .poll = info.poll, + .run = info.run, + .uninit = info.uninit, + .arena = &arena} + }; info.init(ctx); return true; } - static void uninit_task(ListNode *task) + static void uninit_task(ListNode * task) { Flex const flex = Task::node_flex(task->v.frame_layout); - u8 *ctx; + u8 * ctx; flex.unpack(task, task, ctx); task->v.uninit(ctx); } - void release_task(ListNode *task) + void release_task(ListNode * task) { - ListNode *arena = task->v.arena; + ListNode * arena = task->v.arena; uninit_task(task); release_arena(arena); } - bool create_task(TaskInfo const &info, ListNode *&task) + bool create_task(TaskInfo const & info, ListNode *& task) { LockGuard guard{current_arena.lock}; @@ -307,9 +312,9 @@ struct TaskQueue TaskQueue(TaskQueue &&) = default; - TaskQueue &operator=(TaskQueue const &) = delete; + TaskQueue & operator=(TaskQueue const &) = delete; - TaskQueue &operator=(TaskQueue &&) = default; + TaskQueue & operator=(TaskQueue &&) = default; ~TaskQueue() = default; @@ -318,24 +323,24 @@ struct TaskQueue return tasks.is_empty(); } - ListNode *pop_task() + ListNode * pop_task() { - LockGuard guard{lock}; - ListNode *t = tasks.pop_front(); + LockGuard guard{lock}; + ListNode * t = tasks.pop_front(); return t; } /// @brief push task on the queue /// @param t non-null task node - void push_task(ListNode *t) + void push_task(ListNode * t) { LockGuard guard{lock}; tasks.push_back(t); } - void push_task(TaskInfo const &info) + void push_task(TaskInfo const & info) { - ListNode *t; + ListNode * t; CHECK(allocator.create_task(info, t)); push_task(t); } @@ -351,7 +356,10 @@ struct alignas(CACHELINE_ALIGNMENT) TaskThread std::thread thread; TaskThread(AllocatorImpl allocator, nanoseconds max_sleep) : - queue{allocator}, stop_token{}, max_sleep{max_sleep}, thread{} + queue{allocator}, + stop_token{}, + max_sleep{max_sleep}, + thread{} { } }; @@ -395,29 +403,29 @@ struct ASH_DLL_EXPORT SchedulerImpl : Scheduler, Pin<> CHECK_DESC(main_thread_id == std::this_thread::get_id(), "Scheduler can only be joined on the main thread"); - for (TaskThread &t : dedicated_threads) + for (TaskThread & t : dedicated_threads) { t.stop_token.request_stop(); } - for (TaskThread &t : worker_threads) + for (TaskThread & t : worker_threads) { t.stop_token.request_stop(); } - for (TaskThread &t : dedicated_threads) + for (TaskThread & t : dedicated_threads) { t.thread.join(); } - for (TaskThread &t : worker_threads) + for (TaskThread & t : worker_threads) { t.thread.join(); } while (true) { - ListNode *task = main_queue.pop_task(); + ListNode * task = main_queue.pop_task(); if (task == nullptr) { @@ -430,7 +438,7 @@ struct ASH_DLL_EXPORT SchedulerImpl : Scheduler, Pin<> joined = true; } - static void thread_loop(TaskAllocator &a, TaskQueue &q, StopTokenState &s, + static void thread_loop(TaskAllocator & a, TaskQueue & q, StopTokenState & s, nanoseconds max_sleep) { u64 poll = 0; @@ -443,7 +451,7 @@ struct ASH_DLL_EXPORT SchedulerImpl : Scheduler, Pin<> break; } - ListNode *task = q.pop_task(); + ListNode * task = q.pop_task(); if (task == nullptr) [[unlikely]] { @@ -454,7 +462,7 @@ struct ASH_DLL_EXPORT SchedulerImpl : Scheduler, Pin<> Flex const flex = Task::node_flex(task->v.frame_layout); - u8 *frame; + u8 * frame; flex.unpack(task, task, frame); @@ -483,7 +491,7 @@ struct ASH_DLL_EXPORT SchedulerImpl : Scheduler, Pin<> // run loop done. purge pending tasks while (true) { - ListNode *task = q.pop_task(); + ListNode * task = q.pop_task(); if (task == nullptr) { @@ -494,7 +502,7 @@ struct ASH_DLL_EXPORT SchedulerImpl : Scheduler, Pin<> } } - static void main_thread_loop(TaskAllocator &a, TaskQueue &q, + static void main_thread_loop(TaskAllocator & a, TaskQueue & q, nanoseconds grace_period, nanoseconds duration) { steady_clock::time_point const begin = steady_clock::now(); @@ -508,7 +516,7 @@ struct ASH_DLL_EXPORT SchedulerImpl : Scheduler, Pin<> break; } - ListNode *task = q.pop_task(); + ListNode * task = q.pop_task(); if (task == nullptr) [[unlikely]] { @@ -527,7 +535,7 @@ struct ASH_DLL_EXPORT SchedulerImpl : Scheduler, Pin<> Flex const flex = Task::node_flex(task->v.frame_layout); - u8 *frame; + u8 * frame; flex.unpack(task, task, frame); @@ -561,20 +569,20 @@ struct ASH_DLL_EXPORT SchedulerImpl : Scheduler, Pin<> return worker_threads.size32(); } - virtual void schedule_dedicated(TaskInfo const &info, u32 thread) override + virtual void schedule_dedicated(TaskInfo const & info, u32 thread) override { CHECK_DESC(thread < dedicated_threads.size32(), "Invalid dedicated thread ID"); - TaskThread &t = dedicated_threads[thread]; + TaskThread & t = dedicated_threads[thread]; t.queue.push_task(info); } - virtual void schedule_worker(TaskInfo const &info) override + virtual void schedule_worker(TaskInfo const & info) override { worker_queue.push_task(info); } - virtual void schedule_main(TaskInfo const &info) override + virtual void schedule_main(TaskInfo const & info) override { main_queue.push_task(info); } @@ -586,7 +594,7 @@ struct ASH_DLL_EXPORT SchedulerImpl : Scheduler, Pin<> } }; -ASH_C_LINKAGE ASH_DLL_EXPORT Scheduler *scheduler = nullptr; +ASH_C_LINKAGE ASH_DLL_EXPORT Scheduler * scheduler = nullptr; void Scheduler::init(AllocatorImpl allocator, std::thread::id main_thread_id, Span dedicated_thread_sleep, @@ -602,7 +610,7 @@ void Scheduler::init(AllocatorImpl allocator, std::thread::id main_thread_id, alignas(SchedulerImpl) static u8 storage[sizeof(SchedulerImpl)]; - SchedulerImpl *impl = new (storage) SchedulerImpl{allocator, main_thread_id}; + SchedulerImpl * impl = new (storage) SchedulerImpl{allocator, main_thread_id}; u32 const num_dedicated_threads = dedicated_thread_sleep.size32(); u32 const num_worker_threads = worker_thread_sleep.size32(); @@ -616,20 +624,20 @@ void Scheduler::init(AllocatorImpl allocator, std::thread::id main_thread_id, for (u32 i = 0; i < num_dedicated_threads; i++) { impl->dedicated_threads.push(allocator, dedicated_thread_sleep[i]).unwrap(); - TaskThread &t = impl->dedicated_threads[i]; - t.thread = std::thread{[&t] { + TaskThread & t = impl->dedicated_threads[i]; + t.thread = std::thread{[&t] { SchedulerImpl::thread_loop(t.queue.allocator, t.queue, t.stop_token, - t.max_sleep); + t.max_sleep); }}; } for (u32 i = 0; i < num_worker_threads; i++) { impl->worker_threads.push(allocator, worker_thread_sleep[i]).unwrap(); - TaskThread &t = impl->worker_threads[i]; - t.thread = std::thread{[&t, impl] { + TaskThread & t = impl->worker_threads[i]; + t.thread = std::thread{[&t, impl] { SchedulerImpl::thread_loop(impl->worker_queue.allocator, - impl->worker_queue, t.stop_token, t.max_sleep); + impl->worker_queue, t.stop_token, t.max_sleep); }}; } @@ -643,4 +651,4 @@ void Scheduler::uninit() scheduler = nullptr; } -} // namespace ash \ No newline at end of file +} // namespace ash diff --git a/ashura/std/async.h b/ashura/std/async.h index 22baa5d3..b70b298c 100644 --- a/ashura/std/async.h +++ b/ashura/std/async.h @@ -117,20 +117,20 @@ struct SpinLock template struct LockGuard { - L *lock_; + L * lock_; - explicit LockGuard(L &lock) : lock_{&lock} + explicit LockGuard(L & lock) : lock_{&lock} { lock_->lock(); } LockGuard(LockGuard const &) = delete; - LockGuard &operator=(LockGuard const &) = delete; + LockGuard & operator=(LockGuard const &) = delete; LockGuard(LockGuard &&) = delete; - LockGuard &operator=(LockGuard &&) = delete; + LockGuard & operator=(LockGuard &&) = delete; ~LockGuard() { @@ -192,20 +192,20 @@ struct ReadWriteLock struct ReadGuard { - ReadWriteLock *lock_; + ReadWriteLock * lock_; - explicit ReadGuard(ReadWriteLock &lock) : lock_{&lock} + explicit ReadGuard(ReadWriteLock & lock) : lock_{&lock} { lock_->lock_read(); } ReadGuard(ReadGuard const &) = delete; - ReadGuard &operator=(ReadGuard const &) = delete; + ReadGuard & operator=(ReadGuard const &) = delete; ReadGuard(ReadGuard &&) = delete; - ReadGuard &operator=(ReadGuard &&) = delete; + ReadGuard & operator=(ReadGuard &&) = delete; ~ReadGuard() { @@ -215,20 +215,20 @@ struct ReadGuard struct WriteGuard { - ReadWriteLock *lock_; + ReadWriteLock * lock_; - explicit WriteGuard(ReadWriteLock &lock) : lock_{&lock} + explicit WriteGuard(ReadWriteLock & lock) : lock_{&lock} { lock_->lock_write(); } WriteGuard(WriteGuard const &) = delete; - WriteGuard &operator=(WriteGuard const &) = delete; + WriteGuard & operator=(WriteGuard const &) = delete; WriteGuard(WriteGuard &&) = delete; - WriteGuard &operator=(WriteGuard &&) = delete; + WriteGuard & operator=(WriteGuard &&) = delete; ~WriteGuard() { @@ -251,6 +251,7 @@ template struct AtomicInit { AtomicInitStage stage_; + union { T v_; @@ -261,15 +262,16 @@ struct AtomicInit } template - constexpr AtomicInit(V<0>, Args &&...args) : - stage_{AtomicInitStage::Init}, v_{static_cast(args)...} + constexpr AtomicInit(V<0>, Args &&... args) : + stage_{AtomicInitStage::Init}, + v_{static_cast(args)...} { } - constexpr AtomicInit(AtomicInit const &) = delete; - constexpr AtomicInit(AtomicInit &&) = delete; - constexpr AtomicInit &operator=(AtomicInit const &) = delete; - constexpr AtomicInit &operator=(AtomicInit &&) = delete; + constexpr AtomicInit(AtomicInit const &) = delete; + constexpr AtomicInit(AtomicInit &&) = delete; + constexpr AtomicInit & operator=(AtomicInit const &) = delete; + constexpr AtomicInit & operator=(AtomicInit &&) = delete; ~AtomicInit() { @@ -285,7 +287,7 @@ struct AtomicInit } template - [[nodiscard]] bool init(Args &&...args) + [[nodiscard]] bool init(Args &&... args) { std::atomic_ref stage{stage_}; AtomicInitStage expected = AtomicInitStage::Uninit; @@ -307,7 +309,7 @@ struct AtomicInit /// @brief Get the wrapped value /// @return null if value is not initialized yet - T *get() + T * get() { std::atomic_ref stage{stage_}; if (stage.load(std::memory_order_acquire) != AtomicInitStage::Init) @@ -326,7 +328,9 @@ struct [[nodiscard]] Sync ReadWriteLock lock_; template - constexpr Sync(Args &&...args) : data_{static_cast(args)...}, lock_{} + constexpr Sync(Args &&... args) : + data_{static_cast(args)...}, + lock_{} { } @@ -334,21 +338,21 @@ struct [[nodiscard]] Sync constexpr Sync(Sync &&) = delete; - constexpr Sync &operator=(Sync const &) = delete; + constexpr Sync & operator=(Sync const &) = delete; - constexpr Sync &operator=(Sync &&) = delete; + constexpr Sync & operator=(Sync &&) = delete; constexpr ~Sync() = default; template Op> - void read(Op &&op) + void read(Op && op) { ReadGuard guard{lock_}; static_cast(op)(data_); } template Op> - void write(Op &&op) + void write(Op && op) { WriteGuard guard{lock_}; static_cast(op)(data_); @@ -388,7 +392,8 @@ struct SemaphoreState u64 stage_; explicit constexpr SemaphoreState(u64 num_stages) : - num_stages_{num_stages}, stage_{0} + num_stages_{num_stages}, + stage_{0} { } @@ -533,9 +538,9 @@ inline Result create_stop_token(AllocatorImpl allocator) /// @param any if to wait for all semaphores or atleast 1 semaphore. /// @returns returns if the semaphore await operation completed successfully /// based on the `any` criteria. -[[nodiscard]] inline bool await_semaphores(Span sems, - Span stages, - nanoseconds timeout) +[[nodiscard]] inline bool await_semaphores(Span sems, + Span stages, + nanoseconds timeout) { CHECK(sems.size() == stages.size()); usize const n = sems.size(); @@ -558,9 +563,9 @@ inline Result create_stop_token(AllocatorImpl allocator) { for (; next < n; next++) { - SemaphoreState *const &s = sems[next]; - u64 const stage = min(stages[next], s->num_stages_ - 1); - bool const is_ready = stage < s->stage(); + SemaphoreState * const & s = sems[next]; + u64 const stage = min(stages[next], s->num_stages_ - 1); + bool const is_ready = stage < s->stage(); if (!is_ready) { @@ -623,7 +628,8 @@ struct [[nodiscard]] Stream Semaphore semaphore_; Stream(Rc data, Semaphore semaphore) : - data_{std::move(data)}, semaphore_{std::move(semaphore)} + data_{std::move(data)}, + semaphore_{std::move(semaphore)} { } @@ -643,14 +649,14 @@ struct [[nodiscard]] Stream } template F> - void yield_unseq(F &&op, u64 increment) const + void yield_unseq(F && op, u64 increment) const { static_cast(op)(*data_.get()); semaphore_->increment(increment); } template F> - void yield_seq(F &&op, u64 stage) const + void yield_seq(F && op, u64 stage) const { static_cast(op)(*data_.get()); CHECK_DESC(semaphore_->signal(stage + 1), @@ -660,7 +666,7 @@ struct [[nodiscard]] Stream template Result> stream_inplace(AllocatorImpl allocator, u64 num_stages, - Args &&...args) + Args &&... args) { Result data = rc_inplace(allocator, static_cast(args)...); if (!data) @@ -672,7 +678,9 @@ Result> stream_inplace(AllocatorImpl allocator, u64 num_stages, { return Err{}; } - return Ok{Stream{std::move(data.value()), std::move(sem.value())}}; + return Ok{ + Stream{std::move(data.value()), std::move(sem.value())} + }; } template @@ -683,9 +691,9 @@ Result> stream(AllocatorImpl allocator, u64 num_stages, T value) template [[nodiscard]] bool await_streams(nanoseconds timeout, Span stages, - Stream const &...streams) + Stream const &... streams) { - SemaphoreState *semaphores[] = {(streams.semaphore_.get())...}; + SemaphoreState * semaphores[] = {(streams.semaphore_.get())...}; return await_semaphores(semaphores, stages, timeout); } @@ -702,7 +710,8 @@ struct [[nodiscard]] Future u64 stage_; Future(Stream> stream, u64 stage) : - stream_{std::move(stream)}, stage_{stage} + stream_{std::move(stream)}, + stage_{stage} { } @@ -716,18 +725,18 @@ struct [[nodiscard]] Future return stream_.is_ready(stage_); } - T &get() const + T & get() const { - T *data = stream_.data_.get()->get(); + T * data = stream_.data_.get()->get(); CHECK_DESC(data != nullptr, "Called `Future::get()` on a pending Future"); return *data; } template - void complete(Args &&...args) const + void complete(Args &&... args) const { stream_.yield_seq( - [&](AtomicInit &v) { + [&](AtomicInit & v) { bool const init = v.init(static_cast(args)...); CHECK_DESC( init, @@ -745,22 +754,24 @@ Result> future(AllocatorImpl allocator) { return Err{}; } - return Ok{Future{std::move(stream.value()), 0}}; + return Ok{ + Future{std::move(stream.value()), 0} + }; } template [[nodiscard]] bool await_futures(nanoseconds timeout, - Future const &...futures) + Future const &... futures) { - SemaphoreState *semaphores[] = {(futures.stream_.semaphore_.get())...}; - u64 const stages[] = {futures.stage_...}; + SemaphoreState * semaphores[] = {(futures.stream_.semaphore_.get())...}; + u64 const stages[] = {futures.stage_...}; return await_semaphores(semaphores, stages, timeout); } constexpr usize MAX_TASK_FRAME_SIZE = PAGE_SIZE >> 4; template -concept TaskFrame = requires(F f) { +concept TaskFrame = requires (F f) { { !f.poll() }; { !f.run() }; } && (sizeof(F) <= MAX_TASK_FRAME_SIZE); @@ -822,24 +833,24 @@ struct TaskSchedule /// @brief Wrap a Task frame /// @return TaskInfo struct to be passed to the scheduler for execution template -TaskInfo to_task_info(F &frame) +TaskInfo to_task_info(F & frame) { - Fn init = fn(&frame, [](F *frame, void *mem) { + Fn init = fn(&frame, [](F * frame, void * mem) { new (mem) F{static_cast(*frame)}; }); - TaskInfo::Uninit uninit = [](void *f) { - F *frame = reinterpret_cast(f); + TaskInfo::Uninit uninit = [](void * f) { + F * frame = reinterpret_cast(f); frame->~F(); }; - TaskInfo::Poll poll = [](void *f) -> bool { - F *frame = reinterpret_cast(f); + TaskInfo::Poll poll = [](void * f) -> bool { + F * frame = reinterpret_cast(f); return frame->poll(); }; - TaskInfo::Run run = [](void *f) -> bool { - F *frame = reinterpret_cast(f); + TaskInfo::Run run = [](void * f) -> bool { + F * frame = reinterpret_cast(f); return frame->run(); }; @@ -900,16 +911,16 @@ struct Scheduler /// @brief Schedule task to a specific dedicated thread /// @param info Task frame information /// @param thread the index of the dedicated thread to schedule to - virtual void schedule_dedicated(TaskInfo const &info, u32 thread) = 0; + virtual void schedule_dedicated(TaskInfo const & info, u32 thread) = 0; /// @brief Schedule task to a worker thread /// @param info Task frame information - virtual void schedule_worker(TaskInfo const &info) = 0; + virtual void schedule_worker(TaskInfo const & info) = 0; /// @brief Schedule task to the main thread. The tasks are executed once the /// main thread loop runs. /// @param info Task frame information - virtual void schedule_main(TaskInfo const &info) = 0; + virtual void schedule_main(TaskInfo const & info) = 0; /// @brief Execute work on the main thread queue /// @param grace_period minimum time (within duration) to wait for tasks when @@ -919,7 +930,7 @@ struct Scheduler nanoseconds duration) = 0; template - void schedule(F &&task, TaskSchedule schedule) + void schedule(F && task, TaskSchedule schedule) { TaskInfo info = to_task_info(task); @@ -943,18 +954,18 @@ struct Scheduler /// @brief Global scheduler object. Designed for hooking across DLLs. Must be /// initialized with `Scheduler::init()` and uninitialized with /// `Scheduler::uninit()`. -ASH_C_LINKAGE ASH_DLL_EXPORT Scheduler *scheduler; +ASH_C_LINKAGE ASH_DLL_EXPORT Scheduler * scheduler; namespace async { template -concept Poll = requires(P p) { +concept Poll = requires (P p) { { p() && true }; }; template -concept Run = requires(R r) { +concept Run = requires (R r) { { r() && true }; }; @@ -981,16 +992,17 @@ struct [[nodiscard]] AwaitStreams Array stages; - explicit AwaitStreams(Array const &stages, + explicit AwaitStreams(Array const & stages, Stream... streams) : - streams{std::move(streams)...}, stages{stages} + streams{std::move(streams)...}, + stages{stages} { } bool operator()() const { return apply( - [this](auto const &...s) { + [this](auto const &... s) { return await_streams(nanoseconds{0}, stages, s...); }, streams); @@ -1009,7 +1021,7 @@ struct [[nodiscard]] AwaitFutures bool operator()() const { return apply( - [](auto const &...f) { return await_futures(nanoseconds{0}, f...); }, + [](auto const &... f) { return await_futures(nanoseconds{0}, f...); }, futures); } }; @@ -1076,7 +1088,7 @@ void once(Tuple fns, P poll = {}, TaskSchedule schedule = {}) /// @param poll Poller functor that returns true when ready /// @param schedule How to schedule the task template - requires(Convertible, bool>) +requires (Convertible, bool>) void loop(F fn, P poll = {}, TaskSchedule schedule = {}) { TaskBody body{[fn = std::move(fn)]() mutable -> bool { return fn(); }, @@ -1094,8 +1106,8 @@ void loop(F fn, P poll = {}, TaskSchedule schedule = {}) /// @param poll Poller functor that returns true when ready /// @param schedule How to schedule the task template F, Poll P = Ready> - requires(Same, void> || - Convertible, bool>) +requires (Same, void> || + Convertible, bool>) void repeat(F fn, u64 n, P poll = {}, TaskSchedule schedule = {}) { if (n == 0) @@ -1132,7 +1144,7 @@ void repeat(F fn, u64 n, P poll = {}, TaskSchedule schedule = {}) /// @param poll Poller functor that returns true when ready /// @param schedule How to schedule the shards template -void shard(Fn fn, Rc const &state, u64 n, +void shard(Fn fn, Rc const & state, u64 n, P poll = {}, TaskSchedule schedule = {}) { if (n == 0) diff --git a/ashura/std/buffer.h b/ashura/std/buffer.h index 561cb667..3ae9f90b 100644 --- a/ashura/std/buffer.h +++ b/ashura/std/buffer.h @@ -11,11 +11,11 @@ namespace ash template struct [[nodiscard]] Buffer { - T *data_ = nullptr; + T * data_ = nullptr; usize capacity_ = 0; usize size_ = 0; - constexpr T *data() const + constexpr T * data() const { return data_; } @@ -65,7 +65,7 @@ constexpr Span span(Buffer buffer) template struct [[nodiscard]] RingBuffer { - T *data_ = nullptr; + T * data_ = nullptr; usize capacity_ = 0; usize size_ = 0; usize consume_next_ = 0; @@ -85,7 +85,7 @@ struct [[nodiscard]] RingBuffer return size_ == 0; } - [[nodiscard]] constexpr bool try_consume(T *out) + [[nodiscard]] constexpr bool try_consume(T * out) { if (size_ == 0) { @@ -100,7 +100,7 @@ struct [[nodiscard]] RingBuffer return true; } - [[nodiscard]] constexpr bool try_produce(T const &in) + [[nodiscard]] constexpr bool try_produce(T const & in) { if (size_ == capacity_) { @@ -123,7 +123,7 @@ struct [[nodiscard]] SPSCRingBuffer alignas(CACHELINE_ALIGNMENT) usize produce_next_ = 0; alignas(CACHELINE_ALIGNMENT) usize consume_next_ = 0; - T *data_ = nullptr; + T * data_ = nullptr; usize capacity_ = 0; usize capacity() const @@ -131,7 +131,7 @@ struct [[nodiscard]] SPSCRingBuffer return capacity_; } - [[nodiscard]] bool try_consume(T *out) + [[nodiscard]] bool try_consume(T * out) { std::atomic_ref p{produce_next_}; std::atomic_ref c{consume_next_}; @@ -153,7 +153,7 @@ struct [[nodiscard]] SPSCRingBuffer return true; } - [[nodiscard]] bool try_produce(T const &in) + [[nodiscard]] bool try_produce(T const & in) { std::atomic_ref p{produce_next_}; std::atomic_ref c{consume_next_}; @@ -174,4 +174,4 @@ struct [[nodiscard]] SPSCRingBuffer } }; -} // namespace ash \ No newline at end of file +} // namespace ash diff --git a/ashura/std/cfg.h b/ashura/std/cfg.h index 29947b64..d5291a12 100644 --- a/ashura/std/cfg.h +++ b/ashura/std/cfg.h @@ -1,4 +1,3 @@ - /// SPDX-License-Identifier: MIT #pragma once @@ -7,7 +6,8 @@ /*********************** COMPILERS ***********************/ -#if defined(__GNUC__) // any compiler that implements the GNU compiler +#if defined( \ + __GNUC__) // any compiler that implements the GNU compiler \ // extensions # define ASH_COMPILER_GNUC 1 #else diff --git a/ashura/std/dyn.h b/ashura/std/dyn.h index 9e200ca2..cf695202 100644 --- a/ashura/std/dyn.h +++ b/ashura/std/dyn.h @@ -31,14 +31,14 @@ struct [[nodiscard]] Dyn constexpr Dyn(Dyn const &) = delete; - constexpr Dyn &operator=(Dyn const &) = delete; + constexpr Dyn & operator=(Dyn const &) = delete; - constexpr Dyn(Dyn &&other) : inner{other.inner} + constexpr Dyn(Dyn && other) : inner{other.inner} { other.inner = Inner{}; } - constexpr Dyn &operator=(Dyn &&other) + constexpr Dyn & operator=(Dyn && other) { if (this == &other) [[unlikely]] { @@ -77,7 +77,7 @@ struct [[nodiscard]] Dyn } template - constexpr decltype(auto) operator()(Args &&...args) const + constexpr decltype(auto) operator()(Args &&... args) const { return inner.handle(static_cast(args)...); } @@ -90,9 +90,9 @@ struct [[nodiscard]] Dyn template constexpr Result, Void> dyn_inplace(AllocatorImpl allocator, - Args &&...args) + Args &&... args) { - T *object; + T * object; if (!allocator.nalloc(1, object)) [[unlikely]] { return Err{Void{}}; @@ -100,11 +100,13 @@ constexpr Result, Void> dyn_inplace(AllocatorImpl allocator, new (object) T{static_cast(args)...}; - return Ok{Dyn{object, allocator, - fn(object, [](T *object, AllocatorImpl allocator) { - object->~T(); - allocator.ndealloc(object, 1); - })}}; + return Ok{ + Dyn{object, allocator, + fn(object, [](T * object, AllocatorImpl allocator) { + object->~T(); + allocator.ndealloc(object, 1); + })} + }; } template @@ -114,7 +116,7 @@ constexpr Result, Void> dyn(AllocatorImpl allocator, T object) } template -constexpr Dyn transmute(Dyn &&base, H handle) +constexpr Dyn transmute(Dyn && base, H handle) { Dyn t{static_cast(handle), base.inner.allocator, base.inner.uninit}; base.inner.handle = {}; @@ -124,7 +126,7 @@ constexpr Dyn transmute(Dyn &&base, H handle) } template -constexpr Dyn cast(Dyn &&from) +constexpr Dyn cast(Dyn && from) { return transmute(static_cast &&>(from), static_cast(from.get())); diff --git a/ashura/std/enum.gen.h b/ashura/std/enum.gen.h index b339e468..4f8c6ec9 100644 --- a/ashura/std/enum.gen.h +++ b/ashura/std/enum.gen.h @@ -1,4 +1,3 @@ - /// SPDX-License-Identifier: MIT /// Meta-Generated Source Code // clang-format off diff --git a/ashura/std/enum.py b/ashura/std/enum.py index 49bb895c..79235248 100644 --- a/ashura/std/enum.py +++ b/ashura/std/enum.py @@ -10,8 +10,7 @@ def out(code): return file.write(code) -out(f""" -/// SPDX-License-Identifier: MIT +out(f"""/// SPDX-License-Identifier: MIT /// Meta-Generated Source Code // clang-format off #pragma once diff --git a/ashura/std/format.cc b/ashura/std/format.cc index bf589e10..acf88b06 100644 --- a/ashura/std/format.cc +++ b/ashura/std/format.cc @@ -7,7 +7,7 @@ namespace ash { template -bool push_int(fmt::Context const &ctx, fmt::Spec const &spec, IntT value) +bool push_int(fmt::Context const & ctx, fmt::Spec const & spec, IntT value) { int base = 0; @@ -52,7 +52,7 @@ bool push_int(fmt::Context const &ctx, fmt::Spec const &spec, IntT value) } template -bool push_float(fmt::Context const &ctx, fmt::Spec const &spec, FloatT value) +bool push_float(fmt::Context const & ctx, fmt::Spec const & spec, FloatT value) { std::chars_format format = std::chars_format::general; switch (spec.style) @@ -88,71 +88,71 @@ bool push_float(fmt::Context const &ctx, fmt::Spec const &spec, FloatT value) return false; } -bool fmt::push(fmt::Context const &ctx, fmt::Spec const &, bool value) +bool fmt::push(fmt::Context const & ctx, fmt::Spec const &, bool value) { return ctx.push(value ? "true"_str : "false"_str); } -bool fmt::push(fmt::Context const &ctx, fmt::Spec const &spec, u8 value) +bool fmt::push(fmt::Context const & ctx, fmt::Spec const & spec, u8 value) { return push_int(ctx, spec, value); } -bool fmt::push(fmt::Context const &ctx, fmt::Spec const &spec, u16 value) +bool fmt::push(fmt::Context const & ctx, fmt::Spec const & spec, u16 value) { return push_int(ctx, spec, value); } -bool fmt::push(fmt::Context const &ctx, fmt::Spec const &spec, u32 value) +bool fmt::push(fmt::Context const & ctx, fmt::Spec const & spec, u32 value) { return push_int(ctx, spec, value); } -bool fmt::push(fmt::Context const &ctx, fmt::Spec const &spec, u64 value) +bool fmt::push(fmt::Context const & ctx, fmt::Spec const & spec, u64 value) { return push_int(ctx, spec, value); } -bool fmt::push(fmt::Context const &ctx, fmt::Spec const &spec, i8 value) +bool fmt::push(fmt::Context const & ctx, fmt::Spec const & spec, i8 value) { return push_int(ctx, spec, value); } -bool fmt::push(fmt::Context const &ctx, fmt::Spec const &spec, i16 value) +bool fmt::push(fmt::Context const & ctx, fmt::Spec const & spec, i16 value) { return push_int(ctx, spec, value); } -bool fmt::push(fmt::Context const &ctx, fmt::Spec const &spec, i32 value) +bool fmt::push(fmt::Context const & ctx, fmt::Spec const & spec, i32 value) { return push_int(ctx, spec, value); } -bool fmt::push(fmt::Context const &ctx, fmt::Spec const &spec, i64 value) +bool fmt::push(fmt::Context const & ctx, fmt::Spec const & spec, i64 value) { return push_int(ctx, spec, value); } -bool fmt::push(fmt::Context const &ctx, fmt::Spec const &spec, f32 value) +bool fmt::push(fmt::Context const & ctx, fmt::Spec const & spec, f32 value) { return push_float(ctx, spec, value); } -bool fmt::push(fmt::Context const &ctx, fmt::Spec const &spec, f64 value) +bool fmt::push(fmt::Context const & ctx, fmt::Spec const & spec, f64 value) { return push_float(ctx, spec, value); } -bool fmt::push(fmt::Context const &ctx, fmt::Spec const &spec, - Vec2 const &value) +bool fmt::push(fmt::Context const & ctx, fmt::Spec const & spec, + Vec2 const & value) { return push(ctx, spec, "Vec2{") && push(ctx, spec, value.x) && push(ctx, spec, ", ") && push(ctx, spec, value.y) && push(ctx, spec, "}"); } -bool fmt::push(fmt::Context const &ctx, fmt::Spec const &spec, - Vec3 const &value) +bool fmt::push(fmt::Context const & ctx, fmt::Spec const & spec, + Vec3 const & value) { return push(ctx, spec, "Vec3{") && push(ctx, spec, value.x) && push(ctx, spec, ", ") && push(ctx, spec, value.y) && @@ -160,8 +160,8 @@ bool fmt::push(fmt::Context const &ctx, fmt::Spec const &spec, push(ctx, spec, "}"); } -bool fmt::push(fmt::Context const &ctx, fmt::Spec const &spec, - Vec4 const &value) +bool fmt::push(fmt::Context const & ctx, fmt::Spec const & spec, + Vec4 const & value) { return push(ctx, spec, "Vec4{") && push(ctx, spec, value.x) && push(ctx, spec, ", ") && push(ctx, spec, value.y) && @@ -170,16 +170,16 @@ bool fmt::push(fmt::Context const &ctx, fmt::Spec const &spec, push(ctx, spec, "}"); } -bool fmt::push(fmt::Context const &ctx, fmt::Spec const &spec, - Vec2I const &value) +bool fmt::push(fmt::Context const & ctx, fmt::Spec const & spec, + Vec2I const & value) { return push(ctx, spec, "Vec2I{") && push(ctx, spec, value.x) && push(ctx, spec, ", ") && push(ctx, spec, value.y) && push(ctx, spec, "}"); } -bool fmt::push(fmt::Context const &ctx, fmt::Spec const &spec, - Vec3I const &value) +bool fmt::push(fmt::Context const & ctx, fmt::Spec const & spec, + Vec3I const & value) { return push(ctx, spec, "Vec3I{") && push(ctx, spec, value.x) && push(ctx, spec, ", ") && push(ctx, spec, value.y) && @@ -187,8 +187,8 @@ bool fmt::push(fmt::Context const &ctx, fmt::Spec const &spec, push(ctx, spec, "}"); } -bool fmt::push(fmt::Context const &ctx, fmt::Spec const &spec, - Vec4I const &value) +bool fmt::push(fmt::Context const & ctx, fmt::Spec const & spec, + Vec4I const & value) { return push(ctx, spec, "Vec4I{") && push(ctx, spec, value.x) && push(ctx, spec, ", ") && push(ctx, spec, value.y) && @@ -197,16 +197,16 @@ bool fmt::push(fmt::Context const &ctx, fmt::Spec const &spec, push(ctx, spec, "}"); } -bool fmt::push(fmt::Context const &ctx, fmt::Spec const &spec, - Vec2U const &value) +bool fmt::push(fmt::Context const & ctx, fmt::Spec const & spec, + Vec2U const & value) { return push(ctx, spec, "Vec2I{") && push(ctx, spec, value.x) && push(ctx, spec, ", ") && push(ctx, spec, value.y) && push(ctx, spec, "}"); } -bool fmt::push(fmt::Context const &ctx, fmt::Spec const &spec, - Vec3U const &value) +bool fmt::push(fmt::Context const & ctx, fmt::Spec const & spec, + Vec3U const & value) { return push(ctx, spec, "Vec3U{") && push(ctx, spec, value.x) && push(ctx, spec, ", ") && push(ctx, spec, value.y) && @@ -214,8 +214,8 @@ bool fmt::push(fmt::Context const &ctx, fmt::Spec const &spec, push(ctx, spec, "}"); } -bool fmt::push(fmt::Context const &ctx, fmt::Spec const &spec, - Vec4U const &value) +bool fmt::push(fmt::Context const & ctx, fmt::Spec const & spec, + Vec4U const & value) { return push(ctx, spec, "Vec4U{") && push(ctx, spec, value.x) && push(ctx, spec, ", ") && push(ctx, spec, value.y) && @@ -224,26 +224,28 @@ bool fmt::push(fmt::Context const &ctx, fmt::Spec const &spec, push(ctx, spec, "}"); } -bool fmt::push(fmt::Context const &, fmt::Spec &spec, fmt::Spec const &value) +bool fmt::push(fmt::Context const &, fmt::Spec & spec, fmt::Spec const & value) { spec = value; return true; } -bool fmt::push(fmt::Context const &ctx, fmt::Spec const &, Span str) +bool fmt::push(fmt::Context const & ctx, fmt::Spec const &, + Span str) { return ctx.push(str); } -bool fmt::push(fmt::Context const &ctx, fmt::Spec const &spec, char const *str) +bool fmt::push(fmt::Context const & ctx, fmt::Spec const & spec, + char const * str) { return push(ctx, spec, Span{str, strlen(str)}); } -bool fmt::push(fmt::Context const &ctx, fmt::Spec const &, void const *ptr) +bool fmt::push(fmt::Context const & ctx, fmt::Spec const &, void const * ptr) { Spec const ptr_spec{.style = Style::Hex}; return ctx.push("0x"_str) && push_int(ctx, ptr_spec, (uptr) ptr); } -} // namespace ash \ No newline at end of file +} // namespace ash diff --git a/ashura/std/format.h b/ashura/std/format.h index 1a6670d8..722ac342 100644 --- a/ashura/std/format.h +++ b/ashura/std/format.h @@ -37,73 +37,74 @@ struct Context Span scratch = {}; }; -inline Context buffer(Buffer *b, Span scratch) +inline Context buffer(Buffer * b, Span scratch) { - auto f = [](Buffer *b, Span in) { return b->extend(in); }; + auto f = [](Buffer * b, Span in) { return b->extend(in); }; return Context{.push = fn(b, f), .scratch = scratch}; } template -bool push(Context const &ctx, Spec const &, T const &) +bool push(Context const & ctx, Spec const &, T const &) { return ctx.push(""_str); } -bool push(Context const &ctx, Spec const &, bool value); -bool push(Context const &ctx, Spec const &spec, u8 value); -bool push(Context const &ctx, Spec const &spec, u16 value); -bool push(Context const &ctx, Spec const &spec, u32 value); -bool push(Context const &ctx, Spec const &spec, u64 value); -bool push(Context const &ctx, Spec const &spec, i8 value); -bool push(Context const &ctx, Spec const &spec, i16 value); -bool push(Context const &ctx, Spec const &spec, i32 value); -bool push(Context const &ctx, Spec const &spec, i64 value); -bool push(Context const &ctx, Spec const &spec, f32 value); -bool push(Context const &ctx, Spec const &spec, f64 value); -bool push(Context const &ctx, Spec const &spec, Vec2 const &value); -bool push(Context const &ctx, Spec const &spec, Vec3 const &value); -bool push(Context const &ctx, Spec const &spec, Vec4 const &value); -bool push(Context const &ctx, Spec const &spec, Vec2I const &value); -bool push(Context const &ctx, Spec const &spec, Vec3I const &value); -bool push(Context const &ctx, Spec const &spec, Vec4I const &value); -bool push(Context const &ctx, Spec const &spec, Vec2U const &value); -bool push(Context const &ctx, Spec const &spec, Vec3U const &value); -bool push(Context const &ctx, Spec const &spec, Vec4U const &value); -bool push(Context const &, Spec &spec, Spec const &value); -bool push(Context const &ctx, Spec const &, Span str); +bool push(Context const & ctx, Spec const &, bool value); +bool push(Context const & ctx, Spec const & spec, u8 value); +bool push(Context const & ctx, Spec const & spec, u16 value); +bool push(Context const & ctx, Spec const & spec, u32 value); +bool push(Context const & ctx, Spec const & spec, u64 value); +bool push(Context const & ctx, Spec const & spec, i8 value); +bool push(Context const & ctx, Spec const & spec, i16 value); +bool push(Context const & ctx, Spec const & spec, i32 value); +bool push(Context const & ctx, Spec const & spec, i64 value); +bool push(Context const & ctx, Spec const & spec, f32 value); +bool push(Context const & ctx, Spec const & spec, f64 value); +bool push(Context const & ctx, Spec const & spec, Vec2 const & value); +bool push(Context const & ctx, Spec const & spec, Vec3 const & value); +bool push(Context const & ctx, Spec const & spec, Vec4 const & value); +bool push(Context const & ctx, Spec const & spec, Vec2I const & value); +bool push(Context const & ctx, Spec const & spec, Vec3I const & value); +bool push(Context const & ctx, Spec const & spec, Vec4I const & value); +bool push(Context const & ctx, Spec const & spec, Vec2U const & value); +bool push(Context const & ctx, Spec const & spec, Vec3U const & value); +bool push(Context const & ctx, Spec const & spec, Vec4U const & value); +bool push(Context const &, Spec & spec, Spec const & value); +bool push(Context const & ctx, Spec const &, Span str); -inline bool push(Context const &ctx, Spec const &spec, Span str) +inline bool push(Context const & ctx, Spec const & spec, Span str) { return push(ctx, spec, str.as_const()); } template -bool push(Context const &ctx, Spec const &spec, char const (&str)[N]) +bool push(Context const & ctx, Spec const & spec, char const (&str)[N]) { return push(ctx, spec, Span{str, N}); } -bool push(Context const &ctx, Spec const &spec, char const *str); -bool push(Context const &ctx, Spec const &spec, void const *ptr); +bool push(Context const & ctx, Spec const & spec, char const * str); +bool push(Context const & ctx, Spec const & spec, void const * ptr); template -bool push(Context const &ctx, Spec const &spec, T *ptr) +bool push(Context const & ctx, Spec const & spec, T * ptr) { return push(ctx, spec, (void const *) ptr); } -inline bool push(Context const &ctx, Spec const &spec, std::string const &str) +inline bool push(Context const & ctx, Spec const & spec, + std::string const & str) { return push(ctx, spec, span(str)); } -inline bool push(Context const &ctx, Spec const &spec, std::string_view str) +inline bool push(Context const & ctx, Spec const & spec, std::string_view str) { return push(ctx, spec, span(str)); } template -bool format(Context const &ctx, Args const &...args) +bool format(Context const & ctx, Args const &... args) { Spec spec; return (true && ... && push(ctx, spec, args)); diff --git a/ashura/std/fs.cc b/ashura/std/fs.cc index b2816f60..a3adf412 100644 --- a/ashura/std/fs.cc +++ b/ashura/std/fs.cc @@ -1,4 +1,3 @@ - /// SPDX-License-Identifier: MIT #include "ashura/std/fs.h" #include "ashura/std/error.h" @@ -8,13 +7,13 @@ namespace ash { -Result read_file(Span path, Vec &buff) +Result read_file(Span path, Vec & buff) { char path_c_str[MAX_PATH_SIZE + 1]; CHECK(to_c_str(path, path_c_str)); - std::FILE *file = std::fopen(path_c_str, "rb"); + std::FILE * file = std::fopen(path_c_str, "rb"); if (file == nullptr) { return Err{(IoErr) errno}; @@ -54,4 +53,4 @@ Result read_file(Span path, Vec &buff) return Ok{}; } -} // namespace ash \ No newline at end of file +} // namespace ash diff --git a/ashura/std/fs.h b/ashura/std/fs.h index cbe8aa1f..b7136fff 100644 --- a/ashura/std/fs.h +++ b/ashura/std/fs.h @@ -279,16 +279,16 @@ constexpr Span to_string(IoErr err) namespace fmt { -inline bool push(Context const &ctx, Spec const &spec, IoErr const &err) +inline bool push(Context const & ctx, Spec const & spec, IoErr const & err) { return push(ctx, spec, to_string(err)); } } // namespace fmt -Result read_file(Span path, Vec &buff); +Result read_file(Span path, Vec & buff); -inline Result<> path_append(Vec &path, Span tail) +inline Result<> path_append(Vec & path, Span tail) { if (!path.is_empty() && path.last() != '/' && path.last() != '\\') { @@ -304,4 +304,4 @@ inline Result<> path_append(Vec &path, Span tail) return Ok{}; } -} // namespace ash \ No newline at end of file +} // namespace ash diff --git a/ashura/std/functional.h b/ashura/std/functional.h index 533ca349..7ace9274 100644 --- a/ashura/std/functional.h +++ b/ashura/std/functional.h @@ -6,7 +6,7 @@ namespace ash { template -constexpr decltype(auto) fold_impl_reduce(Tuple &fns, In &&...in) +constexpr decltype(auto) fold_impl_reduce(Tuple & fns, In &&... in) { if constexpr (I == (Tuple::SIZE - 1)) { @@ -28,7 +28,7 @@ constexpr decltype(auto) fold_impl_reduce(Tuple &fns, In &&...in) } template -constexpr decltype(auto) fold_impl(Tuple &fns, In &&...in) +constexpr decltype(auto) fold_impl(Tuple & fns, In &&... in) { if constexpr (Tuple::SIZE == 0) { @@ -44,7 +44,7 @@ constexpr decltype(auto) fold_impl(Tuple &fns, In &&...in) /// i.e. result = ( in... -> fn.0 -> fn.1 -> fn.2 -> return ) /// @return the return value of the last function template -constexpr decltype(auto) fold(Tuple &fns, In &&...in) +constexpr decltype(auto) fold(Tuple & fns, In &&... in) { return fold_impl(fns, static_cast(in)...); } diff --git a/ashura/std/hash.cc b/ashura/std/hash.cc index b6064ea1..7672cc96 100644 --- a/ashura/std/hash.cc +++ b/ashura/std/hash.cc @@ -10,4 +10,4 @@ Hash hash_bytes(Span bytes) return XXH3_64bits(bytes.data(), bytes.size()); } -} // namespace ash \ No newline at end of file +} // namespace ash diff --git a/ashura/std/hash.h b/ashura/std/hash.h index 003708cd..0f705d71 100644 --- a/ashura/std/hash.h +++ b/ashura/std/hash.h @@ -7,7 +7,7 @@ namespace ash constexpr Hash hash_combine(Hash hash_a, Hash hash_b) { - hash_a ^= hash_b + 0x9e3779b9 + (hash_a << 6) + (hash_a >> 2); + hash_a ^= hash_b + 0x9e37'79b9 + (hash_a << 6) + (hash_a >> 2); return hash_a; } @@ -31,7 +31,7 @@ struct StrHasher struct BitHasher { template - Hash operator()(T const &a) const + Hash operator()(T const & a) const { return hash_bytes(Span{&a, 1}.as_u8()); } diff --git a/ashura/std/image.h b/ashura/std/image.h index 226691e1..97e7e4a0 100644 --- a/ashura/std/image.h +++ b/ashura/std/image.h @@ -112,8 +112,8 @@ void copy_image(ImageSpan src, ImageSpan dst) src.width = min(src.width, dst.width); src.height = min(src.height, dst.height); - auto const *in = src.channels.data(); - auto *out = dst.channels.data(); + auto const * in = src.channels.data(); + auto * out = dst.channels.data(); for (u32 i = 0; i < src.height; i++, in += src.pitch(), out += dst.pitch()) { @@ -128,13 +128,13 @@ void copy_alpha_image_to_BGRA(ImageSpan src, ImageSpan dst, src.width = min(src.width, dst.width); src.height = min(src.height, dst.width); - auto const *in = src.channels.data(); - auto *out = dst.channels.data(); + auto const * in = src.channels.data(); + auto * out = dst.channels.data(); for (u32 i = 0; i < src.height; i++, in += src.pitch(), out += dst.pitch()) { - auto const *in_p = in; - auto *out_p = out; + auto const * in_p = in; + auto * out_p = out; for (u32 j = 0; j < src.width; j++, in_p += 1, out_p += 4) { out_p[0] = B; @@ -145,4 +145,4 @@ void copy_alpha_image_to_BGRA(ImageSpan src, ImageSpan dst, } } -} // namespace ash \ No newline at end of file +} // namespace ash diff --git a/ashura/std/list.h b/ashura/std/list.h index aeb6b497..1d440da5 100644 --- a/ashura/std/list.h +++ b/ashura/std/list.h @@ -18,9 +18,9 @@ namespace ash template struct [[nodiscard]] ListNode : Pin<> { - ListNode *next = this; - ListNode *prev = this; - T v = {}; + ListNode * next = this; + ListNode * prev = this; + T v = {}; void isolate() { @@ -46,14 +46,14 @@ namespace list /// @tparam T /// @param node must be valid and non-null template -static constexpr void unlink_node(ListNode *node) +static constexpr void unlink_node(ListNode * node) { // detach from siblings node->next->prev = node->prev; node->prev->next = node->next; // create 1 element node - node->next = node; - node->prev = node; + node->next = node; + node->prev = node; } /// @brief @@ -61,10 +61,10 @@ static constexpr void unlink_node(ListNode *node) /// @param head must be valid and non-null, set to null if empty /// @return popped element or null template -[[nodiscard]] constexpr ListNode *pop_front(ListNode *&head) +[[nodiscard]] constexpr ListNode * pop_front(ListNode *& head) { - ListNode *out = head; - ListNode *new_head = (head->next == head) ? nullptr : head->next; + ListNode * out = head; + ListNode * new_head = (head->next == head) ? nullptr : head->next; unlink_node(out); head = new_head; return out; @@ -75,10 +75,10 @@ template /// @param head must be valid and non-null, set to null if empty /// @return template -[[nodiscard]] constexpr ListNode *pop_back(ListNode *&head) +[[nodiscard]] constexpr ListNode * pop_back(ListNode *& head) { - ListNode *out = head->prev; - ListNode *new_head = (head->prev == head) ? nullptr : head; + ListNode * out = head->prev; + ListNode * new_head = (head->prev == head) ? nullptr : head; unlink_node(out); head = new_head; return out; @@ -92,16 +92,16 @@ template /// @param ext must be valid and non-null /// template -constexpr void attach(ListNode *node, ListNode *ext) +constexpr void attach(ListNode * node, ListNode * ext) { - ListNode *node_head = node; - ListNode *node_tail = node->prev; - ListNode *ext_head = ext; - ListNode *ext_tail = ext->prev; - ext_head->prev = node_tail; - ext_tail->next = node_head; - node_head->prev = ext_tail; - node_tail->next = ext_head; + ListNode * node_head = node; + ListNode * node_tail = node->prev; + ListNode * ext_head = ext; + ListNode * ext_tail = ext->prev; + ext_head->prev = node_tail; + ext_tail->next = node_head; + node_head->prev = ext_tail; + node_tail->next = ext_head; } /// @@ -112,8 +112,8 @@ constexpr void attach(ListNode *node, ListNode *ext) /// @param ext must be valid and non-null /// template -[[nodiscard]] constexpr ListNode *push_back(ListNode *head, - ListNode *ext) +[[nodiscard]] constexpr ListNode * push_back(ListNode * head, + ListNode * ext) { attach(head, ext); return head; @@ -127,8 +127,8 @@ template /// @param ext must be valid and non-null /// template -[[nodiscard]] constexpr ListNode *push_front(ListNode *head, - ListNode *ext) +[[nodiscard]] constexpr ListNode * push_front(ListNode * head, + ListNode * ext) { attach(ext, head); return ext; @@ -142,26 +142,26 @@ template template struct [[nodiscard]] List { - ListNode *head; + ListNode * head; constexpr List() : head{nullptr} { } - explicit constexpr List(ListNode *head) : head{head} + explicit constexpr List(ListNode * head) : head{head} { } constexpr List(List const &) = delete; - constexpr List(List &&other) : head{other.head} + constexpr List(List && other) : head{other.head} { other.head = nullptr; } - constexpr List &operator=(List const &) = delete; + constexpr List & operator=(List const &) = delete; - constexpr List &operator=(List &&other) + constexpr List & operator=(List && other) { swap(head, other.head); return *this; @@ -177,7 +177,7 @@ struct [[nodiscard]] List return head == nullptr; } - [[nodiscard]] constexpr ListNode *tail() const + [[nodiscard]] constexpr ListNode * tail() const { if (head == nullptr) [[unlikely]] { @@ -187,7 +187,7 @@ struct [[nodiscard]] List return head->prev; } - [[nodiscard]] constexpr ListNode *pop_front() + [[nodiscard]] constexpr ListNode * pop_front() { if (head == nullptr) [[unlikely]] { @@ -197,7 +197,7 @@ struct [[nodiscard]] List return list::pop_front(head); } - [[nodiscard]] constexpr ListNode *pop_back() + [[nodiscard]] constexpr ListNode * pop_back() { if (head == nullptr) [[unlikely]] { @@ -207,7 +207,7 @@ struct [[nodiscard]] List return list::pop_back(head); } - constexpr void push_front(ListNode *ext) + constexpr void push_front(ListNode * ext) { if (head == nullptr) [[unlikely]] { @@ -218,7 +218,7 @@ struct [[nodiscard]] List head = list::push_front(head, ext); } - constexpr void push_back(ListNode *ext) + constexpr void push_back(ListNode * ext) { if (head == nullptr) [[unlikely]] { diff --git a/ashura/std/locale.h b/ashura/std/locale.h index 7cf191b7..c9123655 100644 --- a/ashura/std/locale.h +++ b/ashura/std/locale.h @@ -1,6 +1,6 @@ - /// SPDX-License-Identifier: MIT #pragma once + namespace ash { diff --git a/ashura/std/log.cc b/ashura/std/log.cc index 1632369a..ee328001 100644 --- a/ashura/std/log.cc +++ b/ashura/std/log.cc @@ -6,7 +6,7 @@ namespace ash { -ASH_C_LINKAGE ASH_DLL_EXPORT Logger *logger = nullptr; +ASH_C_LINKAGE ASH_DLL_EXPORT Logger * logger = nullptr; void Logger::init() { @@ -32,7 +32,7 @@ void Logger::uninit() StdioSink stdio_sink{}; -char const *get_level_str(LogLevels level) +char const * get_level_str(LogLevels level) { switch (level) { @@ -67,8 +67,8 @@ char const *get_level_str(LogLevels level) void StdioSink::log(LogLevels level, Span log_message) { - char const *level_str = get_level_str(level); - std::FILE *file = stdout; + char const * level_str = get_level_str(level); + std::FILE * file = stdout; switch (level) { @@ -93,7 +93,7 @@ void StdioSink::log(LogLevels level, Span log_message) std::time_t current_time = std::time(nullptr); if (current_time != (std::time_t) -1) { - tm *current_local_time = std::localtime(¤t_time); + tm * current_local_time = std::localtime(¤t_time); if (current_local_time != nullptr) { time_string_length = std::strftime(time_string, sizeof(time_string), @@ -120,7 +120,7 @@ void StdioSink::flush() void FileSink::log(LogLevels level, Span log_message) { - char const *level_str = get_level_str(level); + char const * level_str = get_level_str(level); constexpr char const time_format[] = "%d/%m/%Y, %H:%M:%S"; char time_string[256]; usize time_string_length = 0; @@ -128,7 +128,7 @@ void FileSink::log(LogLevels level, Span log_message) std::time_t current_time = std::time(nullptr); if (current_time != (std::time_t) -1) { - std::tm *current_local_time = std::localtime(¤t_time); + std::tm * current_local_time = std::localtime(¤t_time); if (current_local_time != nullptr) { time_string_length = std::strftime(time_string, sizeof(time_string), diff --git a/ashura/std/log.h b/ashura/std/log.h index 84cb7adc..a15b3e8a 100644 --- a/ashura/std/log.h +++ b/ashura/std/log.h @@ -1,4 +1,3 @@ - /// SPDX-License-Identifier: MIT #pragma once #include "ashura/std/cfg.h" @@ -44,43 +43,43 @@ struct Logger : Pin<> static constexpr usize SCRATCH_SIZE = 256; static constexpr u32 MAX_SINKS = 8; - LogSink *sinks[MAX_SINKS] = {}; + LogSink * sinks[MAX_SINKS] = {}; u32 num_sinks = 0; char buffer[BUFFER_CAPACITY] = {}; std::mutex mutex = {}; template - bool debug(Args const &...args) + bool debug(Args const &... args) { return log(LogLevels::Debug, args...); } template - bool trace(Args const &...args) + bool trace(Args const &... args) { return log(LogLevels::Trace, args...); } template - bool info(Args const &...args) + bool info(Args const &... args) { return log(LogLevels::Info, args...); } template - bool warn(Args const &...args) + bool warn(Args const &... args) { return log(LogLevels::Warning, args...); } template - bool error(Args const &...args) + bool error(Args const &... args) { return log(LogLevels::Error, args...); } template - bool fatal(Args const &...args) + bool fatal(Args const &... args) { return log(LogLevels::Fatal, args...); } @@ -88,14 +87,14 @@ struct Logger : Pin<> void flush() { std::lock_guard lock{mutex}; - for (LogSink *sink : Span{sinks, num_sinks}) + for (LogSink * sink : Span{sinks, num_sinks}) { sink->flush(); } } template - bool log(LogLevels level, Args const &...args) + bool log(LogLevels level, Args const &... args) { std::lock_guard lock{mutex}; char scratch[SCRATCH_SIZE]; @@ -106,7 +105,7 @@ struct Logger : Pin<> return false; } - for (LogSink *sink : Span{sinks, num_sinks}) + for (LogSink * sink : Span{sinks, num_sinks}) { sink->log(level, msg); } @@ -114,7 +113,7 @@ struct Logger : Pin<> } template - [[noreturn]] void panic(Args const &...args) + [[noreturn]] void panic(Args const &... args) { std::atomic_ref panic_count{*ash::panic_count}; if (panic_count.fetch_add(1, std::memory_order::relaxed)) @@ -139,7 +138,7 @@ struct Logger : Pin<> static void uninit(); - [[nodiscard]] bool add_sink(LogSink *s) + [[nodiscard]] bool add_sink(LogSink * s) { std::lock_guard lock{mutex}; if ((num_sinks + 1) > MAX_SINKS) @@ -168,14 +167,14 @@ struct StdioSink : LogSink struct FileSink : LogSink { - FILE *file = nullptr; + FILE * file = nullptr; std::mutex mutex; void log(LogLevels level, Span log_message) override; void flush() override; }; -ASH_C_LINKAGE ASH_DLL_EXPORT ash::Logger *logger; +ASH_C_LINKAGE ASH_DLL_EXPORT ash::Logger * logger; extern StdioSink stdio_sink; diff --git a/ashura/std/map.h b/ashura/std/map.h index a9eb05e3..3ff08b6e 100644 --- a/ashura/std/map.h +++ b/ashura/std/map.h @@ -41,8 +41,8 @@ struct [[nodiscard]] Map static constexpr Distance PROBE_SENTINEL = -1; - Distance *probe_dists_; - Entry *probes_; + Distance * probe_dists_; + Entry * probes_; usize num_probes_; usize num_entries_; Distance max_probe_dist_; @@ -65,9 +65,9 @@ struct [[nodiscard]] Map constexpr Map(Map const &) = delete; - constexpr Map &operator=(Map const &) = delete; + constexpr Map & operator=(Map const &) = delete; - constexpr Map(Map &&other) : + constexpr Map(Map && other) : probe_dists_{other.probe_dists_}, probes_{other.probes_}, num_probes_{other.num_probes_}, @@ -87,7 +87,7 @@ struct [[nodiscard]] Map other.cmp_ = {}; } - constexpr Map &operator=(Map &&other) + constexpr Map & operator=(Map && other) { if (this == &other) [[unlikely]] { @@ -173,7 +173,7 @@ struct [[nodiscard]] Map return num_probes_; } - [[nodiscard]] constexpr V *try_get(auto const &key, Hash hash) const + [[nodiscard]] constexpr V * try_get(auto const & key, Hash hash) const { if (num_probes_ == 0 || num_entries_ == 0) { @@ -187,7 +187,7 @@ struct [[nodiscard]] Map { break; } - Entry *probe = probes_ + probe_idx; + Entry * probe = probes_ + probe_idx; if (cmp_(probe->key, key)) { return &probe->value; @@ -198,25 +198,25 @@ struct [[nodiscard]] Map return nullptr; } - [[nodiscard]] constexpr V *try_get(auto const &key) const + [[nodiscard]] constexpr V * try_get(auto const & key) const { Hash const hash = hasher_(key); return try_get(key, hash); } - [[nodiscard]] constexpr V &operator[](auto const &key) const + [[nodiscard]] constexpr V & operator[](auto const & key) const { - V *v = try_get(key); + V * v = try_get(key); CHECK(v != nullptr); return *v; } - [[nodiscard]] constexpr bool has(auto const &key) const + [[nodiscard]] constexpr bool has(auto const & key) const { return try_get(key) != nullptr; } - [[nodiscard]] constexpr bool has(auto const &key, Hash hash) const + [[nodiscard]] constexpr bool has(auto const & key, Hash hash) const { return try_get(key, hash) != nullptr; } @@ -227,7 +227,7 @@ struct [[nodiscard]] Map return num_probes == 0 || ((num_entries * 10ULL) / num_probes) > 6ULL; } - constexpr void reinsert_(Entry *src_probes, Distance const *src_probe_dists, + constexpr void reinsert_(Entry * src_probes, Distance const * src_probe_dists, usize n) { for (usize src_probe_idx = 0; src_probe_idx < n; src_probe_idx++) @@ -241,8 +241,8 @@ struct [[nodiscard]] Map Distance probe_dist = 0; while (true) { - Entry *dst_probe = probes_ + probe_idx; - Distance *dst_probe_dist = probe_dists_ + probe_idx; + Entry * dst_probe = probes_ + probe_idx; + Distance * dst_probe_dist = probe_dists_ + probe_idx; if (*dst_probe_dist == PROBE_SENTINEL) { @@ -266,13 +266,13 @@ struct [[nodiscard]] Map constexpr bool rehash_n_(usize new_num_probes) { - Distance *new_probe_dists; + Distance * new_probe_dists; if (!allocator_.nalloc(new_num_probes, new_probe_dists)) { return false; } - Entry *new_probes; + Entry * new_probes; if (!allocator_.nalloc(new_num_probes, new_probes)) { allocator_.ndealloc(new_probe_dists, new_num_probes); @@ -284,14 +284,14 @@ struct [[nodiscard]] Map new_probe_dists[i] = PROBE_SENTINEL; } - Entry *old_probes = probes_; - Distance *old_probe_dists = probe_dists_; - usize old_num_probes = num_probes_; - probes_ = new_probes; - probe_dists_ = new_probe_dists; - num_probes_ = new_num_probes; - num_entries_ = 0; - max_probe_dist_ = 0; + Entry * old_probes = probes_; + Distance * old_probe_dists = probe_dists_; + usize old_num_probes = num_probes_; + probes_ = new_probes; + probe_dists_ = new_probe_dists; + num_probes_ = new_num_probes; + num_entries_ = 0; + max_probe_dist_ = 0; reinsert_(old_probes, old_probe_dists, old_num_probes); allocator_.ndealloc(old_probe_dists, old_num_probes); @@ -327,7 +327,7 @@ struct [[nodiscard]] Map /// @return The inserted or existing value if the insert was successful /// without a memory allocation error, otherwise an Err [[nodiscard]] constexpr Result - insert(K key, V value, bool *exists = nullptr, bool replace = true) + insert(K key, V value, bool * exists = nullptr, bool replace = true) { if (exists != nullptr) { @@ -347,8 +347,8 @@ struct [[nodiscard]] Map while (true) { - Entry *dst_probe = probes_ + probe_idx; - Distance *dst_probe_dist = probe_dists_ + probe_idx; + Entry * dst_probe = probes_ + probe_idx; + Distance * dst_probe_dist = probe_dists_ + probe_idx; if (*dst_probe_dist == PROBE_SENTINEL) { insert_idx = probe_idx; @@ -394,16 +394,16 @@ struct [[nodiscard]] Map usize probe_idx = (pop_idx + 1) & (num_probes_ - 1); while (probe_idx != pop_idx) { - Entry *probe = probes_ + probe_idx; - Distance *probe_dist = probe_dists_ + probe_idx; + Entry * probe = probes_ + probe_idx; + Distance * probe_dist = probe_dists_ + probe_idx; if (*probe_dist == 0 || *probe_dist == PROBE_SENTINEL) { break; } - Entry *insert_probe = probes_ + insert_idx; - Distance *insert_probe_dist = probe_dists_ + insert_idx; + Entry * insert_probe = probes_ + insert_idx; + Distance * insert_probe_dist = probe_dists_ + insert_idx; obj::relocate_non_overlapping(Span{probe, 1}, insert_probe); *insert_probe_dist = *probe_dist - 1; @@ -413,7 +413,7 @@ struct [[nodiscard]] Map } } - constexpr bool erase(auto const &key) + constexpr bool erase(auto const & key) { if (num_probes_ == 0 || num_entries_ == 0) { @@ -425,12 +425,12 @@ struct [[nodiscard]] Map while (probe_dist <= max_probe_dist_) { - Distance *dst_probe_dist = probe_dists_ + probe_idx; + Distance * dst_probe_dist = probe_dists_ + probe_idx; if (*dst_probe_dist == PROBE_SENTINEL) { return false; } - Entry *dst_probe = probes_ + probe_idx; + Entry * dst_probe = probes_ + probe_idx; if (cmp_(dst_probe->key, key)) { dst_probe->~Entry(); @@ -446,7 +446,7 @@ struct [[nodiscard]] Map } template - constexpr void iter(Fn &&fn) const + constexpr void iter(Fn && fn) const { for (usize i = 0; i < num_probes_; i++) { diff --git a/ashura/std/math.h b/ashura/std/math.h index 14527f01..2c0c4c2a 100644 --- a/ashura/std/math.h +++ b/ashura/std/math.h @@ -124,7 +124,7 @@ constexpr f32 invsqrt(f32 x) { // (enable only on IEEE 754) static_assert(std::numeric_limits::is_iec559); - f32 const y = std::bit_cast(0x5F3759DF - (std::bit_cast(x) >> 1)); + f32 const y = std::bit_cast(0x5F37'59DF - (std::bit_cast(x) >> 1)); return y * (1.5F - (x * 0.5F * y * y)); } @@ -170,7 +170,7 @@ constexpr u32 num_mip_levels(u32 a) /// interpolator `t` /// This is the exact form: (1 - t) * A + T * B, optimized for FMA template -constexpr T lerp(T const &low, T const &high, T const &t) +constexpr T lerp(T const & low, T const & high, T const & t) { return low - t * low + t * high; } @@ -178,7 +178,7 @@ constexpr T lerp(T const &low, T const &high, T const &t) /// @brief logarithmically interpolate between points `low` and `high` given /// interpolator `t` template -inline T log_interp(T const &low, T const &high, T const &t) +inline T log_interp(T const & low, T const & high, T const & t) { return low * exp(t * log(high / low)); } @@ -192,53 +192,54 @@ inline T log_interp(T const &low, T const &high, T const &t) /// @param half_life time to complete half of the whole operation /// template -inline T damplerp(T const &low, T const &high, T const &dt, T const &half_life) +inline T damplerp(T const & low, T const & high, T const & dt, + T const & half_life) { return lerp(low, high, 1 - exp2(-half_life * dt)); } /// find interpolator t, given points a and b, and interpolated value v template -constexpr T unlerp(T const &low, T const &high, T const &v) +constexpr T unlerp(T const & low, T const & high, T const & v) { return (v - low) / (high - low); } template -constexpr T relerp(T const &in_low, T const &in_high, T const &out_low, - T const &out_high, T const &v) +constexpr T relerp(T const & in_low, T const & in_high, T const & out_low, + T const & out_high, T const & v) { return lerp(out_low, out_high, unlerp(in_low, in_high, v)); } // SEE: https://www.youtube.com/watch?v=jvPPXbo87ds template -constexpr T ease_in(T const &t) +constexpr T ease_in(T const & t) { return t * t; } template -constexpr T ease_out(T const &t) +constexpr T ease_out(T const & t) { return 1 - (1 - t) * (1 - t); } template -constexpr T ease_in_out(T const &t) +constexpr T ease_in_out(T const & t) { return lerp(ease_in(t), ease_out(t), t); } template -constexpr T bezier(T const &p0, T const &p1, T const &p2, T const &t) +constexpr T bezier(T const & p0, T const & p1, T const & p2, T const & t) { return (1 - t) * (1 - t) * p0 + 2 * (1 - t) * t * p1 + t * t * p2; } template -constexpr T cubic_bezier(T const &p0, T const &p1, T const &p2, T const &p3, - T const &t) +constexpr T cubic_bezier(T const & p0, T const & p1, T const & p2, T const & p3, + T const & t) { return (1 - t) * (1 - t) * (1 - t) * p0 + 3 * (1 - t) * (1 - t) * t * p1 + 3 * (1 - t) * t * t * p2 + t * t * t * p3; @@ -251,8 +252,8 @@ constexpr T cubic_bezier(T const &p0, T const &p1, T const &p2, T const &p3, /// ne of the features of the Catmull-Rom spline is that the specified curve /// will pass through all of the control points. template -constexpr T catmull_rom(T const &p0, T const &p1, T const &p2, T const &p3, - T const &t) +constexpr T catmull_rom(T const & p0, T const & p1, T const & p2, T const & p3, + T const & t) { return 0.5F * ((2 * p1) + (-p0 + p2) * t + (2 * p0 - 5 * p1 + 4 * p2 - p3) * t * t + @@ -352,43 +353,43 @@ constexpr f32 smoothstep(f32 a, f32 b, f32 t) } template -inline T grid_snap(T const &a, T const &unit) +inline T grid_snap(T const & a, T const & unit) { return floor((a + unit * 0.5F) / unit) * unit; } template -constexpr T norm_to_axis(T const &norm) +constexpr T norm_to_axis(T const & norm) { return norm * 2 - 1; } template -constexpr T axis_to_norm(T const &axis) +constexpr T axis_to_norm(T const & axis) { return axis * 0.5F + 0.5F; } template -constexpr T norm_to_space(T const &norm) +constexpr T norm_to_space(T const & norm) { return norm - 0.5F; } template -constexpr T space_to_norm(T const &space) +constexpr T space_to_norm(T const & space) { return space + 0.5F; } template -constexpr T space_to_axis(T const &space) +constexpr T space_to_axis(T const & space) { return space * 2; } template -constexpr T axis_to_space(T const &axis) +constexpr T axis_to_space(T const & axis) { return axis * 0.5F; } @@ -398,7 +399,7 @@ constexpr T axis_to_space(T const &axis) /// @param alignment the alignment to align to [-1, +1] /// @return returns the aligned position relative to the space's center template -constexpr T space_align(T const &space, T const &item, T const &alignment) +constexpr T space_align(T const & space, T const & item, T const & alignment) { T const trailing = (space - item) * 0.5F; return lerp(-trailing, trailing, axis_to_norm(alignment)); @@ -450,12 +451,12 @@ struct alignas(8) Vec2 return Vec2{value, value}; } - constexpr f32 &operator[](usize i) + constexpr f32 & operator[](usize i) { return (&x)[i]; } - constexpr f32 const &operator[](usize i) const + constexpr f32 const & operator[](usize i) const { return (&x)[i]; } @@ -536,25 +537,25 @@ constexpr Vec2 operator/(f32 a, Vec2 b) return Vec2{a / b.x, a / b.y}; } -constexpr Vec2 &operator+=(Vec2 &a, Vec2 b) +constexpr Vec2 & operator+=(Vec2 & a, Vec2 b) { a = a + b; return a; } -constexpr Vec2 &operator-=(Vec2 &a, Vec2 b) +constexpr Vec2 & operator-=(Vec2 & a, Vec2 b) { a = a - b; return a; } -constexpr Vec2 &operator*=(Vec2 &a, Vec2 b) +constexpr Vec2 & operator*=(Vec2 & a, Vec2 b) { a = a * b; return a; } -constexpr Vec2 &operator/=(Vec2 &a, Vec2 b) +constexpr Vec2 & operator/=(Vec2 & a, Vec2 b) { a = a / b; return a; @@ -571,12 +572,12 @@ struct Vec3 return Vec3{value, value, value}; } - constexpr f32 &operator[](usize i) + constexpr f32 & operator[](usize i) { return (&x)[i]; } - constexpr f32 const &operator[](usize i) const + constexpr f32 const & operator[](usize i) const { return (&x)[i]; } @@ -667,25 +668,25 @@ constexpr Vec3 operator/(f32 a, Vec3 b) return Vec3{a / b.x, a / b.y, a / b.z}; } -constexpr Vec3 &operator+=(Vec3 &a, Vec3 b) +constexpr Vec3 & operator+=(Vec3 & a, Vec3 b) { a = a + b; return a; } -constexpr Vec3 &operator-=(Vec3 &a, Vec3 b) +constexpr Vec3 & operator-=(Vec3 & a, Vec3 b) { a = a - b; return a; } -constexpr Vec3 &operator*=(Vec3 &a, Vec3 b) +constexpr Vec3 & operator*=(Vec3 & a, Vec3 b) { a = a * b; return a; } -constexpr Vec3 &operator/=(Vec3 &a, Vec3 b) +constexpr Vec3 & operator/=(Vec3 & a, Vec3 b) { a = a / b; return a; @@ -703,12 +704,12 @@ struct alignas(16) Vec4 return Vec4{value, value, value, value}; } - constexpr f32 &operator[](usize i) + constexpr f32 & operator[](usize i) { return (&x)[i]; } - constexpr f32 const &operator[](usize i) const + constexpr f32 const & operator[](usize i) const { return (&x)[i]; } @@ -799,25 +800,25 @@ constexpr Vec4 operator/(f32 a, Vec4 b) return Vec4{a / b.x, a / b.y, a / b.z, a / b.w}; } -constexpr Vec4 &operator+=(Vec4 &a, Vec4 b) +constexpr Vec4 & operator+=(Vec4 & a, Vec4 b) { a = a + b; return a; } -constexpr Vec4 &operator-=(Vec4 &a, Vec4 b) +constexpr Vec4 & operator-=(Vec4 & a, Vec4 b) { a = a - b; return a; } -constexpr Vec4 &operator*=(Vec4 &a, Vec4 b) +constexpr Vec4 & operator*=(Vec4 & a, Vec4 b) { a = a * b; return a; } -constexpr Vec4 &operator/=(Vec4 &a, Vec4 b) +constexpr Vec4 & operator/=(Vec4 & a, Vec4 b) { a = a / b; return a; @@ -841,12 +842,12 @@ struct alignas(4) Vec4U8 .x = x / 255.0F, .y = y / 255.0F, .z = z / 255.0F, .w = w / 255.0F}; } - constexpr u8 &operator[](usize i) + constexpr u8 & operator[](usize i) { return (&x)[i]; } - constexpr u8 const &operator[](usize i) const + constexpr u8 const & operator[](usize i) const { return (&x)[i]; } @@ -886,25 +887,25 @@ constexpr Vec4U8 operator/(Vec4U8 a, Vec4U8 b) static_cast(a.z / b.z), static_cast(a.w / b.w)}; } -constexpr Vec4U8 &operator+=(Vec4U8 &a, Vec4U8 b) +constexpr Vec4U8 & operator+=(Vec4U8 & a, Vec4U8 b) { a = a + b; return a; } -constexpr Vec4U8 &operator-=(Vec4U8 &a, Vec4U8 b) +constexpr Vec4U8 & operator-=(Vec4U8 & a, Vec4U8 b) { a = a - b; return a; } -constexpr Vec4U8 &operator*=(Vec4U8 &a, Vec4U8 b) +constexpr Vec4U8 & operator*=(Vec4U8 & a, Vec4U8 b) { a = a * b; return a; } -constexpr Vec4U8 &operator/=(Vec4U8 &a, Vec4U8 b) +constexpr Vec4U8 & operator/=(Vec4U8 & a, Vec4U8 b) { a = a / b; return a; @@ -930,12 +931,12 @@ struct alignas(8) Vec2I return Vec2I{value, value}; } - constexpr i32 &operator[](usize i) + constexpr i32 & operator[](usize i) { return (&x)[i]; } - constexpr i32 const &operator[](usize i) const + constexpr i32 const & operator[](usize i) const { return (&x)[i]; } @@ -986,25 +987,25 @@ constexpr Vec2I operator/(Vec2I a, Vec2I b) return Vec2I{a.x / b.x, a.y / b.y}; } -constexpr Vec2I &operator+=(Vec2I &a, Vec2I b) +constexpr Vec2I & operator+=(Vec2I & a, Vec2I b) { a = a + b; return a; } -constexpr Vec2I &operator-=(Vec2I &a, Vec2I b) +constexpr Vec2I & operator-=(Vec2I & a, Vec2I b) { a = a - b; return a; } -constexpr Vec2I &operator*=(Vec2I &a, Vec2I b) +constexpr Vec2I & operator*=(Vec2I & a, Vec2I b) { a = a * b; return a; } -constexpr Vec2I &operator/=(Vec2I &a, Vec2I b) +constexpr Vec2I & operator/=(Vec2I & a, Vec2I b) { a = a / b; return a; @@ -1016,12 +1017,12 @@ struct Vec3I i32 y = 0; i32 z = 0; - constexpr i32 &operator[](usize i) + constexpr i32 & operator[](usize i) { return (&x)[i]; } - constexpr i32 const &operator[](usize i) const + constexpr i32 const & operator[](usize i) const { return (&x)[i]; } @@ -1057,25 +1058,25 @@ constexpr Vec3I operator/(Vec3I a, Vec3I b) return Vec3I{a.x / b.x, a.y / b.y, a.z / b.z}; } -constexpr Vec3I &operator+=(Vec3I &a, Vec3I b) +constexpr Vec3I & operator+=(Vec3I & a, Vec3I b) { a = a + b; return a; } -constexpr Vec3I &operator-=(Vec3I &a, Vec3I b) +constexpr Vec3I & operator-=(Vec3I & a, Vec3I b) { a = a - b; return a; } -constexpr Vec3I &operator*=(Vec3I &a, Vec3I b) +constexpr Vec3I & operator*=(Vec3I & a, Vec3I b) { a = a * b; return a; } -constexpr Vec3I &operator/=(Vec3I &a, Vec3I b) +constexpr Vec3I & operator/=(Vec3I & a, Vec3I b) { a = a / b; return a; @@ -1093,12 +1094,12 @@ struct alignas(16) Vec4I return Vec4I{value, value, value, value}; } - constexpr i32 &operator[](usize i) + constexpr i32 & operator[](usize i) { return (&x)[i]; } - constexpr i32 const &operator[](usize i) const + constexpr i32 const & operator[](usize i) const { return (&x)[i]; } @@ -1134,25 +1135,25 @@ constexpr Vec4I operator/(Vec4I a, Vec4I b) return Vec4I{a.x / b.x, a.y / b.y, a.z / b.z, a.w / b.w}; } -constexpr Vec4I &operator+=(Vec4I &a, Vec4I b) +constexpr Vec4I & operator+=(Vec4I & a, Vec4I b) { a = a + b; return a; } -constexpr Vec4I &operator-=(Vec4I &a, Vec4I b) +constexpr Vec4I & operator-=(Vec4I & a, Vec4I b) { a = a - b; return a; } -constexpr Vec4I &operator*=(Vec4I &a, Vec4I b) +constexpr Vec4I & operator*=(Vec4I & a, Vec4I b) { a = a * b; return a; } -constexpr Vec4I &operator/=(Vec4I &a, Vec4I b) +constexpr Vec4I & operator/=(Vec4I & a, Vec4I b) { a = a / b; return a; @@ -1168,12 +1169,12 @@ struct alignas(8) Vec2U return Vec2U{value, value}; } - constexpr u32 &operator[](usize i) + constexpr u32 & operator[](usize i) { return (&x)[i]; } - constexpr u32 const &operator[](usize i) const + constexpr u32 const & operator[](usize i) const { return (&x)[i]; } @@ -1254,25 +1255,25 @@ constexpr Vec2U operator/(u32 a, Vec2U b) return Vec2U{a / b.x, a / b.y}; } -constexpr Vec2U &operator+=(Vec2U &a, Vec2U b) +constexpr Vec2U & operator+=(Vec2U & a, Vec2U b) { a = a + b; return a; } -constexpr Vec2U &operator-=(Vec2U &a, Vec2U b) +constexpr Vec2U & operator-=(Vec2U & a, Vec2U b) { a = a - b; return a; } -constexpr Vec2U &operator*=(Vec2U &a, Vec2U b) +constexpr Vec2U & operator*=(Vec2U & a, Vec2U b) { a = a * b; return a; } -constexpr Vec2U &operator/=(Vec2U &a, Vec2U b) +constexpr Vec2U & operator/=(Vec2U & a, Vec2U b) { a = a / b; return a; @@ -1289,12 +1290,12 @@ struct Vec3U return Vec3U{value, value, value}; } - constexpr u32 &operator[](usize i) + constexpr u32 & operator[](usize i) { return (&x)[i]; } - constexpr u32 const &operator[](usize i) const + constexpr u32 const & operator[](usize i) const { return (&x)[i]; } @@ -1330,25 +1331,25 @@ constexpr Vec3U operator/(Vec3U a, Vec3U b) return Vec3U{a.x / b.x, a.y / b.y, a.z / b.z}; } -constexpr Vec3U &operator+=(Vec3U &a, Vec3U b) +constexpr Vec3U & operator+=(Vec3U & a, Vec3U b) { a = a + b; return a; } -constexpr Vec3U &operator-=(Vec3U &a, Vec3U b) +constexpr Vec3U & operator-=(Vec3U & a, Vec3U b) { a = a - b; return a; } -constexpr Vec3U &operator*=(Vec3U &a, Vec3U b) +constexpr Vec3U & operator*=(Vec3U & a, Vec3U b) { a = a * b; return a; } -constexpr Vec3U &operator/=(Vec3U &a, Vec3U b) +constexpr Vec3U & operator/=(Vec3U & a, Vec3U b) { a = a / b; return a; @@ -1366,12 +1367,12 @@ struct alignas(16) Vec4U return Vec4U{value, value, value, value}; } - constexpr u32 &operator[](usize i) + constexpr u32 & operator[](usize i) { return (&x)[i]; } - constexpr u32 const &operator[](usize i) const + constexpr u32 const & operator[](usize i) const { return (&x)[i]; } @@ -1407,25 +1408,25 @@ constexpr Vec4U operator/(Vec4U a, Vec4U b) return Vec4U{a.x / b.x, a.y / b.y, a.z / b.z, a.w / b.w}; } -constexpr Vec4U &operator+=(Vec4U &a, Vec4U b) +constexpr Vec4U & operator+=(Vec4U & a, Vec4U b) { a = a + b; return a; } -constexpr Vec4U &operator-=(Vec4U &a, Vec4U b) +constexpr Vec4U & operator-=(Vec4U & a, Vec4U b) { a = a - b; return a; } -constexpr Vec4U &operator*=(Vec4U &a, Vec4U b) +constexpr Vec4U & operator*=(Vec4U & a, Vec4U b) { a = a * b; return a; } -constexpr Vec4U &operator/=(Vec4U &a, Vec4U b) +constexpr Vec4U & operator/=(Vec4U & a, Vec4U b) { a = a / b; return a; @@ -1504,12 +1505,16 @@ struct Mat2 static constexpr Mat2 splat(f32 value) { - return Mat2{.rows = {{value, value}, {value, value}}}; + return Mat2{ + .rows = {{value, value}, {value, value}} + }; } static constexpr Mat2 diagonal(f32 value) { - return Mat2{.rows = {{value, 0}, {0, value}}}; + return Mat2{ + .rows = {{value, 0}, {0, value}} + }; } static constexpr Mat2 identity() @@ -1517,12 +1522,12 @@ struct Mat2 return diagonal(1); } - constexpr Vec2 &operator[](usize index) + constexpr Vec2 & operator[](usize index) { return rows[index]; } - constexpr Vec2 const &operator[](usize index) const + constexpr Vec2 const & operator[](usize index) const { return rows[index]; } @@ -1538,61 +1543,69 @@ struct Mat2 } }; -constexpr bool operator==(Mat2 const &a, Mat2 const &b) +constexpr bool operator==(Mat2 const & a, Mat2 const & b) { return a[0] == b[0] && a[1] == b[1]; } -constexpr bool operator!=(Mat2 const &a, Mat2 const &b) +constexpr bool operator!=(Mat2 const & a, Mat2 const & b) { return a[0] != b[0] || a[1] != b[1]; } -constexpr Mat2 operator+(Mat2 const &a, Mat2 const &b) +constexpr Mat2 operator+(Mat2 const & a, Mat2 const & b) { - return Mat2{.rows = {a[0] + b[0], a[1] + b[1]}}; + return Mat2{ + .rows = {a[0] + b[0], a[1] + b[1]} + }; } -constexpr Mat2 operator-(Mat2 const &a, Mat2 const &b) +constexpr Mat2 operator-(Mat2 const & a, Mat2 const & b) { - return Mat2{.rows = {a[0] - b[0], a[1] - b[1]}}; + return Mat2{ + .rows = {a[0] - b[0], a[1] - b[1]} + }; } -constexpr Vec2 operator*(Mat2 const &a, Vec2 const &b) +constexpr Vec2 operator*(Mat2 const & a, Vec2 const & b) { return Vec2{dot(a[0], b), dot(a[1], b)}; } -constexpr Mat2 operator*(Mat2 const &a, Mat2 const &b) +constexpr Mat2 operator*(Mat2 const & a, Mat2 const & b) { - return Mat2{.rows = {{dot(a[0], b.x()), dot(a[0], b.y())}, - {dot(a[1], b.x()), dot(a[1], b.y())}}}; + return Mat2{ + .rows = {{dot(a[0], b.x()), dot(a[0], b.y())}, + {dot(a[1], b.x()), dot(a[1], b.y())}} + }; } -constexpr Mat2 operator/(Mat2 const &a, Mat2 const &b) +constexpr Mat2 operator/(Mat2 const & a, Mat2 const & b) { - return Mat2{.rows = {a[0] / b[0], a[1] / b[1]}}; + return Mat2{ + .rows = {a[0] / b[0], a[1] / b[1]} + }; } -constexpr Mat2 &operator+=(Mat2 &a, Mat2 const &b) +constexpr Mat2 & operator+=(Mat2 & a, Mat2 const & b) { a = a + b; return a; } -constexpr Mat2 &operator-=(Mat2 &a, Mat2 const &b) +constexpr Mat2 & operator-=(Mat2 & a, Mat2 const & b) { a = a - b; return a; } -constexpr Mat2 &operator*=(Mat2 &a, Mat2 const &b) +constexpr Mat2 & operator*=(Mat2 & a, Mat2 const & b) { a = a * b; return a; } -constexpr Mat2 &operator/=(Mat2 &a, Mat2 const &b) +constexpr Mat2 & operator/=(Mat2 & a, Mat2 const & b) { a = a / b; return a; @@ -1604,14 +1617,18 @@ struct Mat3 static constexpr Mat3 splat(f32 value) { - return Mat3{.rows = {{value, value, value}, - {value, value, value}, - {value, value, value}}}; + return Mat3{ + .rows = {{value, value, value}, + {value, value, value}, + {value, value, value}} + }; } static constexpr Mat3 diagonal(f32 value) { - return Mat3{.rows = {{value, 0, 0}, {0, value, 0}, {0, 0, value}}}; + return Mat3{ + .rows = {{value, 0, 0}, {0, value, 0}, {0, 0, value}} + }; } static constexpr Mat3 identity() @@ -1619,12 +1636,12 @@ struct Mat3 return diagonal(1); } - constexpr Vec3 &operator[](usize index) + constexpr Vec3 & operator[](usize index) { return rows[index]; } - constexpr Vec3 const &operator[](usize index) const + constexpr Vec3 const & operator[](usize index) const { return rows[index]; } @@ -1645,64 +1662,72 @@ struct Mat3 } }; -constexpr bool operator==(Mat3 const &a, Mat3 const &b) +constexpr bool operator==(Mat3 const & a, Mat3 const & b) { return a[0] == b[0] && a[1] == b[1] && a[2] == b[2]; } -constexpr bool operator!=(Mat3 const &a, Mat3 const &b) +constexpr bool operator!=(Mat3 const & a, Mat3 const & b) { return a[0] != b[0] || a[1] != b[1] || a[2] != b[2]; } -constexpr Mat3 operator+(Mat3 const &a, Mat3 const &b) +constexpr Mat3 operator+(Mat3 const & a, Mat3 const & b) { - return Mat3{.rows = {a[0] + b[0], a[1] + b[1], a[2] + b[2]}}; + return Mat3{ + .rows = {a[0] + b[0], a[1] + b[1], a[2] + b[2]} + }; } -constexpr Mat3 operator-(Mat3 const &a, Mat3 const &b) +constexpr Mat3 operator-(Mat3 const & a, Mat3 const & b) { - return Mat3{.rows = {a[0] - b[0], a[1] - b[1], a[2] - b[2]}}; + return Mat3{ + .rows = {a[0] - b[0], a[1] - b[1], a[2] - b[2]} + }; } -constexpr Vec3 operator*(Mat3 const &a, Vec3 const &b) +constexpr Vec3 operator*(Mat3 const & a, Vec3 const & b) { return Vec3{dot(a[0], b), dot(a[1], b), dot(a[2], b)}; } -constexpr Mat3 operator*(Mat3 const &a, Mat3 const &b) +constexpr Mat3 operator*(Mat3 const & a, Mat3 const & b) { - return Mat3{.rows = { - {dot(a[0], b.x()), dot(a[0], b.y()), dot(a[0], b.z())}, - {dot(a[1], b.x()), dot(a[1], b.y()), dot(a[1], b.z())}, - {dot(a[2], b.x()), dot(a[2], b.y()), dot(a[2], b.z())}, - }}; + return Mat3{ + .rows = { + {dot(a[0], b.x()), dot(a[0], b.y()), dot(a[0], b.z())}, + {dot(a[1], b.x()), dot(a[1], b.y()), dot(a[1], b.z())}, + {dot(a[2], b.x()), dot(a[2], b.y()), dot(a[2], b.z())}, + } + }; } -constexpr Mat3 operator/(Mat3 const &a, Mat3 const &b) +constexpr Mat3 operator/(Mat3 const & a, Mat3 const & b) { - return Mat3{.rows = {a[0] / b[0], a[1] / b[1], a[2] / b[2]}}; + return Mat3{ + .rows = {a[0] / b[0], a[1] / b[1], a[2] / b[2]} + }; } -constexpr Mat3 &operator+=(Mat3 &a, Mat3 const &b) +constexpr Mat3 & operator+=(Mat3 & a, Mat3 const & b) { a = a + b; return a; } -constexpr Mat3 &operator-=(Mat3 &a, Mat3 const &b) +constexpr Mat3 & operator-=(Mat3 & a, Mat3 const & b) { a = a - b; return a; } -constexpr Mat3 &operator*=(Mat3 &a, Mat3 const &b) +constexpr Mat3 & operator*=(Mat3 & a, Mat3 const & b) { a = a * b; return a; } -constexpr Mat3 &operator/=(Mat3 &a, Mat3 const &b) +constexpr Mat3 & operator/=(Mat3 & a, Mat3 const & b) { a = a / b; return a; @@ -1713,24 +1738,28 @@ struct Mat3Affine static constexpr Vec3 trailing_row = Vec3{0, 0, 1}; Vec3 rows[2] = {}; - constexpr Vec3 &operator[](usize index) + constexpr Vec3 & operator[](usize index) { return rows[index]; } - constexpr Vec3 const &operator[](usize index) const + constexpr Vec3 const & operator[](usize index) const { return rows[index]; } constexpr operator Mat3() const { - return Mat3{.rows = {rows[0], rows[1], {0, 0, 1}}}; + return Mat3{ + .rows = {rows[0], rows[1], {0, 0, 1}} + }; } static constexpr Mat3Affine identity() { - return Mat3Affine{.rows = {{1, 0, 0}, {0, 1, 0}}}; + return Mat3Affine{ + .rows = {{1, 0, 0}, {0, 1, 0}} + }; } constexpr Vec3 x() const @@ -1749,80 +1778,91 @@ struct Mat3Affine } }; -constexpr bool operator==(Mat3Affine const &a, Mat3Affine const &b) +constexpr bool operator==(Mat3Affine const & a, Mat3Affine const & b) { return a[0] == b[0] && a[1] == b[1]; } -constexpr bool operator!=(Mat3Affine const &a, Mat3Affine const &b) +constexpr bool operator!=(Mat3Affine const & a, Mat3Affine const & b) { return a[0] != b[0] || a[1] != b[1]; } -constexpr Mat3Affine operator+(Mat3Affine const &a, Mat3Affine const &b) +constexpr Mat3Affine operator+(Mat3Affine const & a, Mat3Affine const & b) { - return Mat3Affine{.rows = {a[0] + b[0], a[1] + b[1]}}; + return Mat3Affine{ + .rows = {a[0] + b[0], a[1] + b[1]} + }; } -constexpr Mat3Affine operator-(Mat3Affine const &a, Mat3Affine const &b) +constexpr Mat3Affine operator-(Mat3Affine const & a, Mat3Affine const & b) { - return Mat3Affine{.rows = {a[0] - b[0], a[1] - b[1]}}; + return Mat3Affine{ + .rows = {a[0] - b[0], a[1] - b[1]} + }; } -constexpr Vec3 operator*(Mat3Affine const &a, Vec3 const &b) +constexpr Vec3 operator*(Mat3Affine const & a, Vec3 const & b) { return Vec3{dot(a[0], b), dot(a[1], b), dot(Mat3Affine::trailing_row, b)}; } -constexpr Mat3 operator*(Mat3Affine const &a, Mat3 const &b) +constexpr Mat3 operator*(Mat3Affine const & a, Mat3 const & b) { - return Mat3{.rows = { - {dot(a[0], b.x()), dot(a[0], b.y()), dot(a[0], b.z())}, - {dot(a[1], b.x()), dot(a[1], b.y()), dot(a[1], b.z())}, - {dot(Mat3Affine::trailing_row, b.x()), - dot(Mat3Affine::trailing_row, b.y()), - dot(Mat3Affine::trailing_row, b.z())}, - }}; + return Mat3{ + .rows = { + {dot(a[0], b.x()), dot(a[0], b.y()), dot(a[0], b.z())}, + {dot(a[1], b.x()), dot(a[1], b.y()), dot(a[1], b.z())}, + {dot(Mat3Affine::trailing_row, b.x()), + dot(Mat3Affine::trailing_row, b.y()), + dot(Mat3Affine::trailing_row, b.z())}, + } + }; } -constexpr Mat3 operator*(Mat3 const &a, Mat3Affine const &b) +constexpr Mat3 operator*(Mat3 const & a, Mat3Affine const & b) { - return Mat3{.rows = {{dot(a[0], b.x()), dot(a[0], b.y()), dot(a[0], b.z())}, - {dot(a[1], b.x()), dot(a[1], b.y()), dot(a[1], b.z())}, - {dot(a[2], b.x()), dot(a[2], b.y()), dot(a[2], b.z())}}}; + return Mat3{ + .rows = {{dot(a[0], b.x()), dot(a[0], b.y()), dot(a[0], b.z())}, + {dot(a[1], b.x()), dot(a[1], b.y()), dot(a[1], b.z())}, + {dot(a[2], b.x()), dot(a[2], b.y()), dot(a[2], b.z())}} + }; } -constexpr Mat3Affine operator*(Mat3Affine const &a, Mat3Affine const &b) +constexpr Mat3Affine operator*(Mat3Affine const & a, Mat3Affine const & b) { return Mat3Affine{ .rows = {{dot(a[0], b.x()), dot(a[0], b.y()), dot(a[0], b.z())}, - {dot(a[1], b.x()), dot(a[1], b.y()), dot(a[1], b.z())}}}; + {dot(a[1], b.x()), dot(a[1], b.y()), dot(a[1], b.z())}} + }; } -constexpr Mat3Affine operator/(Mat3Affine const &a, Mat3Affine const &b) +constexpr Mat3Affine operator/(Mat3Affine const & a, Mat3Affine const & b) { - return Mat3Affine{.rows = {a[0] / b[0], a[1] / b[1]}}; + return Mat3Affine{ + .rows = {a[0] / b[0], a[1] / b[1]} + }; } -constexpr Mat3Affine &operator+=(Mat3Affine &a, Mat3Affine const &b) +constexpr Mat3Affine & operator+=(Mat3Affine & a, Mat3Affine const & b) { a = a + b; return a; } -constexpr Mat3Affine &operator-=(Mat3Affine &a, Mat3Affine const &b) +constexpr Mat3Affine & operator-=(Mat3Affine & a, Mat3Affine const & b) { a = a - b; return a; } -constexpr Mat3Affine &operator*=(Mat3Affine &a, Mat3Affine const &b) +constexpr Mat3Affine & operator*=(Mat3Affine & a, Mat3Affine const & b) { a = a * b; return a; } -constexpr Mat3Affine &operator/=(Mat3Affine &a, Mat3Affine const &b) +constexpr Mat3Affine & operator/=(Mat3Affine & a, Mat3Affine const & b) { a = a / b; return a; @@ -1834,18 +1874,22 @@ struct Mat4 static constexpr Mat4 splat(f32 value) { - return Mat4{.rows = {{value, value, value, value}, - {value, value, value, value}, - {value, value, value, value}, - {value, value, value, value}}}; + return Mat4{ + .rows = {{value, value, value, value}, + {value, value, value, value}, + {value, value, value, value}, + {value, value, value, value}} + }; } static constexpr Mat4 diagonal(f32 value) { - return Mat4{.rows = {{value, 0, 0, 0}, - {0, value, 0, 0}, - {0, 0, value, 0}, - {0, 0, 0, value}}}; + return Mat4{ + .rows = {{value, 0, 0, 0}, + {0, value, 0, 0}, + {0, 0, value, 0}, + {0, 0, 0, value}} + }; } static constexpr Mat4 identity() @@ -1853,12 +1897,12 @@ struct Mat4 return diagonal(1); } - constexpr Vec4 &operator[](usize index) + constexpr Vec4 & operator[](usize index) { return rows[index]; } - constexpr Vec4 const &operator[](usize index) const + constexpr Vec4 const & operator[](usize index) const { return rows[index]; } @@ -1884,67 +1928,75 @@ struct Mat4 } }; -constexpr bool operator==(Mat4 const &a, Mat4 const &b) +constexpr bool operator==(Mat4 const & a, Mat4 const & b) { return a[0] == b[0] && a[1] == b[1] && a[2] == b[2] && a[3] == b[3]; } -constexpr bool operator!=(Mat4 const &a, Mat4 const &b) +constexpr bool operator!=(Mat4 const & a, Mat4 const & b) { return a[0] != b[0] || a[1] != b[1] || a[2] != b[2] || a[3] != b[3]; } -constexpr Mat4 operator+(Mat4 const &a, Mat4 const &b) +constexpr Mat4 operator+(Mat4 const & a, Mat4 const & b) { - return Mat4{.rows = {a[0] + b[0], a[1] + b[1], a[2] + b[2], a[3] + b[3]}}; + return Mat4{ + .rows = {a[0] + b[0], a[1] + b[1], a[2] + b[2], a[3] + b[3]} + }; } -constexpr Mat4 operator-(Mat4 const &a, Mat4 const &b) +constexpr Mat4 operator-(Mat4 const & a, Mat4 const & b) { - return Mat4{.rows = {a[0] - b[0], a[1] - b[1], a[2] - b[2], a[3] - b[3]}}; + return Mat4{ + .rows = {a[0] - b[0], a[1] - b[1], a[2] - b[2], a[3] - b[3]} + }; } -constexpr Vec4 operator*(Mat4 const &a, Vec4 const &b) +constexpr Vec4 operator*(Mat4 const & a, Vec4 const & b) { return Vec4{dot(a[0], b), dot(a[1], b), dot(a[2], b), dot(a[3], b)}; } -constexpr Mat4 operator*(Mat4 const &a, Mat4 const &b) +constexpr Mat4 operator*(Mat4 const & a, Mat4 const & b) { - return Mat4{.rows = {{dot(a[0], b.x()), dot(a[0], b.y()), dot(a[0], b.z()), - dot(a[0], b.w())}, - {dot(a[1], b.x()), dot(a[1], b.y()), dot(a[1], b.z()), - dot(a[1], b.w())}, - {dot(a[2], b.x()), dot(a[2], b.y()), dot(a[2], b.z()), - dot(a[2], b.w())}, - {dot(a[3], b.x()), dot(a[3], b.y()), dot(a[3], b.z()), - dot(a[3], b.w())}}}; + return Mat4{ + .rows = {{dot(a[0], b.x()), dot(a[0], b.y()), dot(a[0], b.z()), + dot(a[0], b.w())}, + {dot(a[1], b.x()), dot(a[1], b.y()), dot(a[1], b.z()), + dot(a[1], b.w())}, + {dot(a[2], b.x()), dot(a[2], b.y()), dot(a[2], b.z()), + dot(a[2], b.w())}, + {dot(a[3], b.x()), dot(a[3], b.y()), dot(a[3], b.z()), + dot(a[3], b.w())}} + }; } -constexpr Mat4 operator/(Mat4 const &a, Mat4 const &b) +constexpr Mat4 operator/(Mat4 const & a, Mat4 const & b) { - return Mat4{.rows = {a[0] / b[0], a[1] / b[1], a[2] / b[2], a[3] / b[3]}}; + return Mat4{ + .rows = {a[0] / b[0], a[1] / b[1], a[2] / b[2], a[3] / b[3]} + }; } -constexpr Mat4 &operator+=(Mat4 &a, Mat4 const &b) +constexpr Mat4 & operator+=(Mat4 & a, Mat4 const & b) { a = a + b; return a; } -constexpr Mat4 &operator-=(Mat4 &a, Mat4 const &b) +constexpr Mat4 & operator-=(Mat4 & a, Mat4 const & b) { a = a - b; return a; } -constexpr Mat4 &operator*=(Mat4 &a, Mat4 const &b) +constexpr Mat4 & operator*=(Mat4 & a, Mat4 const & b) { a = a * b; return a; } -constexpr Mat4 &operator/=(Mat4 &a, Mat4 const &b) +constexpr Mat4 & operator/=(Mat4 & a, Mat4 const & b) { a = a / b; return a; @@ -1955,24 +2007,28 @@ struct Mat4Affine static constexpr Vec4 trailing_row = Vec4{0, 0, 0, 1}; Vec4 rows[3] = {}; - constexpr Vec4 &operator[](usize index) + constexpr Vec4 & operator[](usize index) { return rows[index]; } - constexpr Vec4 const &operator[](usize index) const + constexpr Vec4 const & operator[](usize index) const { return rows[index]; } constexpr operator Mat4() const { - return Mat4{.rows = {rows[0], rows[1], rows[2], {0, 0, 0, 1}}}; + return Mat4{ + .rows = {rows[0], rows[1], rows[2], {0, 0, 0, 1}} + }; } static constexpr Mat4Affine identity() { - return Mat4Affine{.rows = {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}}}; + return Mat4Affine{ + .rows = {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}} + }; } constexpr Vec4 x() const @@ -1996,96 +2052,108 @@ struct Mat4Affine } }; -constexpr bool operator==(Mat4Affine const &a, Mat4Affine const &b) +constexpr bool operator==(Mat4Affine const & a, Mat4Affine const & b) { return a[0] == b[0] && a[1] == b[1] && a[2] == b[2]; } -constexpr bool operator!=(Mat4Affine const &a, Mat4Affine const &b) +constexpr bool operator!=(Mat4Affine const & a, Mat4Affine const & b) { return a[0] != b[0] || a[1] != b[1] || a[2] != b[2]; } -constexpr Mat4Affine operator+(Mat4Affine const &a, Mat4Affine const &b) +constexpr Mat4Affine operator+(Mat4Affine const & a, Mat4Affine const & b) { - return Mat4Affine{.rows = {a[0] + b[0], a[1] + b[1], a[2] + b[2]}}; + return Mat4Affine{ + .rows = {a[0] + b[0], a[1] + b[1], a[2] + b[2]} + }; } -constexpr Mat4Affine operator-(Mat4Affine const &a, Mat4Affine const &b) +constexpr Mat4Affine operator-(Mat4Affine const & a, Mat4Affine const & b) { - return Mat4Affine{.rows = {a[0] - b[0], a[1] - b[1], a[2] - b[2]}}; + return Mat4Affine{ + .rows = {a[0] - b[0], a[1] - b[1], a[2] - b[2]} + }; } -constexpr Vec4 operator*(Mat4Affine const &a, Vec4 const &b) +constexpr Vec4 operator*(Mat4Affine const & a, Vec4 const & b) { return Vec4{dot(a[0], b), dot(a[1], b), dot(a[2], b), dot(Mat4Affine::trailing_row, b)}; } -constexpr Mat4 operator*(Mat4Affine const &a, Mat4 const &b) +constexpr Mat4 operator*(Mat4Affine const & a, Mat4 const & b) { - return Mat4{.rows = { - {dot(a[0], b.x()), dot(a[0], b.y()), dot(a[0], b.z()), - dot(a[0], b.w())}, - {dot(a[1], b.x()), dot(a[1], b.y()), dot(a[1], b.z()), - dot(a[1], b.w())}, - {dot(a[2], b.x()), dot(a[2], b.y()), dot(a[2], b.z()), - dot(a[2], b.w())}, - {dot(Mat4Affine::trailing_row, b.x()), - dot(Mat4Affine::trailing_row, b.y()), - dot(Mat4Affine::trailing_row, b.z()), - dot(Mat4Affine::trailing_row, b.w())}, - }}; -} - -constexpr Mat4 operator*(Mat4 const &a, Mat4Affine const &b) -{ - return Mat4{.rows = { - {dot(a[0], b.x()), dot(a[0], b.y()), dot(a[0], b.z()), - dot(a[0], b.w())}, - {dot(a[1], b.x()), dot(a[1], b.y()), dot(a[1], b.z()), - dot(a[1], b.w())}, - {dot(a[2], b.x()), dot(a[2], b.y()), dot(a[2], b.z()), - dot(a[2], b.w())}, - {dot(a[3], b.x()), dot(a[3], b.y()), dot(a[3], b.z()), - dot(a[3], b.w())}, - }}; + return Mat4{ + .rows = { + {dot(a[0], b.x()), dot(a[0], b.y()), dot(a[0], b.z()), + dot(a[0], b.w())}, + {dot(a[1], b.x()), dot(a[1], b.y()), dot(a[1], b.z()), + dot(a[1], b.w())}, + {dot(a[2], b.x()), dot(a[2], b.y()), dot(a[2], b.z()), + dot(a[2], b.w())}, + {dot(Mat4Affine::trailing_row, b.x()), + dot(Mat4Affine::trailing_row, b.y()), + dot(Mat4Affine::trailing_row, b.z()), + dot(Mat4Affine::trailing_row, b.w())}, + } + }; +} + +constexpr Mat4 operator*(Mat4 const & a, Mat4Affine const & b) +{ + return Mat4{ + .rows = { + {dot(a[0], b.x()), dot(a[0], b.y()), dot(a[0], b.z()), + dot(a[0], b.w())}, + {dot(a[1], b.x()), dot(a[1], b.y()), dot(a[1], b.z()), + dot(a[1], b.w())}, + {dot(a[2], b.x()), dot(a[2], b.y()), dot(a[2], b.z()), + dot(a[2], b.w())}, + {dot(a[3], b.x()), dot(a[3], b.y()), dot(a[3], b.z()), + dot(a[3], b.w())}, + } + }; } -constexpr Mat4Affine operator*(Mat4Affine const &a, Mat4Affine const &b) +constexpr Mat4Affine operator*(Mat4Affine const & a, Mat4Affine const & b) { - return Mat4Affine{.rows = {{dot(a[0], b.x()), dot(a[0], b.y()), - dot(a[0], b.z()), dot(a[0], b.w())}, - {dot(a[1], b.x()), dot(a[1], b.y()), - dot(a[1], b.z()), dot(a[1], b.w())}, - {dot(a[2], b.x()), dot(a[2], b.y()), - dot(a[2], b.z()), dot(a[2], b.w())}}}; + return Mat4Affine{ + .rows = {{dot(a[0], b.x()), dot(a[0], b.y()), dot(a[0], b.z()), + dot(a[0], b.w())}, + {dot(a[1], b.x()), dot(a[1], b.y()), dot(a[1], b.z()), + dot(a[1], b.w())}, + {dot(a[2], b.x()), dot(a[2], b.y()), dot(a[2], b.z()), + dot(a[2], b.w())}} + }; } -constexpr Mat4Affine operator/(Mat4Affine const &a, Mat4Affine const &b) +constexpr Mat4Affine operator/(Mat4Affine const & a, Mat4Affine const & b) { - return Mat4Affine{.rows = {a[0] / b[0], a[1] / b[1], a[2] / b[2]}}; + return Mat4Affine{ + .rows = {a[0] / b[0], a[1] / b[1], a[2] / b[2]} + }; } -constexpr Mat4Affine &operator+=(Mat4Affine &a, Mat4Affine const &b) +constexpr Mat4Affine & operator+=(Mat4Affine & a, Mat4Affine const & b) { a = a + b; return a; } -constexpr Mat4Affine &operator-=(Mat4Affine &a, Mat4Affine const &b) +constexpr Mat4Affine & operator-=(Mat4Affine & a, Mat4Affine const & b) { a = a - b; return a; } -constexpr Mat4Affine &operator*=(Mat4Affine &a, Mat4Affine const &b) +constexpr Mat4Affine & operator*=(Mat4Affine & a, Mat4Affine const & b) { a = a * b; return a; } -constexpr Mat4Affine &operator/=(Mat4Affine &a, Mat4Affine const &b) +constexpr Mat4Affine & operator/=(Mat4Affine & a, Mat4Affine const & b) { a = a / b; return a; @@ -2141,34 +2209,40 @@ constexpr u32 num_mip_levels(Vec4U a) return (max == 0) ? 0 : (ulog2(max) + 1); } -constexpr Mat2 transpose(Mat2 const &a) +constexpr Mat2 transpose(Mat2 const & a) { - return Mat2{.rows = {a.x(), a.y()}}; + return Mat2{ + .rows = {a.x(), a.y()} + }; } -constexpr Mat3 transpose(Mat3 const &a) +constexpr Mat3 transpose(Mat3 const & a) { - return Mat3{.rows = {a.x(), a.y(), a.z()}}; + return Mat3{ + .rows = {a.x(), a.y(), a.z()} + }; } -constexpr Mat4 transpose(Mat4 const &a) +constexpr Mat4 transpose(Mat4 const & a) { - return Mat4{.rows = {a.x(), a.y(), a.z(), a.w()}}; + return Mat4{ + .rows = {a.x(), a.y(), a.z(), a.w()} + }; } -constexpr f32 determinant(Mat2 const &a) +constexpr f32 determinant(Mat2 const & a) { return a[0].x * a[1].y - a[1].x * a[0].y; } -constexpr f32 determinant(Mat3 const &a) +constexpr f32 determinant(Mat3 const & a) { return a[0].x * a[1].y * a[2].z - a[0].x * a[1].z * a[2].y - a[0].y * a[1].x * a[2].z + a[0].y * a[1].z * a[2].x + a[0].z * a[1].x * a[2].y - a[0].z * a[1].y * a[2].x; } -constexpr f32 determinant(Mat4 const &a) +constexpr f32 determinant(Mat4 const & a) { return a[0].x * (a[1].y * a[2].z * a[3].w + a[1].z * a[2].w * a[3].y + a[1].w * a[2].y * a[3].z - a[1].w * a[2].z * a[3].y - @@ -2184,24 +2258,27 @@ constexpr f32 determinant(Mat4 const &a) a[0].z * a[1].y * a[2].w - a[0].y * a[1].w * a[2].z); } -constexpr Mat2 adjoint(Mat2 const &a) +constexpr Mat2 adjoint(Mat2 const & a) { - return Mat2{.rows = {{a[1].y, -a[0].y}, {-a[1].x, a[0].x}}}; + return Mat2{ + .rows = {{a[1].y, -a[0].y}, {-a[1].x, a[0].x}} + }; } -constexpr Mat3 adjoint(Mat3 const &a) +constexpr Mat3 adjoint(Mat3 const & a) { return Mat3{ .rows = { - {a[1].y * a[2].z - a[1].z * a[2].y, a[0].z * a[2].y - a[0].y * a[2].z, + {a[1].y * a[2].z - a[1].z * a[2].y, a[0].z * a[2].y - a[0].y * a[2].z, a[0].y * a[1].z - a[0].z * a[1].y}, - {a[1].z * a[2].x - a[1].x * a[2].z, a[0].x * a[2].z - a[0].z * a[2].x, + {a[1].z * a[2].x - a[1].x * a[2].z, a[0].x * a[2].z - a[0].z * a[2].x, a[0].z * a[1].x - a[0].x * a[1].z}, - {a[1].x * a[2].y - a[1].y * a[2].x, a[0].y * a[2].x - a[0].x * a[2].y, - a[0].x * a[1].y - a[0].y * a[1].x}}}; + {a[1].x * a[2].y - a[1].y * a[2].x, a[0].y * a[2].x - a[0].x * a[2].y, + a[0].x * a[1].y - a[0].y * a[1].x}} + }; } -constexpr Mat4 adjoint(Mat4 const &a) +constexpr Mat4 adjoint(Mat4 const & a) { Mat4 r; r[0].x = a[1].y * a[2].z * a[3].w + a[1].z * a[2].w * a[3].y + @@ -2260,82 +2337,98 @@ constexpr Mat2 inverse(Mat2 a) return Mat2::splat(1.0F / determinant(a)) * adjoint(a); } -constexpr Mat3 inverse(Mat3 const &a) +constexpr Mat3 inverse(Mat3 const & a) { return Mat3::splat(1.0F / determinant(a)) * adjoint(a); } -constexpr Mat4 inverse(Mat4 const &a) +constexpr Mat4 inverse(Mat4 const & a) { return Mat4::splat(1.0F / determinant(a)) * adjoint(a); } constexpr Mat3Affine translate2d(Vec2 t) { - return Mat3Affine{.rows = {{1, 0, t.x}, {0, 1, t.y}}}; + return Mat3Affine{ + .rows = {{1, 0, t.x}, {0, 1, t.y}} + }; } constexpr Mat4Affine translate3d(Vec3 t) { - return Mat4Affine{.rows = {{1, 0, 0, t.x}, {0, 1, 0, t.y}, {0, 0, 1, t.z}}}; + return Mat4Affine{ + .rows = {{1, 0, 0, t.x}, {0, 1, 0, t.y}, {0, 0, 1, t.z}} + }; } constexpr Mat3Affine scale2d(Vec2 s) { - return Mat3Affine{.rows = {{s.x, 0, 0}, {0, s.y, 0}}}; + return Mat3Affine{ + .rows = {{s.x, 0, 0}, {0, s.y, 0}} + }; } constexpr Mat4Affine scale3d(Vec3 s) { - return Mat4Affine{.rows = {{s.x, 0, 0, 0}, {0, s.y, 0, 0}, {0, 0, s.z, 0}}}; + return Mat4Affine{ + .rows = {{s.x, 0, 0, 0}, {0, s.y, 0, 0}, {0, 0, s.z, 0}} + }; } inline Mat3Affine rotate2d(f32 radians) { - return Mat3Affine{.rows = {{cos(radians), -sin(radians), 0}, - {sin(radians), cos(radians), 0}}}; + return Mat3Affine{ + .rows = {{cos(radians), -sin(radians), 0}, + {sin(radians), cos(radians), 0}} + }; } inline Mat4Affine rotate3d_x(f32 radians) { - return Mat4Affine{.rows = {{1, 0, 0, 0}, - {0, cos(radians), -sin(radians), 0}, - {0, sin(radians), cos(radians), 0}}}; + return Mat4Affine{ + .rows = {{1, 0, 0, 0}, + {0, cos(radians), -sin(radians), 0}, + {0, sin(radians), cos(radians), 0}} + }; } inline Mat4Affine rotate3d_y(f32 radians) { - return Mat4Affine{.rows = {{cos(radians), 0, sin(radians), 0}, - {0, 1, 0, 0}, - {-sin(radians), 0, cos(radians), 0}}}; + return Mat4Affine{ + .rows = {{cos(radians), 0, sin(radians), 0}, + {0, 1, 0, 0}, + {-sin(radians), 0, cos(radians), 0}} + }; } inline Mat4Affine rotate3d_z(f32 radians) { - return Mat4Affine{.rows = {{cos(radians), -sin(radians), 0, 0}, - {sin(radians), cos(radians), 0, 0}, - {0, 0, 1, 0}}}; + return Mat4Affine{ + .rows = {{cos(radians), -sin(radians), 0, 0}, + {sin(radians), cos(radians), 0, 0}, + {0, 0, 1, 0}} + }; } -constexpr Vec2 transform(Mat3 const &t, Vec2 value) +constexpr Vec2 transform(Mat3 const & t, Vec2 value) { Vec3 v = t * Vec3{value.x, value.y, 1}; return Vec2{v.x, v.y}; } -constexpr Vec2 transform(Mat3Affine const &t, Vec2 value) +constexpr Vec2 transform(Mat3Affine const & t, Vec2 value) { Vec3 v = t * Vec3{value.x, value.y, 1}; return Vec2{v.x, v.y}; } -constexpr Vec3 transform(Mat4 const &t, Vec3 value) +constexpr Vec3 transform(Mat4 const & t, Vec3 value) { Vec4 v = t * Vec4{value.x, value.y, value.z, 1}; return Vec3{v.x, v.y, v.z}; } -constexpr Vec3 transform(Mat4Affine const &t, Vec3 value) +constexpr Vec3 transform(Mat4Affine const & t, Vec3 value) { Vec4 v = t * Vec4{value.x, value.y, 1}; return Vec3{v.x, v.y, v.z}; @@ -2505,12 +2598,12 @@ struct Rect } }; -constexpr bool operator==(Rect const &a, Rect const &b) +constexpr bool operator==(Rect const & a, Rect const & b) { return a.offset == b.offset && a.extent == b.extent; } -constexpr bool operator!=(Rect const &a, Rect const &b) +constexpr bool operator!=(Rect const & a, Rect const & b) { return a.offset != b.offset || a.extent != b.extent; } @@ -2558,12 +2651,12 @@ constexpr Rect CRect::offseted() const return Rect::from_center(center, extent); } -constexpr bool operator==(CRect const &a, CRect const &b) +constexpr bool operator==(CRect const & a, CRect const & b) { return a.center == b.center && a.extent == b.extent; } -constexpr bool operator!=(CRect const &a, CRect const &b) +constexpr bool operator!=(CRect const & a, CRect const & b) { return a.center != b.center || a.extent != b.extent; } @@ -2579,12 +2672,12 @@ struct RectU } }; -constexpr bool operator==(RectU const &a, RectU const &b) +constexpr bool operator==(RectU const & a, RectU const & b) { return a.offset == b.offset && a.extent == b.extent; } -constexpr bool operator!=(RectU const &a, RectU const &b) +constexpr bool operator!=(RectU const & a, RectU const & b) { return a.offset != b.offset || a.extent != b.extent; } @@ -2622,12 +2715,12 @@ struct Box } }; -constexpr bool operator==(Box const &a, Box const &b) +constexpr bool operator==(Box const & a, Box const & b) { return a.offset == b.offset && a.extent == b.extent; } -constexpr bool operator!=(Box const &a, Box const &b) +constexpr bool operator!=(Box const & a, Box const & b) { return a.offset != b.offset || a.extent != b.extent; } @@ -2675,12 +2768,12 @@ constexpr Box CBox::offseted() const return Box::from_center(center, extent); } -constexpr bool operator==(CBox const &a, CBox const &b) +constexpr bool operator==(CBox const & a, CBox const & b) { return a.center == b.center && a.extent == b.extent; } -constexpr bool operator!=(CBox const &a, CBox const &b) +constexpr bool operator!=(CBox const & a, CBox const & b) { return a.center != b.center || a.extent != b.extent; } @@ -2697,7 +2790,7 @@ constexpr bool contains_point(Vec2 begin, Vec2 end, Vec2 point) end.y >= point.y; } -constexpr void intersect(Vec2 a_begin, Vec2 a_end, Vec2 &b_begin, Vec2 &b_end) +constexpr void intersect(Vec2 a_begin, Vec2 a_end, Vec2 & b_begin, Vec2 & b_end) { if (!overlaps(a_begin, a_end, b_begin, b_end)) { @@ -2710,27 +2803,27 @@ constexpr void intersect(Vec2 a_begin, Vec2 a_end, Vec2 &b_begin, Vec2 &b_end) b_end = Vec2{min(a_end.x, b_end.x), min(a_end.y, b_end.y)}; } -constexpr bool contains(Rect const &rect, Vec2 point) +constexpr bool contains(Rect const & rect, Vec2 point) { return contains_point(rect.begin(), rect.end(), point); } -constexpr bool contains(CRect const &rect, Vec2 point) +constexpr bool contains(CRect const & rect, Vec2 point) { return contains_point(rect.begin(), rect.end(), point); } -constexpr bool overlaps(Rect const &a, Rect const &b) +constexpr bool overlaps(Rect const & a, Rect const & b) { return ash::overlaps(a.begin(), a.end(), b.begin(), b.end()); } -constexpr bool overlaps(CRect const &a, CRect const &b) +constexpr bool overlaps(CRect const & a, CRect const & b) { return ash::overlaps(a.begin(), a.end(), b.begin(), b.end()); } -constexpr Rect intersect(Rect const &a, Rect const &b) +constexpr Rect intersect(Rect const & a, Rect const & b) { Vec2 begin = b.begin(); Vec2 end = b.end(); @@ -2738,7 +2831,7 @@ constexpr Rect intersect(Rect const &a, Rect const &b) return Rect{.offset = begin, .extent = end - begin}; } -constexpr CRect intersect(CRect const &a, CRect const &b) +constexpr CRect intersect(CRect const & a, CRect const & b) { Vec2 begin = b.begin(); Vec2 end = b.end(); @@ -2746,7 +2839,7 @@ constexpr CRect intersect(CRect const &a, CRect const &b) return CRect::from_offset(begin, end - begin); } -constexpr bool contains(Box const &box, Vec3 point) +constexpr bool contains(Box const & box, Vec3 point) { return box.offset.x <= point.x && box.offset.y <= point.y && box.offset.z <= point.z && (box.offset.x + box.extent.x) >= point.x && @@ -2755,7 +2848,7 @@ constexpr bool contains(Box const &box, Vec3 point) return true; } -constexpr bool overlaps(Box const &a, Box const &b) +constexpr bool overlaps(Box const & a, Box const & b) { Vec3 a_begin = a.offset; Vec3 a_end = a.offset + a.extent; @@ -2775,9 +2868,11 @@ constexpr bool overlaps(Box const &a, Box const &b) constexpr Mat4Affine orthographic(f32 x_mag, f32 y_mag, f32 z_near, f32 z_far) { f32 const z_diff = z_near - z_far; - return Mat4Affine{{{1 / x_mag, 0, 0, 0}, - {0, 1 / y_mag, 0, 0}, - {0, 0, 2 / z_diff, (z_far + z_near) / z_diff}}}; + return Mat4Affine{ + {{1 / x_mag, 0, 0, 0}, + {0, 1 / y_mag, 0, 0}, + {0, 0, 2 / z_diff, (z_far + z_near) / z_diff}} + }; } /// @param aspect_ratio The aspect ratio of the field of view. @@ -2789,10 +2884,12 @@ inline Mat4 perspective(f32 aspect_ratio, f32 y_fov, f32 z_far, f32 z_near) { f32 const s = tanf(y_fov * 0.5F); f32 const z_diff = z_near - z_far; - return Mat4{{{1 / (aspect_ratio * s), 0, 0, 0}, - {0, 1 / s, 0, 0}, - {0, 0, (z_far + z_near) / z_diff, (2 * z_far * z_near) / z_diff}, - {0, 0, -1, 0}}}; + return Mat4{ + {{1 / (aspect_ratio * s), 0, 0, 0}, + {0, 1 / s, 0, 0}, + {0, 0, (z_far + z_near) / z_diff, (2 * z_far * z_near) / z_diff}, + {0, 0, -1, 0}} + }; } constexpr Mat4 look_at(Vec3 eye, Vec3 center, Vec3 up) @@ -2801,10 +2898,12 @@ constexpr Mat4 look_at(Vec3 eye, Vec3 center, Vec3 up) Vec3 const s = normalize(cross(up, f)); Vec3 const u = cross(f, s); - return {{{s.x, s.x, s.x, 0}, - {u.y, u.y, u.y, 0}, - {f.z, f.z, f.z, 0}, - {-dot(s, eye), -dot(u, eye), -dot(f, eye), 1}}}; + return { + {{s.x, s.x, s.x, 0}, + {u.y, u.y, u.y, 0}, + {f.z, f.z, f.z, 0}, + {-dot(s, eye), -dot(u, eye), -dot(f, eye), 1}} + }; } /// @brief Given an object-clip space (mvp) matrix, determine if the object is @@ -2819,7 +2918,7 @@ constexpr Mat4 look_at(Vec3 eye, Vec3 center, Vec3 up) /// -w <= y <= w /// 0 <= z <= w /// -constexpr bool is_outside_frustum(Mat4 const &mvp, Vec3 offset, Vec3 extent) +constexpr bool is_outside_frustum(Mat4 const & mvp, Vec3 offset, Vec3 extent) { constexpr u8 NUM_CORNERS = 8; Vec4 const corners[NUM_CORNERS] = { @@ -2839,7 +2938,7 @@ constexpr bool is_outside_frustum(Mat4 const &mvp, Vec3 offset, Vec3 extent) for (u8 i = 0; i < NUM_CORNERS; i++) { - Vec4 const &corner = corners[i]; + Vec4 const & corner = corners[i]; if (corner.x < -corner.w) { @@ -2871,7 +2970,7 @@ constexpr bool is_outside_frustum(Mat4 const &mvp, Vec3 offset, Vec3 extent) bottom == NUM_CORNERS || back == NUM_CORNERS; } -constexpr void frustum_cull(Mat4 const &mvp, Span global_transform, +constexpr void frustum_cull(Mat4 const & mvp, Span global_transform, Span aabb, BitSpan is_visible) { for (u32 i = 0; i < aabb.size32(); i++) diff --git a/ashura/std/mem.h b/ashura/std/mem.h index 139b389f..c7cf7005 100644 --- a/ashura/std/mem.h +++ b/ashura/std/mem.h @@ -26,7 +26,7 @@ constexpr T align_offset(T alignment, T offset) } template -T *align_ptr(usize alignment, T *p) +T * align_ptr(usize alignment, T * p) { return (T *) align_offset(alignment, (uptr) p); } @@ -38,7 +38,7 @@ constexpr bool is_aligned(T alignment, T offset) } template -bool is_ptr_aligned(usize alignment, T *p) +bool is_ptr_aligned(usize alignment, T * p) { return is_aligned(alignment, (uptr) p); } @@ -47,7 +47,7 @@ namespace mem { template -void copy(Span src, U *dst) +void copy(Span src, U * dst) { if (src.is_empty()) [[unlikely]] { @@ -64,7 +64,7 @@ void copy(Span src, Span dst) } template -void move(Span src, U *dst) +void move(Span src, U * dst) { if (src.is_empty()) [[unlikely]] { @@ -81,7 +81,7 @@ void move(Span src, Span dst) } template -void zero(T *dst, usize n) +void zero(T * dst, usize n) { if (n == 0) [[unlikely]] { @@ -98,7 +98,7 @@ void zero(Span dst) } template -void fill(T *dst, usize n, u8 byte) +void fill(T * dst, usize n, u8 byte) { if (n == 0) [[unlikely]] { @@ -122,7 +122,7 @@ bool eq(Span a, Span b) } template -ASH_FORCE_INLINE T nontemporal_load(T const &src) +ASH_FORCE_INLINE T nontemporal_load(T const & src) { #if ASH_HAS_BUILTIN(nontemporal_load) return __builtin_nontemporal_load(&src); @@ -132,7 +132,7 @@ ASH_FORCE_INLINE T nontemporal_load(T const &src) } template -ASH_FORCE_INLINE void nontemporal_store(T &dst, T data) +ASH_FORCE_INLINE void nontemporal_store(T & dst, T data) { #if ASH_HAS_BUILTIN(nontemporal_store) __builtin_nontemporal_store(data, &dst); @@ -142,7 +142,7 @@ ASH_FORCE_INLINE void nontemporal_store(T &dst, T data) } template -ASH_FORCE_INLINE void prefetch(T const *src, int rw, int locality) +ASH_FORCE_INLINE void prefetch(T const * src, int rw, int locality) { #if ASH_HAS_BUILTIN(prefetch) __builtin_prefetch(src, rw, locality); @@ -171,7 +171,7 @@ struct Layout usize alignment = 1; usize size = 0; - constexpr Layout append(Layout const &ext) const + constexpr Layout append(Layout const & ext) const { return Layout{.alignment = max(alignment, ext.alignment), .size = align_offset(ext.alignment, size) + ext.size}; @@ -210,7 +210,7 @@ struct Flex constexpr Layout layout() const { Layout l; - for (Layout const &m : members) + for (Layout const & m : members) { l = l.append(m); } @@ -218,7 +218,7 @@ struct Flex } template - void unpack_at(void const *&stack, usize i, Span &span) const + void unpack_at(void const *& stack, usize i, Span & span) const { stack = align_ptr(members[i].alignment, stack); usize const count = members[i].size / sizeof(T); @@ -227,7 +227,7 @@ struct Flex } template - void unpack_at(void const *&stack, usize i, T *&ptr) const + void unpack_at(void const *& stack, usize i, T *& ptr) const { Span span; unpack_at(stack, i, span); @@ -235,8 +235,8 @@ struct Flex } template - requires(sizeof...(T) == N) - void unpack(void const *stack, T &...p) const + requires (sizeof...(T) == N) + void unpack(void const * stack, T &... p) const { usize i = 0; (unpack_at(stack, i++, p), ...); @@ -269,7 +269,7 @@ struct StrEq struct BitEq { template - bool operator()(T const &a, T const &b) const + bool operator()(T const & a, T const & b) const { return mem::eq(Span{&a, 1}, Span{&b, 1}); } diff --git a/ashura/std/obj.h b/ashura/std/obj.h index db521866..42899597 100644 --- a/ashura/std/obj.h +++ b/ashura/std/obj.h @@ -12,16 +12,16 @@ namespace obj template constexpr void default_construct(Span dst) { - for (T *iter = dst.begin(); iter != dst.end(); iter++) + for (T * iter = dst.begin(); iter != dst.end(); iter++) { new (iter) T{}; } } template -constexpr void move_construct(Span src, U *dst) +constexpr void move_construct(Span src, U * dst) { - for (T *in = src.begin(); in != src.end(); in++, dst++) + for (T * in = src.begin(); in != src.end(); in++, dst++) { new (dst) T{static_cast(*in)}; } @@ -34,9 +34,9 @@ constexpr void move_construct(Span src, Span dst) } template -constexpr void copy_construct(Span src, U *dst) +constexpr void copy_construct(Span src, U * dst) { - for (T *in = src.begin(); in != src.end(); in++, dst++) + for (T * in = src.begin(); in != src.end(); in++, dst++) { new (dst) T{*in}; } @@ -53,7 +53,7 @@ constexpr void destruct(Span src) { if constexpr (!TriviallyDestructible) { - for (T *iter = src.begin(); iter != src.end(); iter++) + for (T * iter = src.begin(); iter != src.end(); iter++) { iter->~T(); } @@ -61,9 +61,9 @@ constexpr void destruct(Span src) } template -constexpr void move(Span src, U *dst) +constexpr void move(Span src, U * dst) { - for (T *in = src.begin(); in != src.end(); in++, dst++) + for (T * in = src.begin(); in != src.end(); in++, dst++) { *in = (T &&) (*dst); } @@ -76,9 +76,9 @@ constexpr void move(Span src, Span dst) } template -constexpr void copy(Span src, U *dst) +constexpr void copy(Span src, U * dst) { - for (T *in = src.begin(); in != src.end(); in++, dst++) + for (T * in = src.begin(); in != src.end(); in++, dst++) { *dst = *in; } @@ -93,7 +93,7 @@ constexpr void copy(Span src, Span dst) /// @brief move-construct object from src to an uninitialized memory range /// dst_mem and destroy object at src_mem, leaving src's objects uninitialized. template -constexpr void relocate(Span src, U *dst) +constexpr void relocate(Span src, U * dst) { if constexpr (TriviallyRelocatable) { @@ -116,7 +116,7 @@ constexpr void relocate(Span src, Span dst) /// /// @note src_mem and dst_mem must not be same nor overlapping. template -constexpr void relocate_non_overlapping(Span src, U *dst) +constexpr void relocate_non_overlapping(Span src, U * dst) { if constexpr (TriviallyRelocatable) { diff --git a/ashura/std/option.h b/ashura/std/option.h index dfe9bd53..252f7b8c 100644 --- a/ashura/std/option.h +++ b/ashura/std/option.h @@ -48,13 +48,15 @@ struct [[nodiscard]] Option } constexpr Option(Some some) : - is_some_{true}, value_{static_cast(some.value)} + is_some_{true}, + value_{static_cast(some.value)} { } template - explicit constexpr Option(V<0>, Args &&...args) : - is_some_{true}, value_{static_cast(args)...} + explicit constexpr Option(V<0>, Args &&... args) : + is_some_{true}, + value_{static_cast(args)...} { } @@ -62,7 +64,7 @@ struct [[nodiscard]] Option { } - constexpr Option &operator=(Some other) + constexpr Option & operator=(Some other) { if (is_some_) { @@ -73,7 +75,7 @@ struct [[nodiscard]] Option return *this; } - constexpr Option &operator=(NoneType) + constexpr Option & operator=(NoneType) { if (is_some_) { @@ -83,7 +85,7 @@ struct [[nodiscard]] Option return *this; } - constexpr Option(Option &&other) : is_some_{other.is_some_} + constexpr Option(Option && other) : is_some_{other.is_some_} { if (other.is_some_) { @@ -91,7 +93,7 @@ struct [[nodiscard]] Option } } - constexpr Option &operator=(Option &&other) + constexpr Option & operator=(Option && other) { if (this == &other) [[unlikely]] { @@ -113,7 +115,7 @@ struct [[nodiscard]] Option return *this; } - constexpr Option(Option const &other) : is_some_{other.is_some_} + constexpr Option(Option const & other) : is_some_{other.is_some_} { if (other.is_some_) { @@ -121,7 +123,7 @@ struct [[nodiscard]] Option } } - constexpr Option &operator=(Option const &other) + constexpr Option & operator=(Option const & other) { if (this == &other) [[unlikely]] { @@ -159,7 +161,7 @@ struct [[nodiscard]] Option } template - [[nodiscard]] constexpr bool contains(CmpType const &cmp) const + [[nodiscard]] constexpr bool contains(CmpType const & cmp) const { if (is_some_) { @@ -171,13 +173,14 @@ struct [[nodiscard]] Option } } - constexpr T &value(SourceLocation loc = SourceLocation::current()) + constexpr T & value(SourceLocation loc = SourceLocation::current()) { CHECK_DESC_SRC(loc, is_some_, "Expected Value in Option but got None"); return value_; } - constexpr T const &value(SourceLocation loc = SourceLocation::current()) const + constexpr T const & + value(SourceLocation loc = SourceLocation::current()) const { CHECK_DESC_SRC(loc, is_some_, "Expected Value in Option but got None"); return value_; @@ -201,7 +204,7 @@ struct [[nodiscard]] Option return None; } - constexpr T expect(char const *msg, + constexpr T expect(char const * msg, SourceLocation loc = SourceLocation::current()) { CHECK_DESC_SRC(loc, is_some_, msg); @@ -215,7 +218,7 @@ struct [[nodiscard]] Option } template - constexpr T unwrap_or(U &&alt) + constexpr T unwrap_or(U && alt) { if (is_some_) { @@ -225,7 +228,7 @@ struct [[nodiscard]] Option } template - constexpr T unwrap_or_else(Fn &&op) + constexpr T unwrap_or_else(Fn && op) { if (is_some_) { @@ -235,7 +238,7 @@ struct [[nodiscard]] Option } template - constexpr auto map(Fn &&op) + constexpr auto map(Fn && op) { using U = decltype(op(value_)); if (is_some_) @@ -246,7 +249,7 @@ struct [[nodiscard]] Option } template - constexpr auto map_or(Fn &&op, U &&alt) + constexpr auto map_or(Fn && op, U && alt) { if (is_some_) { @@ -256,7 +259,7 @@ struct [[nodiscard]] Option } template - constexpr decltype(auto) map_or_else(Fn &&op, AltFn &&alt_fn) + constexpr decltype(auto) map_or_else(Fn && op, AltFn && alt_fn) { if (is_some_) { @@ -266,7 +269,7 @@ struct [[nodiscard]] Option } template - constexpr auto and_then(Fn &&op) + constexpr auto and_then(Fn && op) { using OutOption = decltype(op(value_)); if (is_some_) @@ -277,7 +280,7 @@ struct [[nodiscard]] Option } template - constexpr auto or_else(Fn &&op) + constexpr auto or_else(Fn && op) { using OutOption = decltype(op()); if (is_some_) @@ -287,7 +290,7 @@ struct [[nodiscard]] Option return op(); } - constexpr void expect_none(char const *msg, + constexpr void expect_none(char const * msg, SourceLocation loc = SourceLocation::current()) { CHECK_DESC_SRC(loc, !is_some_, msg, " ", value_); @@ -300,7 +303,7 @@ struct [[nodiscard]] Option } template - constexpr decltype(auto) match(SomeFn &&some_fn, NoneFn &&none_fn) + constexpr decltype(auto) match(SomeFn && some_fn, NoneFn && none_fn) { if (is_some_) { @@ -310,7 +313,7 @@ struct [[nodiscard]] Option } template - constexpr decltype(auto) match(SomeFn &&some_fn, NoneFn &&none_fn) const + constexpr decltype(auto) match(SomeFn && some_fn, NoneFn && none_fn) const { if (is_some_) { @@ -324,13 +327,13 @@ template Option(Some) -> Option; template -[[nodiscard]] constexpr bool operator==(Some const &a, Some const &b) +[[nodiscard]] constexpr bool operator==(Some const & a, Some const & b) { return a.value == b.value; } template -[[nodiscard]] constexpr bool operator!=(Some const &a, Some const &b) +[[nodiscard]] constexpr bool operator!=(Some const & a, Some const & b) { return a.value != b.value; } @@ -358,7 +361,8 @@ template } template -[[nodiscard]] constexpr bool operator==(Option const &a, Option const &b) +[[nodiscard]] constexpr bool operator==(Option const & a, + Option const & b) { if (a.is_none() && b.is_none()) { @@ -372,7 +376,8 @@ template } template -[[nodiscard]] constexpr bool operator!=(Option const &a, Option const &b) +[[nodiscard]] constexpr bool operator!=(Option const & a, + Option const & b) { if (a.is_none() && b.is_none()) { @@ -386,7 +391,7 @@ template } template -[[nodiscard]] constexpr bool operator==(Option const &a, Some const &b) +[[nodiscard]] constexpr bool operator==(Option const & a, Some const & b) { if (a.is_some_) { @@ -396,7 +401,7 @@ template } template -[[nodiscard]] constexpr bool operator!=(Option const &a, Some const &b) +[[nodiscard]] constexpr bool operator!=(Option const & a, Some const & b) { if (a.is_some_) { @@ -406,7 +411,7 @@ template } template -[[nodiscard]] constexpr bool operator==(Some const &a, Option const &b) +[[nodiscard]] constexpr bool operator==(Some const & a, Option const & b) { if (b.is_some_) { @@ -416,7 +421,7 @@ template } template -[[nodiscard]] constexpr bool operator!=(Some const &a, Option const &b) +[[nodiscard]] constexpr bool operator!=(Some const & a, Option const & b) { if (b.is_some_) { @@ -426,25 +431,25 @@ template } template -[[nodiscard]] constexpr bool operator==(Option const &a, NoneType) +[[nodiscard]] constexpr bool operator==(Option const & a, NoneType) { return a.is_none(); } template -[[nodiscard]] constexpr bool operator!=(Option const &a, NoneType) +[[nodiscard]] constexpr bool operator!=(Option const & a, NoneType) { return a.is_some_; } template -[[nodiscard]] constexpr bool operator==(NoneType, Option const &a) +[[nodiscard]] constexpr bool operator==(NoneType, Option const & a) { return a.is_none(); } template -[[nodiscard]] constexpr bool operator!=(NoneType, Option const &a) +[[nodiscard]] constexpr bool operator!=(NoneType, Option const & a) { return a.is_some_; } diff --git a/ashura/std/panic.cc b/ashura/std/panic.cc index 3db8f878..ccb42c6f 100644 --- a/ashura/std/panic.cc +++ b/ashura/std/panic.cc @@ -13,9 +13,9 @@ void noop_panic_handler() void exception_panic_handler() { throw Panic{}; -}; +} -ASH_C_LINKAGE ASH_DLL_EXPORT u64 *panic_count = &panic_count_impl; +ASH_C_LINKAGE ASH_DLL_EXPORT u64 * panic_count = &panic_count_impl; ASH_C_LINKAGE ASH_DLL_EXPORT PanicHandler panic_handler = #if ASH_CFG(PANIC_HANDLER, EXCEPTION) @@ -24,4 +24,4 @@ ASH_C_LINKAGE ASH_DLL_EXPORT PanicHandler panic_handler = noop_panic_handler; #endif -} // namespace ash \ No newline at end of file +} // namespace ash diff --git a/ashura/std/panic.h b/ashura/std/panic.h index 89ddb4d3..51a29ca9 100644 --- a/ashura/std/panic.h +++ b/ashura/std/panic.h @@ -11,7 +11,7 @@ struct Panic typedef void (*PanicHandler)(); -ASH_C_LINKAGE ASH_DLL_EXPORT u64 *panic_count; +ASH_C_LINKAGE ASH_DLL_EXPORT u64 * panic_count; ASH_C_LINKAGE ASH_DLL_EXPORT PanicHandler panic_handler; diff --git a/ashura/std/range.h b/ashura/std/range.h index 86bd3669..dfc41be2 100644 --- a/ashura/std/range.h +++ b/ashura/std/range.h @@ -9,10 +9,10 @@ namespace ash // TODO: lamarrr view namespace template -constexpr void swap_range(Span a, Span b, SwapOpT &&swap_op = {}) +constexpr void swap_range(Span a, Span b, SwapOpT && swap_op = {}) { - A *a_iter = begin(a); - B *b_iter = begin(b); + A * a_iter = begin(a); + B * b_iter = begin(b); for (; a_iter != end(a); a_iter++, b_iter++) { swap_op(*a_iter, *b_iter); @@ -20,7 +20,7 @@ constexpr void swap_range(Span a, Span b, SwapOpT &&swap_op = {}) } template -constexpr void fill(R &&dst, U &&value) +constexpr void fill(R && dst, U && value) { OutputIterator auto it = begin(dst); while (it != end(dst)) @@ -31,7 +31,7 @@ constexpr void fill(R &&dst, U &&value) } template -constexpr bool all_of(R &&range, Predicate &&predicate) +constexpr bool all_of(R && range, Predicate && predicate) { InputIterator auto it = begin(range); while (it != end(range)) @@ -46,7 +46,7 @@ constexpr bool all_of(R &&range, Predicate &&predicate) } template -constexpr bool any_of(R &&range, Predicate &&predicate) +constexpr bool any_of(R && range, Predicate && predicate) { InputIterator auto it = begin(range); while (it != end(range)) @@ -61,7 +61,7 @@ constexpr bool any_of(R &&range, Predicate &&predicate) } template -constexpr bool none_of(R &&range, Predicate &&predicate) +constexpr bool none_of(R && range, Predicate && predicate) { InputIterator auto it = begin(range); while (it != end(range)) @@ -76,7 +76,7 @@ constexpr bool none_of(R &&range, Predicate &&predicate) } template -constexpr bool contains(R &&range, U &&value, Cmp &&cmp = {}) +constexpr bool contains(R && range, U && value, Cmp && cmp = {}) { InputIterator auto it = begin(range); while (it != end(range)) @@ -91,7 +91,7 @@ constexpr bool contains(R &&range, U &&value, Cmp &&cmp = {}) } template -constexpr bool begins_with(B &&body, H &&head, Cmp &&cmp = {}) +constexpr bool begins_with(B && body, H && head, Cmp && cmp = {}) { if (size(head) > size(body)) { @@ -115,7 +115,7 @@ constexpr bool begins_with(B &&body, H &&head, Cmp &&cmp = {}) } template -constexpr bool ends_with(B &&body, F &&foot, Cmp &&cmp = {}) +constexpr bool ends_with(B && body, F && foot, Cmp && cmp = {}) { if (size(foot) > size(body)) { @@ -141,7 +141,7 @@ constexpr bool ends_with(B &&body, F &&foot, Cmp &&cmp = {}) /// size is 0 if not found, size is 1 if found template -constexpr Span find(Span span, U &&value, Cmp &&cmp = {}) +constexpr Span find(Span span, U && value, Cmp && cmp = {}) { usize offset = 0; for (; offset < span.size(); offset++) @@ -155,7 +155,7 @@ constexpr Span find(Span span, U &&value, Cmp &&cmp = {}) } template -constexpr Span find_if(Span span, Predicate &&predicate) +constexpr Span find_if(Span span, Predicate && predicate) { usize offset = 0; for (; offset < span.size(); offset++) @@ -169,10 +169,10 @@ constexpr Span find_if(Span span, Predicate &&predicate) } template -constexpr usize count(R &&range, Target &&target, Cmp &&cmp = {}) +constexpr usize count(R && range, Target && target, Cmp && cmp = {}) { usize count = 0; - for (auto &element : range) + for (auto & element : range) { if (cmp(element, target)) { @@ -183,10 +183,10 @@ constexpr usize count(R &&range, Target &&target, Cmp &&cmp = {}) } template -constexpr usize count_if(R &&range, Predicate &&predicate) +constexpr usize count_if(R && range, Predicate && predicate) { usize count = 0; - for (auto &element : range) + for (auto & element : range) { if (predicate(element)) { @@ -197,7 +197,7 @@ constexpr usize count_if(R &&range, Predicate &&predicate) } template -constexpr bool range_eq(A &&a, B &&b, Cmp &&cmp = {}) +constexpr bool range_eq(A && a, B && b, Cmp && cmp = {}) { if (size(a) != size(b)) { @@ -221,7 +221,7 @@ constexpr bool range_eq(A &&a, B &&b, Cmp &&cmp = {}) } template -constexpr void map(I &&input, O &&output, Map &&mapper) +constexpr void map(I && input, O && output, Map && mapper) { InputIterator auto input_it = begin(input); OutputIterator auto output_it = begin(output); @@ -235,7 +235,7 @@ constexpr void map(I &&input, O &&output, Map &&mapper) } template -constexpr Init reduce(R &&range, Init &&init, Reduce &&reducer = {}) +constexpr Init reduce(R && range, Init && init, Reduce && reducer = {}) { InputIterator auto it = begin(range); while (it != end(range)) @@ -248,8 +248,8 @@ constexpr Init reduce(R &&range, Init &&init, Reduce &&reducer = {}) } template -constexpr Init map_reduce(R &&range, Init &&init, Map &&mapper, - Reduce &&reducer = {}) +constexpr Init map_reduce(R && range, Init && init, Map && mapper, + Reduce && reducer = {}) { InputIterator auto it = begin(range); while (it != end(range)) @@ -262,7 +262,8 @@ constexpr Init map_reduce(R &&range, Init &&init, Map &&mapper, } template -constexpr void replace(R &&range, E &&target, F &&replacement, Cmp &&cmp = {}) +constexpr void replace(R && range, E && target, F && replacement, + Cmp && cmp = {}) { OutputIterator auto iter = begin(range); while (iter != end(range)) @@ -275,7 +276,7 @@ constexpr void replace(R &&range, E &&target, F &&replacement, Cmp &&cmp = {}) } template -constexpr void replace_if(R &&range, F &&replacement, Test &&test) +constexpr void replace_if(R && range, F && replacement, Test && test) { OutputIterator auto iter = begin(range); while (iter != end(range)) @@ -288,10 +289,10 @@ constexpr void replace_if(R &&range, F &&replacement, Test &&test) } template -constexpr void unique(Span, Cmp &&cmp = {}); // destroy? retain? +constexpr void unique(Span, Cmp && cmp = {}); // destroy? retain? template -constexpr void reverse(R &&range, SwapOp &&swap = {}) +constexpr void reverse(R && range, SwapOp && swap = {}) { if (is_empty(range)) { @@ -310,10 +311,10 @@ constexpr void reverse(R &&range, SwapOp &&swap = {}) } template -constexpr void rotate(Span, SwapOp &&swap = {}); +constexpr void rotate(Span, SwapOp && swap = {}); template -constexpr void split(Span span, Span delimeter, Op op, Cmp &&cmp = {}); +constexpr void split(Span span, Span delimeter, Op op, Cmp && cmp = {}); // first check if src begins with other // keep advancing whilst src begins with other @@ -323,34 +324,34 @@ constexpr void split(Span span, Span delimeter, Op op, Cmp &&cmp = {}); // if equal again, move back // move back until it is no longer equal template -constexpr Span strip(Span src, Span other, Cmp &&cmp = {}); +constexpr Span strip(Span src, Span other, Cmp && cmp = {}); template -constexpr void sort(S &&span, Cmp &&cmp = {}) +constexpr void sort(S && span, Cmp && cmp = {}) { std::sort(begin(span), end(span), cmp); } template -constexpr void indirect_sort(Span indices, Cmp &&cmp = {}) +constexpr void indirect_sort(Span indices, Cmp && cmp = {}) { sort(indices, [&](I a, I b) { return cmp(a, b); }); } template -constexpr void stable_sort(S &&span, Cmp &&cmp = {}) +constexpr void stable_sort(S && span, Cmp && cmp = {}) { std::stable_sort(begin(span), end(span), cmp); } template -constexpr void indirect_stable_sort(Span indices, Cmp &&cmp = {}) +constexpr void indirect_stable_sort(Span indices, Cmp && cmp = {}) { stable_sort(indices, [&](I a, I b) { return cmp(a, b); }); } template -constexpr Tuple partition(R &&range, Predicate &&predicate) +constexpr Tuple partition(R && range, Predicate && predicate) { OutputIterator auto iter = begin(range); OutputIterator auto const first = begin(range); @@ -373,24 +374,27 @@ constexpr Tuple partition(R &&range, Predicate &&predicate) usize const first_size = static_cast(next - first); usize const second_size = static_cast(iter - next); - return Tuple{Slice{0, first_size}, Slice{first_size, second_size}}; + return Tuple{ + Slice{0, first_size }, + Slice{first_size, second_size} + }; } template void iota(Span s, T first) { - for (auto &v : s) + for (auto & v : s) { v = first++; }; } template -constexpr T inclusive_scan(Span input, Span output, T &&init = {}, - Op &&op = {}) +constexpr T inclusive_scan(Span input, Span output, T && init = {}, + Op && op = {}) { - T const *in = input.begin(); - T *out = output.begin(); + T const * in = input.begin(); + T * out = output.begin(); while (in != input.end()) { @@ -404,17 +408,17 @@ constexpr T inclusive_scan(Span input, Span output, T &&init = {}, } template -constexpr T prefix_sum(Span input, Span output, T &&init = {}) +constexpr T prefix_sum(Span input, Span output, T && init = {}) { return inclusive_scan(input, output, (T &&) init, Add{}); } template -constexpr T exclusive_scan(Span input, Span output, - T &&init = {}, Op &&op = {}) +constexpr T exclusive_scan(Span input, Span output, T && init = {}, + Op && op = {}) { - T const *in = input.begin(); - T *out = output.begin(); + T const * in = input.begin(); + T * out = output.begin(); while (in != input.end()) { @@ -428,7 +432,7 @@ constexpr T exclusive_scan(Span input, Span output, } template -constexpr T suffix_sum(Span input, Span output, T &&init = {}) +constexpr T suffix_sum(Span input, Span output, T && init = {}) { return exclusive_scan(input, output, (T &&) init, Add{}); } diff --git a/ashura/std/rc.h b/ashura/std/rc.h index 7b0d5463..c54f218a 100644 --- a/ashura/std/rc.h +++ b/ashura/std/rc.h @@ -26,14 +26,14 @@ struct [[nodiscard]] Rc struct Inner { H handle = {}; - AliasCount *alias_count = nullptr; + AliasCount * alias_count = nullptr; AllocatorImpl allocator = {}; Uninit uninit = noop; }; Inner inner{}; - constexpr Rc(H handle, AliasCount &alias_count, AllocatorImpl allocator, + constexpr Rc(H handle, AliasCount & alias_count, AllocatorImpl allocator, Uninit uninit) : inner{.handle = handle, .alias_count = &alias_count, @@ -46,14 +46,14 @@ struct [[nodiscard]] Rc constexpr Rc(Rc const &) = delete; - constexpr Rc &operator=(Rc const &) = delete; + constexpr Rc & operator=(Rc const &) = delete; - constexpr Rc(Rc &&other) : inner{other.inner} + constexpr Rc(Rc && other) : inner{other.inner} { other.inner = Inner{}; } - constexpr Rc &operator=(Rc &&other) + constexpr Rc & operator=(Rc && other) { if (this == &other) [[unlikely]] { @@ -116,7 +116,7 @@ struct [[nodiscard]] Rc } template - constexpr decltype(auto) operator()(Args &&...args) const + constexpr decltype(auto) operator()(Args &&... args) const { return inner.handle(forward(args)...); } @@ -135,9 +135,9 @@ struct AliasCounted : AliasCount template constexpr Result, Void> rc_inplace(AllocatorImpl allocator, - Args &&...args) + Args &&... args) { - AliasCounted *object; + AliasCounted * object; if (!allocator.nalloc(1, object)) { @@ -148,10 +148,11 @@ constexpr Result, Void> rc_inplace(AllocatorImpl allocator, return Ok{ Rc{&object->data, *object, allocator, - fn(object, [](AliasCounted *object, AllocatorImpl allocator) { + fn(object, [](AliasCounted * object, AllocatorImpl allocator) { object->~AliasCounted(); allocator.ndealloc(object, 1); - })}}; + })} + }; } template @@ -161,7 +162,7 @@ constexpr Result, Void> rc(AllocatorImpl allocator, T object) } template -constexpr Rc transmute(Rc &&base, H handle) +constexpr Rc transmute(Rc && base, H handle) { Rc t{static_cast(handle, base.inner.allocator, base.inner.uninit)}; base.inner.handle = {}; @@ -171,7 +172,7 @@ constexpr Rc transmute(Rc &&base, H handle) } template -constexpr Rc cast(Rc &&from) +constexpr Rc cast(Rc && from) { return transmute((Rc &&) from, static_cast(from.get())); } diff --git a/ashura/std/result.h b/ashura/std/result.h index 3710f284..ae75a1e9 100644 --- a/ashura/std/result.h +++ b/ashura/std/result.h @@ -59,11 +59,12 @@ struct [[nodiscard]] Result } constexpr Result(Err err) : - is_ok_{false}, err_{static_cast(err.value)} + is_ok_{false}, + err_{static_cast(err.value)} { } - constexpr Result(Result &&other) : is_ok_{other.is_ok_} + constexpr Result(Result && other) : is_ok_{other.is_ok_} { if (other.is_ok_) { @@ -75,7 +76,7 @@ struct [[nodiscard]] Result } } - constexpr Result &operator=(Result &&other) + constexpr Result & operator=(Result && other) { if (this == &other) [[unlikely]] { @@ -105,7 +106,7 @@ struct [[nodiscard]] Result return *this; } - constexpr Result &operator=(Ok other) + constexpr Result & operator=(Ok other) { if (is_ok_) { @@ -121,7 +122,7 @@ struct [[nodiscard]] Result return *this; } - constexpr Result &operator=(Err other) + constexpr Result & operator=(Err other) { if (is_ok_) { @@ -137,7 +138,7 @@ struct [[nodiscard]] Result return *this; } - constexpr Result(Result const &other) : is_ok_{other.is_ok_} + constexpr Result(Result const & other) : is_ok_{other.is_ok_} { if (other.is_ok_) { @@ -149,7 +150,7 @@ struct [[nodiscard]] Result } } - constexpr Result &operator=(Result const &other) + constexpr Result & operator=(Result const & other) { if (this == &other) [[unlikely]] { @@ -195,7 +196,7 @@ struct [[nodiscard]] Result } template - [[nodiscard]] constexpr bool contains(U const &cmp) const + [[nodiscard]] constexpr bool contains(U const & cmp) const { if (is_ok_) { @@ -205,7 +206,7 @@ struct [[nodiscard]] Result } template - [[nodiscard]] constexpr bool contains_err(F const &cmp) const + [[nodiscard]] constexpr bool contains_err(F const & cmp) const { if (is_ok_) { @@ -214,26 +215,27 @@ struct [[nodiscard]] Result return err_ == cmp; } - constexpr T &value(SourceLocation loc = SourceLocation::current()) + constexpr T & value(SourceLocation loc = SourceLocation::current()) { CHECK_DESC_SRC(loc, is_ok_, ".value() called on Result with Err = ", err_); return value_; } - constexpr T const &value(SourceLocation loc = SourceLocation::current()) const + constexpr T const & + value(SourceLocation loc = SourceLocation::current()) const { CHECK_DESC_SRC(loc, is_ok_, ".value() called on Result with Err = ", err_); return value_; } - constexpr E &err(SourceLocation loc = SourceLocation::current()) + constexpr E & err(SourceLocation loc = SourceLocation::current()) { CHECK_DESC_SRC(loc, !is_ok_, ".err() called on Result with Value = ", value_); return err_; } - constexpr E const &err(SourceLocation loc = SourceLocation::current()) const + constexpr E const & err(SourceLocation loc = SourceLocation::current()) const { CHECK_DESC_SRC(loc, !is_ok_, ".err() called on Result with Value = ", value_); @@ -259,7 +261,7 @@ struct [[nodiscard]] Result } template - constexpr auto map(Fn &&op) + constexpr auto map(Fn && op) { using U = decltype(static_cast(op)(value_)); if (is_ok_) @@ -270,7 +272,7 @@ struct [[nodiscard]] Result } template - constexpr auto map_or(Fn &&op, U &&alt) + constexpr auto map_or(Fn && op, U && alt) { if (is_ok_) { @@ -280,7 +282,7 @@ struct [[nodiscard]] Result } template - constexpr decltype(auto) map_or_else(Fn &&op, AltFn &&alt_op) + constexpr decltype(auto) map_or_else(Fn && op, AltFn && alt_op) { if (is_ok_) { @@ -290,7 +292,7 @@ struct [[nodiscard]] Result } template - constexpr auto and_then(Fn &&op) + constexpr auto and_then(Fn && op) { using OutResult = decltype(static_cast(op)(value_)); if (is_ok_) @@ -301,7 +303,7 @@ struct [[nodiscard]] Result } template - constexpr auto or_else(Fn &&op) + constexpr auto or_else(Fn && op) { using OutResult = decltype(static_cast(op)(err_)); if (is_ok_) @@ -312,7 +314,7 @@ struct [[nodiscard]] Result } template - constexpr T unwrap_or(U &&alt) + constexpr T unwrap_or(U && alt) { if (is_ok_) { @@ -322,7 +324,7 @@ struct [[nodiscard]] Result } template - constexpr T unwrap_or_else(Fn &&op) + constexpr T unwrap_or_else(Fn && op) { if (is_ok_) { @@ -338,7 +340,7 @@ struct [[nodiscard]] Result return static_cast(value_); } - constexpr T expect(char const *msg, + constexpr T expect(char const * msg, SourceLocation loc = SourceLocation::current()) { CHECK_DESC_SRC(loc, is_ok_, msg, " ", err_); @@ -352,7 +354,7 @@ struct [[nodiscard]] Result return static_cast(err_); } - constexpr E expect_err(char const *msg, + constexpr E expect_err(char const * msg, SourceLocation loc = SourceLocation::current()) { CHECK_DESC_SRC(loc, !is_ok_, msg, " ", value_); @@ -360,7 +362,7 @@ struct [[nodiscard]] Result } template - constexpr decltype(auto) match(OkFn &&ok_fn, ErrFn &&err_fn) + constexpr decltype(auto) match(OkFn && ok_fn, ErrFn && err_fn) { if (is_ok_) { @@ -370,7 +372,7 @@ struct [[nodiscard]] Result } template - constexpr decltype(auto) match(OkFn &&ok_fn, ErrFn &&err_fn) const + constexpr decltype(auto) match(OkFn && ok_fn, ErrFn && err_fn) const { if (is_ok_) { @@ -381,31 +383,31 @@ struct [[nodiscard]] Result }; template -[[nodiscard]] constexpr bool operator==(Ok const &a, Ok const &b) +[[nodiscard]] constexpr bool operator==(Ok const & a, Ok const & b) { return a.value == b.value; } template -[[nodiscard]] constexpr bool operator!=(Ok const &a, Ok const &b) +[[nodiscard]] constexpr bool operator!=(Ok const & a, Ok const & b) { return a.value != b.value; } template -[[nodiscard]] constexpr bool operator==(Err const &a, Err const &b) +[[nodiscard]] constexpr bool operator==(Err const & a, Err const & b) { return a.value == b.value; } template -[[nodiscard]] constexpr bool operator!=(Err const &a, Err const &b) +[[nodiscard]] constexpr bool operator!=(Err const & a, Err const & b) { return a.value != b.value; } template -[[nodiscard]] constexpr bool operator==(Result const &a, Ok const &b) +[[nodiscard]] constexpr bool operator==(Result const & a, Ok const & b) { if (a.is_ok_) { @@ -415,7 +417,7 @@ template } template -[[nodiscard]] constexpr bool operator!=(Result const &a, Ok const &b) +[[nodiscard]] constexpr bool operator!=(Result const & a, Ok const & b) { if (a.is_ok_) { @@ -425,7 +427,7 @@ template } template -[[nodiscard]] constexpr bool operator==(Ok const &a, Result const &b) +[[nodiscard]] constexpr bool operator==(Ok const & a, Result const & b) { if (b.is_ok_) { @@ -435,7 +437,7 @@ template } template -[[nodiscard]] constexpr bool operator!=(Ok const &a, Result const &b) +[[nodiscard]] constexpr bool operator!=(Ok const & a, Result const & b) { if (b.is_ok_) { @@ -445,7 +447,8 @@ template } template -[[nodiscard]] constexpr bool operator==(Result const &a, Err const &b) +[[nodiscard]] constexpr bool operator==(Result const & a, + Err const & b) { if (a.is_err()) { @@ -455,7 +458,8 @@ template } template -[[nodiscard]] constexpr bool operator!=(Result const &a, Err const &b) +[[nodiscard]] constexpr bool operator!=(Result const & a, + Err const & b) { if (a.is_err()) { @@ -465,7 +469,8 @@ template } template -[[nodiscard]] constexpr bool operator==(Err const &a, Result const &b) +[[nodiscard]] constexpr bool operator==(Err const & a, + Result const & b) { if (b.is_err()) { @@ -475,7 +480,8 @@ template } template -[[nodiscard]] constexpr bool operator!=(Err const &a, Result const &b) +[[nodiscard]] constexpr bool operator!=(Err const & a, + Result const & b) { if (b.is_err()) { @@ -485,8 +491,8 @@ template } template -[[nodiscard]] constexpr bool operator==(Result const &a, - Result const &b) +[[nodiscard]] constexpr bool operator==(Result const & a, + Result const & b) { if (a.is_ok_ && b.is_ok_) { @@ -500,8 +506,8 @@ template } template -[[nodiscard]] constexpr bool operator!=(Result const &a, - Result const &b) +[[nodiscard]] constexpr bool operator!=(Result const & a, + Result const & b) { if (a.is_ok_ && b.is_ok_) { diff --git a/ashura/std/simd.h b/ashura/std/simd.h index f34283ae..c2662355 100644 --- a/ashura/std/simd.h +++ b/ashura/std/simd.h @@ -35,4 +35,4 @@ namespace ash /// - choose between runtime and comptime (most pref) dispatch. avoid using a /// separate type for simd elements -} // namespace ash \ No newline at end of file +} // namespace ash diff --git a/ashura/std/sparse_vec.h b/ashura/std/sparse_vec.h index 6d29a5ae..083b0ee0 100644 --- a/ashura/std/sparse_vec.h +++ b/ashura/std/sparse_vec.h @@ -55,9 +55,9 @@ struct SparseVec SparseVec(SparseVec const &) = delete; - SparseVec &operator=(SparseVec const &) = delete; + SparseVec & operator=(SparseVec const &) = delete; - SparseVec(SparseVec &&other) : + SparseVec(SparseVec && other) : index_to_id{std::move(other.index_to_id)}, id_to_index{std::move(other.id_to_index)}, dense{std::move(other.dense)}, @@ -66,7 +66,7 @@ struct SparseVec other.free_id_head = STUB; } - SparseVec &operator=(SparseVec &&other) + SparseVec & operator=(SparseVec && other) { if (this == &other) [[unlikely]] { @@ -91,7 +91,7 @@ struct SparseVec constexpr void clear() { - apply([](auto &...d) { (d.clear(), ...); }, dense); + apply([](auto &... d) { (d.clear(), ...); }, dense); id_to_index.clear(); index_to_id.clear(); free_id_head = STUB; @@ -99,7 +99,7 @@ struct SparseVec constexpr void reset() { - apply([](auto &...d) { (d.reset(), ...); }, dense); + apply([](auto &... d) { (d.reset(), ...); }, dense); id_to_index.reset(); index_to_id.reset(); free_id_head = STUB; @@ -107,7 +107,7 @@ struct SparseVec constexpr void uninit() { - apply([](auto &...d) { (d.uninit(), ...); }, dense); + apply([](auto &... d) { (d.uninit(), ...); }, dense); id_to_index.uninit(); index_to_id.uninit(); } @@ -164,10 +164,10 @@ struct SparseVec if (index != last) { - apply([index, last](auto &...d) { (d.swap(index, last), ...); }, dense); + apply([index, last](auto &... d) { (d.swap(index, last), ...); }, dense); } - apply([](auto &...d) { (d.pop(), ...); }, dense); + apply([](auto &... d) { (d.pop(), ...); }, dense); // adjust id and index mapping if (index != last) @@ -200,7 +200,7 @@ struct SparseVec } bool failed = apply( - [&](auto &...d) { + [&](auto &... d) { return (false || ... || !d.reserve(target_capacity)); }, dense); @@ -222,7 +222,7 @@ struct SparseVec } bool failed = apply( - [target_size](auto &...d) { + [target_size](auto &... d) { return (false || ... || !d.grow(target_size)); }, dense); @@ -260,7 +260,7 @@ struct SparseVec struct Pusher { template - static constexpr void push(Tuple &t, Head &&head, Tail &&...tail) + static constexpr void push(Tuple & t, Head && head, Tail &&... tail) { get(t).push(static_cast(head)).unwrap(); if constexpr (sizeof...(tail) != 0) @@ -271,8 +271,8 @@ struct SparseVec }; template - constexpr Result push(Args &&...args) - requires(sizeof...(Args) == sizeof...(V)) + constexpr Result push(Args &&... args) + requires (sizeof...(Args) == sizeof...(V)) { u64 const index = size(); diff --git a/ashura/std/str.h b/ashura/std/str.h index 7a26e4f8..c428a264 100644 --- a/ashura/std/str.h +++ b/ashura/std/str.h @@ -11,7 +11,7 @@ namespace str template Result<> join(Span const> strings, Span delimiter, - Vec &out) + Vec & out) { if (strings.size() == 0) { diff --git a/ashura/std/text.h b/ashura/std/text.h index 188cb0f7..e5dabbb1 100644 --- a/ashura/std/text.h +++ b/ashura/std/text.h @@ -14,8 +14,8 @@ namespace ash /// utf8-validation [[nodiscard]] constexpr usize count_utf8_codepoints(Span text) { - c8 const *in = text.data(); - usize count = 0; + c8 const * in = text.data(); + usize count = 0; while (in != text.end()) { if ((*in & 0xc0) != 0x80) @@ -32,8 +32,8 @@ namespace ash [[nodiscard]] constexpr usize utf8_decode(Span encoded, Span decoded) { - c8 const *in = encoded.data(); - c32 *out = decoded.data(); + c8 const * in = encoded.data(); + c32 * out = decoded.data(); while (in != encoded.end()) { if ((*in & 0xF8) == 0xF0) @@ -70,8 +70,8 @@ namespace ash [[nodiscard]] constexpr usize utf8_encode(Span decoded, Span encoded) { - c8 *out = encoded.data(); - c32 const *in = decoded.data(); + c8 * out = encoded.data(); + c32 const * in = decoded.data(); while (in != decoded.end()) { @@ -93,7 +93,7 @@ namespace ash out[2] = 0x80 | (*in & 0x3F); out += 3; } - if (*in <= 0x10FFFF) + if (*in <= 0x10'FFFF) { out[0] = 0xF0 | (*in >> 18); out[1] = 0x80 | ((*in >> 12) & 0x3F); @@ -108,7 +108,7 @@ namespace ash /// @brief converts UTF-8 text from @p encoded to UTF-32 and appends into @p /// `decoded` -inline Result<> utf8_decode(Span encoded, Vec &decoded) +inline Result<> utf8_decode(Span encoded, Vec & decoded) { usize const first = decoded.size(); usize const count = count_utf8_codepoints(encoded); @@ -123,7 +123,7 @@ inline Result<> utf8_decode(Span encoded, Vec &decoded) /// @brief converts UTF-32 text from @p decoded to UTF-8 and appends into @p /// `encoded` [[nodiscard]] inline Result<> utf8_encode(Span decoded, - Vec &encoded) + Vec & encoded) { usize const first = encoded.size(); usize const max_count = decoded.size(); @@ -140,12 +140,12 @@ inline Result<> utf8_decode(Span encoded, Vec &decoded) constexpr void replace_invalid_codepoints(Span input, Span output, c32 replacement) { - c32 const *in = input.begin(); - c32 *out = output.begin(); + c32 const * in = input.begin(); + c32 * out = output.begin(); while (in < input.end()) { - if (*in > 0x10FFFF) [[unlikely]] + if (*in > 0x10'FFFF) [[unlikely]] { *out = replacement; } diff --git a/ashura/std/time.h b/ashura/std/time.h index e39133b1..5a9ee894 100644 --- a/ashura/std/time.h +++ b/ashura/std/time.h @@ -21,4 +21,4 @@ using namespace std::chrono_literals; using std::chrono::duration_cast; -} // namespace ash \ No newline at end of file +} // namespace ash diff --git a/ashura/std/traits.h b/ashura/std/traits.h index 3fe9f982..72da76d0 100644 --- a/ashura/std/traits.h +++ b/ashura/std/traits.h @@ -31,7 +31,7 @@ struct RemoveConstVolatile : RemoveConstVolatile }; template -struct RemoveConstVolatile : RemoveConstVolatile +struct RemoveConstVolatile : RemoveConstVolatile { }; @@ -76,7 +76,7 @@ template concept Same = SameImpl::value; template -concept Convertible = requires(From &&from) { +concept Convertible = requires (From && from) { { static_cast(static_cast(from)) }; }; @@ -136,7 +136,7 @@ template concept FloatingPoint = std::is_floating_point_v; template -concept Callable = requires(F &&f, Args &&...args) { +concept Callable = requires (F && f, Args &&... args) { { static_cast(f)(static_cast(args)...) }; }; diff --git a/ashura/std/tuple.gen.h b/ashura/std/tuple.gen.h index 083d0e5c..8f84d499 100644 --- a/ashura/std/tuple.gen.h +++ b/ashura/std/tuple.gen.h @@ -1,4 +1,3 @@ - /// SPDX-License-Identifier: MIT /// Meta-Generated Source Code // clang-format off diff --git a/ashura/std/tuple.h b/ashura/std/tuple.h index 7a6dbb5a..d2fdef82 100644 --- a/ashura/std/tuple.h +++ b/ashura/std/tuple.h @@ -7,7 +7,7 @@ namespace ash { template -constexpr auto &&impl_get(Tuple &&tuple) +constexpr auto && impl_get(Tuple && tuple) { if constexpr (std::is_lvalue_reference_v) { @@ -20,44 +20,45 @@ constexpr auto &&impl_get(Tuple &&tuple) } template - requires(I < sizeof...(T)) -constexpr decltype(auto) get(Tuple const &tuple) +requires (I < sizeof...(T)) +constexpr decltype(auto) get(Tuple const & tuple) { return impl_get(tuple); } template - requires(I < sizeof...(T)) -constexpr decltype(auto) get(Tuple &tuple) +requires (I < sizeof...(T)) +constexpr decltype(auto) get(Tuple & tuple) { return impl_get(tuple); } template - requires(I < sizeof...(T)) -constexpr decltype(auto) get(Tuple const &&tuple) +requires (I < sizeof...(T)) +constexpr decltype(auto) get(Tuple const && tuple) { return impl_get(static_cast const &&>(tuple)); } template - requires(I < sizeof...(T)) -constexpr decltype(auto) get(Tuple &&tuple) +requires (I < sizeof...(T)) +constexpr decltype(auto) get(Tuple && tuple) { return impl_get(static_cast &&>(tuple)); } template -constexpr decltype(auto) impl_apply(F &&f, Tuple &&t, std::index_sequence) +constexpr decltype(auto) impl_apply(F && f, Tuple && t, + std::index_sequence) { return static_cast(f)(get(static_cast(t))...); } template -constexpr decltype(auto) apply(F &&f, Tuple &&t) +constexpr decltype(auto) apply(F && f, Tuple && t) { return impl_apply(static_cast(f), static_cast(t), std::make_index_sequence::SIZE>{}); } -} // namespace ash \ No newline at end of file +} // namespace ash diff --git a/ashura/std/tuple.py b/ashura/std/tuple.py index fc63d565..70a562af 100644 --- a/ashura/std/tuple.py +++ b/ashura/std/tuple.py @@ -9,8 +9,7 @@ def out(code): return file.write(code) -out(f""" -/// SPDX-License-Identifier: MIT +out(f"""/// SPDX-License-Identifier: MIT /// Meta-Generated Source Code // clang-format off #pragma once diff --git a/ashura/std/types.h b/ashura/std/types.h index f0527a82..d10b6d9f 100644 --- a/ashura/std/types.h +++ b/ashura/std/types.h @@ -49,16 +49,16 @@ constexpr i16 I16_MIN = -0x7FFF - 1; constexpr i16 I16_MAX = 0x7FFF; constexpr u32 U32_MIN = 0; -constexpr u32 U32_MAX = 0xFFFFFFFFU; +constexpr u32 U32_MAX = 0xFFFF'FFFFU; -constexpr i32 I32_MIN = -0x7FFFFFFF - 1; -constexpr i32 I32_MAX = 0x7FFFFFFF; +constexpr i32 I32_MIN = -0x7FFF'FFFF - 1; +constexpr i32 I32_MAX = 0x7FFF'FFFF; constexpr u64 U64_MIN = 0; -constexpr u64 U64_MAX = 0xFFFFFFFFFFFFFFFFULL; +constexpr u64 U64_MAX = 0xFFFF'FFFF'FFFF'FFFFULL; -constexpr i64 I64_MIN = -0x7FFFFFFFFFFFFFFFLL - 1; -constexpr i64 I64_MAX = 0x7FFFFFFFFFFFFFFFLL; +constexpr i64 I64_MIN = -0x7FFF'FFFF'FFFF'FFFFLL - 1; +constexpr i64 I64_MAX = 0x7FFF'FFFF'FFFF'FFFFLL; constexpr usize USIZE_MIN = 0; constexpr usize USIZE_MAX = SIZE_MAX; @@ -82,7 +82,7 @@ constexpr f32 PI = 3.14159265358979323846F; struct Add { - constexpr auto operator()(auto const &a, auto const &b) const + constexpr auto operator()(auto const & a, auto const & b) const { return a + b; } @@ -90,7 +90,7 @@ struct Add struct Sub { - constexpr auto operator()(auto const &a, auto const &b) const + constexpr auto operator()(auto const & a, auto const & b) const { return a - b; } @@ -98,7 +98,7 @@ struct Sub struct Mul { - constexpr auto operator()(auto const &a, auto const &b) const + constexpr auto operator()(auto const & a, auto const & b) const { return a * b; } @@ -106,7 +106,7 @@ struct Mul struct Div { - constexpr auto operator()(auto const &a, auto const &b) const + constexpr auto operator()(auto const & a, auto const & b) const { return a / b; } @@ -114,7 +114,7 @@ struct Div struct Eq { - constexpr bool operator()(auto const &a, auto const &b) const + constexpr bool operator()(auto const & a, auto const & b) const { return a == b; } @@ -122,7 +122,7 @@ struct Eq struct NEq { - constexpr bool operator()(auto const &a, auto const &b) const + constexpr bool operator()(auto const & a, auto const & b) const { return a != b; } @@ -130,7 +130,7 @@ struct NEq struct Less { - constexpr bool operator()(auto const &a, auto const &b) const + constexpr bool operator()(auto const & a, auto const & b) const { return a < b; } @@ -138,7 +138,7 @@ struct Less struct LEq { - constexpr bool operator()(auto const &a, auto const &b) const + constexpr bool operator()(auto const & a, auto const & b) const { return a <= b; } @@ -146,7 +146,7 @@ struct LEq struct Gt { - constexpr bool operator()(auto const &a, auto const &b) const + constexpr bool operator()(auto const & a, auto const & b) const { return a > b; } @@ -154,7 +154,7 @@ struct Gt struct GEq { - constexpr bool operator()(auto const &a, auto const &b) const + constexpr bool operator()(auto const & a, auto const & b) const { return a >= b; } @@ -162,7 +162,7 @@ struct GEq struct Cmp { - constexpr int operator()(auto const &a, auto const &b) const + constexpr int operator()(auto const & a, auto const & b) const { if (a == b) { @@ -179,7 +179,7 @@ struct Cmp struct Min { template - constexpr T const &operator()(T const &a, T const &b) const + constexpr T const & operator()(T const & a, T const & b) const { return a < b ? a : b; } @@ -188,7 +188,7 @@ struct Min struct Max { template - constexpr auto const &operator()(T const &a, T const &b) const + constexpr auto const & operator()(T const & a, T const & b) const { return a > b ? a : b; } @@ -197,7 +197,7 @@ struct Max struct Swap { template - constexpr void operator()(T &a, T &b) const + constexpr void operator()(T & a, T & b) const { T a_tmp{static_cast(a)}; a = static_cast(b); @@ -208,8 +208,8 @@ struct Swap struct Clamp { template - constexpr T const &operator()(T const &value, T const &min, - T const &max) const + constexpr T const & operator()(T const & value, T const & min, + T const & max) const { return value < min ? min : (value > max ? max : value); } @@ -283,86 +283,86 @@ constexpr bool get_bit(u64 s, usize i) return (s >> i) & 1; } -constexpr void clear_bit(u8 &s, usize i) +constexpr void clear_bit(u8 & s, usize i) { s &= ~(((u8) 1) << i); } -constexpr void clear_bit(u16 &s, usize i) +constexpr void clear_bit(u16 & s, usize i) { s &= ~(((u16) 1) << i); } -constexpr void clear_bit(u32 &s, usize i) +constexpr void clear_bit(u32 & s, usize i) { s &= ~(((u32) 1) << i); } -constexpr void clear_bit(u64 &s, usize i) +constexpr void clear_bit(u64 & s, usize i) { s &= ~(((u64) 1) << i); } -constexpr void set_bit(u8 &s, usize i) +constexpr void set_bit(u8 & s, usize i) { s |= (((u8) 1) << i); } -constexpr void set_bit(u16 &s, usize i) +constexpr void set_bit(u16 & s, usize i) { s |= (((u16) 1) << i); } -constexpr void set_bit(u32 &s, usize i) +constexpr void set_bit(u32 & s, usize i) { s |= (((u32) 1) << i); } -constexpr void set_bit(u64 &s, usize i) +constexpr void set_bit(u64 & s, usize i) { s |= (((u64) 1) << i); } -constexpr void assign_bit(u8 &s, usize i, bool b) +constexpr void assign_bit(u8 & s, usize i, bool b) { s &= ~(((u8) 1) << i); s |= (((u8) b) << i); } -constexpr void assign_bit(u16 &s, usize i, bool b) +constexpr void assign_bit(u16 & s, usize i, bool b) { s &= ~(((u16) 1) << i); s |= (((u16) b) << i); } -constexpr void assign_bit(u32 &s, usize i, bool b) +constexpr void assign_bit(u32 & s, usize i, bool b) { s &= ~(((u32) 1) << i); s |= (((u32) b) << i); } -constexpr void assign_bit(u64 &s, usize i, bool b) +constexpr void assign_bit(u64 & s, usize i, bool b) { s &= ~(((u64) 1) << i); s |= (((u64) b) << i); } -constexpr void flip_bit(u8 &s, usize i) +constexpr void flip_bit(u8 & s, usize i) { s = s ^ (((usize) 1) << i); } -constexpr void flip_bit(u16 &s, usize i) +constexpr void flip_bit(u16 & s, usize i) { s = s ^ (((usize) 1) << i); } -constexpr void flip_bit(u32 &s, usize i) +constexpr void flip_bit(u32 & s, usize i) { s = s ^ (((usize) 1) << i); } -constexpr void flip_bit(u64 &s, usize i) +constexpr void flip_bit(u64 & s, usize i) { s = s ^ (((usize) 1) << i); } @@ -589,43 +589,43 @@ constexpr E enum_not(E a) return static_cast(enum_uv_not(a)); } -#define ASH_DEFINE_ENUM_BIT_OPS(E) \ - constexpr E operator|(E a, E b) \ - { \ - return ::ash::enum_or(a, b); \ - } \ - \ - constexpr E operator&(E a, E b) \ - { \ - return ::ash::enum_and(a, b); \ - } \ - \ - constexpr E operator^(E a, E b) \ - { \ - return ::ash::enum_xor(a, b); \ - } \ - \ - constexpr E operator~(E a) \ - { \ - return ::ash::enum_not(a); \ - } \ - \ - constexpr E &operator|=(E &a, E b) \ - { \ - a = a | b; \ - return a; \ - } \ - \ - constexpr E &operator&=(E &a, E b) \ - { \ - a = a & b; \ - return a; \ - } \ - \ - constexpr E &operator^=(E &a, E b) \ - { \ - a = a ^ b; \ - return a; \ +#define ASH_DEFINE_ENUM_BIT_OPS(E) \ + constexpr E operator|(E a, E b) \ + { \ + return ::ash::enum_or(a, b); \ + } \ + \ + constexpr E operator&(E a, E b) \ + { \ + return ::ash::enum_and(a, b); \ + } \ + \ + constexpr E operator^(E a, E b) \ + { \ + return ::ash::enum_xor(a, b); \ + } \ + \ + constexpr E operator~(E a) \ + { \ + return ::ash::enum_not(a); \ + } \ + \ + constexpr E & operator|=(E & a, E b) \ + { \ + a = a | b; \ + return a; \ + } \ + \ + constexpr E & operator&=(E & a, E b) \ + { \ + a = a & b; \ + return a; \ + } \ + \ + constexpr E & operator^=(E & a, E b) \ + { \ + a = a ^ b; \ + return a; \ } struct Slice @@ -724,37 +724,37 @@ struct Slice64 }; template -constexpr T *begin(T (&a)[N]) +constexpr T * begin(T (&a)[N]) { return a; } template -constexpr auto begin(T &&a) -> decltype(a.begin()) +constexpr auto begin(T && a) -> decltype(a.begin()) { return a.begin(); } template -constexpr T *end(T (&a)[N]) +constexpr T * end(T (&a)[N]) { return a + N; } template -constexpr auto end(T &&a) -> decltype(a.end()) +constexpr auto end(T && a) -> decltype(a.end()) { return a.end(); } template -constexpr T *data(T (&a)[N]) +constexpr T * data(T (&a)[N]) { return a; } template -constexpr auto data(T &&a) -> decltype(a.data()) +constexpr auto data(T && a) -> decltype(a.data()) { return a.data(); } @@ -766,7 +766,7 @@ constexpr usize size(T (&)[N]) } template -constexpr auto size(T &&a) -> decltype(a.size()) +constexpr auto size(T && a) -> decltype(a.size()) { return a.size(); } @@ -778,7 +778,7 @@ constexpr usize size_bytes(T (&)[N]) } template -constexpr auto size_bytes(T &&a) -> decltype(a.size()) +constexpr auto size_bytes(T && a) -> decltype(a.size()) { return sizeof(T) * a.size(); } @@ -790,19 +790,19 @@ constexpr usize size_bits(T (&)[N]) } template -constexpr auto size_bits(T &&a) -> decltype(a.size()) +constexpr auto size_bits(T && a) -> decltype(a.size()) { return sizeof(T) * 8 * a.size(); } template -constexpr auto is_empty(T &&a) +constexpr auto is_empty(T && a) { return size(a) == 0; } template -concept InputIterator = requires(It it) { +concept InputIterator = requires (It it) { { // deref *it @@ -830,7 +830,7 @@ concept InputIterator = requires(It it) { }; template -concept OutputIterator = InputIterator && requires(It it) { +concept OutputIterator = InputIterator && requires (It it) { { // assign *it = *it @@ -838,13 +838,13 @@ concept OutputIterator = InputIterator && requires(It it) { }; template -concept InputRange = requires(R r) { +concept InputRange = requires (R r) { { begin(r) } -> InputIterator; { end(r) } -> InputIterator; }; template -concept OutputRange = requires(R r) { +concept OutputRange = requires (R r) { { begin(r) } -> OutputIterator; { end(r) } -> OutputIterator; }; @@ -862,12 +862,12 @@ struct Array return false; } - constexpr T *data() + constexpr T * data() { return data_; } - constexpr T const *data() const + constexpr T const * data() const { return data_; } @@ -897,68 +897,68 @@ struct Array return sizeof(T) * SIZE; } - constexpr T *begin() + constexpr T * begin() { return data_; } - constexpr T const *begin() const + constexpr T const * begin() const { return data_; } - constexpr T *end() + constexpr T * end() { return data_ + SIZE; } - constexpr T const *end() const + constexpr T const * end() const { return data_ + SIZE; } - constexpr T &first() + constexpr T & first() { return get(0); } - constexpr T const &first() const + constexpr T const & first() const { return get(0); } - constexpr T &last() + constexpr T & last() { return get(SIZE - 1); } - constexpr T const &last() const + constexpr T const & last() const { return get(SIZE - 1); } - constexpr T &get(usize index) + constexpr T & get(usize index) { return data_[index]; } - constexpr T const &get(usize index) const + constexpr T const & get(usize index) const { return data_[index]; } template - constexpr void set(usize index, Args &&...args) + constexpr void set(usize index, Args &&... args) { data_[index] = T{static_cast(args)...}; } - constexpr T &operator[](usize index) + constexpr T & operator[](usize index) { return data_[index]; } - constexpr T const &operator[](usize index) const + constexpr T const & operator[](usize index) const { return data_[index]; } @@ -994,7 +994,7 @@ using ContainerDataType = std::remove_pointer_t()))>; template -concept SpanContainer = requires(Container c) { +concept SpanContainer = requires (Container c) { { data(c) }; { size(c) }; }; @@ -1009,12 +1009,12 @@ struct Span using Type = T; using Repr = T; - T *data_ = nullptr; + T * data_ = nullptr; usize size_ = 0; constexpr Span() = default; - constexpr Span(T *data, usize size) : data_{data}, size_{size} + constexpr Span(T * data, usize size) : data_{data}, size_{size} { } @@ -1024,8 +1024,9 @@ struct Span } template C> - constexpr Span(C &container) : - data_{ash::data(container)}, size_{ash::size(container)} + constexpr Span(C & container) : + data_{ash::data(container)}, + size_{ash::size(container)} { } @@ -1038,9 +1039,9 @@ struct Span constexpr Span(Span &&) = default; - constexpr Span &operator=(Span const &) = default; + constexpr Span & operator=(Span const &) = default; - constexpr Span &operator=(Span &&) = default; + constexpr Span & operator=(Span &&) = default; constexpr ~Span() = default; @@ -1049,7 +1050,7 @@ struct Span return size_ == 0; } - constexpr T *data() const + constexpr T * data() const { return data_; } @@ -1074,39 +1075,38 @@ struct Span return sizeof(T) * size_; } - constexpr T *begin() const + constexpr T * begin() const { return data_; } - constexpr T *end() const + constexpr T * end() const { return data_ + size_; } - constexpr T &first() const + constexpr T & first() const { return get(0); } - constexpr T &last() const + constexpr T & last() const { return get(size_ - 1); } - constexpr T &operator[](usize index) const + constexpr T & operator[](usize index) const { return data_[index]; } - constexpr T &get(usize index) const + constexpr T & get(usize index) const { return data_[index]; } template - constexpr void set(usize index, Args &&...args) const - requires(NonConst) + constexpr void set(usize index, Args &&... args) const requires (NonConst) { data_[index] = T{static_cast(args)...}; } @@ -1116,26 +1116,22 @@ struct Span return Span{data_, size_}; } - constexpr Span as_u8() const - requires(NonConst) + constexpr Span as_u8() const requires (NonConst) { return Span{reinterpret_cast(data_), size_bytes()}; } - constexpr Span as_u8() const - requires(Const) + constexpr Span as_u8() const requires (Const) { return Span{reinterpret_cast(data_), size_bytes()}; } - constexpr Span as_char() const - requires(NonConst) + constexpr Span as_char() const requires (NonConst) { return Span{reinterpret_cast(data_), size_bytes()}; } - constexpr Span as_char() const - requires(Const) + constexpr Span as_char() const requires (Const) { return Span{reinterpret_cast(data_), size_bytes()}; @@ -1169,7 +1165,7 @@ template Span(T (&)[N]) -> Span; template -Span(C &container) -> Span>; +Span(C & container) -> Span>; template constexpr Span span(std::initializer_list list) @@ -1184,27 +1180,27 @@ constexpr Span span(T (&array)[N]) } template -constexpr auto span(C &c) +constexpr auto span(C & c) { return Span{data(c), size(c)}; } -constexpr Span operator""_str(char const *lit, usize n) +constexpr Span operator""_str(char const * lit, usize n) { return Span{lit, n}; } -constexpr Span operator""_str(c8 const *lit, usize n) +constexpr Span operator""_str(c8 const * lit, usize n) { return Span{lit, n}; } -constexpr Span operator""_str(c16 const *lit, usize n) +constexpr Span operator""_str(c16 const * lit, usize n) { return Span{lit, n}; } -constexpr Span operator""_str(c32 const *lit, usize n) +constexpr Span operator""_str(c32 const * lit, usize n) { return Span{lit, n}; } @@ -1389,7 +1385,8 @@ struct BitSpan constexpr BitSpan() = default; constexpr BitSpan(Span repr, usize bit_size) : - repr_{repr}, bit_size_{bit_size} + repr_{repr}, + bit_size_{bit_size} { } @@ -1397,9 +1394,9 @@ struct BitSpan constexpr BitSpan(BitSpan &&) = default; - constexpr BitSpan &operator=(BitSpan const &) = default; + constexpr BitSpan & operator=(BitSpan const &) = default; - constexpr BitSpan &operator=(BitSpan &&) = default; + constexpr BitSpan & operator=(BitSpan &&) = default; constexpr ~BitSpan() = default; @@ -1494,13 +1491,15 @@ template struct defer { Lambda lambda; - constexpr defer(defer &&) = delete; - constexpr defer(defer const &) = delete; - constexpr defer &operator=(defer &&) = delete; - constexpr defer &operator=(defer const &) = delete; - constexpr defer(Lambda &&l) : lambda{static_cast(l)} + constexpr defer(defer &&) = delete; + constexpr defer(defer const &) = delete; + constexpr defer & operator=(defer &&) = delete; + constexpr defer & operator=(defer const &) = delete; + + constexpr defer(Lambda && l) : lambda{static_cast(l)} { } + constexpr ~defer() { lambda(); @@ -1529,8 +1528,8 @@ struct Fn return thunk(data, static_cast(args)...); } - Thunk thunk = nullptr; - void *data = nullptr; + Thunk thunk = nullptr; + void * data = nullptr; }; template @@ -1539,7 +1538,7 @@ struct PFnThunk; template struct PFnThunk { - static constexpr R thunk(void *data, Args... args) + static constexpr R thunk(void * data, Args... args) { using PFn = R (*)(Args...); @@ -1572,7 +1571,7 @@ struct FunctorThunk; template struct FunctorThunk { - static constexpr R thunk(void *data, Args... args) + static constexpr R thunk(void * data, Args... args) { return (*(reinterpret_cast(data)))(static_cast(args)...); } @@ -1635,7 +1634,7 @@ auto fn(StaticFunctor functor) /// @brief make a function view from a functor reference. Functor should outlive /// the Fn template -auto fn(Functor *functor) +auto fn(Functor * functor) { using Traits = FunctorTraits; using Fn = typename Traits::Fn; @@ -1648,7 +1647,7 @@ auto fn(Functor *functor) /// @brief create a function view from an object reference and a function /// thunk to execute using the object reference as its first argument. template -auto fn(T *t, R (*fn)(T *, Args...)) +auto fn(T * t, R (*fn)(T *, Args...)) { return Fn{reinterpret_cast(fn), const_cast(reinterpret_cast(t))}; @@ -1658,7 +1657,7 @@ auto fn(T *t, R (*fn)(T *, Args...)) /// non-capturing lambda to execute using the object reference as its first /// argument. template -auto fn(T *t, StaticFunctor thunk) +auto fn(T * t, StaticFunctor thunk) { using Traits = FunctorTraits; using PFn = typename Traits::Ptr; @@ -1709,23 +1708,23 @@ struct SourceLocation { static constexpr SourceLocation current( #if ASH_HAS_BUILTIN(FILE) || (defined(__cpp_lib_source_location) && \ - __cpp_lib_source_location >= 201907L) - char const *file = __builtin_FILE(), + __cpp_lib_source_location >= 201'907L) + char const * file = __builtin_FILE(), #elif defined(__FILE__) - char const *file = __FILE__, + char const * file = __FILE__, #else - char const *file = "unknown", + char const * file = "unknown", #endif #if ASH_HAS_BUILTIN(FUNCTION) || (defined(__cpp_lib_source_location) && \ - __cpp_lib_source_location >= 201907L) - char const *function = __builtin_FUNCTION(), + __cpp_lib_source_location >= 201'907L) + char const * function = __builtin_FUNCTION(), #else - char const *function = "unknown", + char const * function = "unknown", #endif #if ASH_HAS_BUILTIN(LINE) || (defined(__cpp_lib_source_location) && \ - __cpp_lib_source_location >= 201907L) + __cpp_lib_source_location >= 201'907L) u32 line = __builtin_LINE(), #elif defined(__LINE__) u32 line = __LINE__, @@ -1734,7 +1733,7 @@ struct SourceLocation #endif #if ASH_HAS_BUILTIN(COLUMN) || (defined(__cpp_lib_source_location) && \ - __cpp_lib_source_location >= 201907L) + __cpp_lib_source_location >= 201'907L) u32 column = __builtin_COLUMN() #else u32 column = 0 @@ -1744,10 +1743,10 @@ struct SourceLocation return SourceLocation{file, function, line, column}; } - char const *file = ""; - char const *function = ""; - u32 line = 0; - u32 column = 0; + char const * file = ""; + char const * function = ""; + u32 line = 0; + u32 column = 0; }; template @@ -1758,14 +1757,15 @@ struct Pin T v; template - constexpr Pin(Args &&...args) : v{static_cast(args)...} + constexpr Pin(Args &&... args) : v{static_cast(args)...} { } - constexpr Pin(Pin const &) = delete; - constexpr Pin(Pin &&) = delete; - constexpr Pin &operator=(Pin const &) = delete; - constexpr Pin &operator=(Pin &&) = delete; - constexpr ~Pin() = default; + + constexpr Pin(Pin const &) = delete; + constexpr Pin(Pin &&) = delete; + constexpr Pin & operator=(Pin const &) = delete; + constexpr Pin & operator=(Pin &&) = delete; + constexpr ~Pin() = default; }; template <> @@ -1773,32 +1773,32 @@ struct Pin { typedef void Type; - constexpr Pin() = default; - constexpr Pin(Pin const &) = delete; - constexpr Pin(Pin &&) = delete; - constexpr Pin &operator=(Pin const &) = delete; - constexpr Pin &operator=(Pin &&) = delete; - constexpr ~Pin() = default; + constexpr Pin() = default; + constexpr Pin(Pin const &) = delete; + constexpr Pin(Pin &&) = delete; + constexpr Pin & operator=(Pin const &) = delete; + constexpr Pin & operator=(Pin &&) = delete; + constexpr ~Pin() = default; }; constexpr u8 sat_add(u8 a, u8 b) { - return (((a + b)) < a) ? U8_MAX : (a + b); + return ((a + b) < a) ? U8_MAX : (a + b); } constexpr u16 sat_add(u16 a, u16 b) { - return (((a + b)) < a) ? U16_MAX : (a + b); + return ((a + b) < a) ? U16_MAX : (a + b); } constexpr u32 sat_add(u32 a, u32 b) { - return (((a + b)) < a) ? U32_MAX : (a + b); + return ((a + b) < a) ? U32_MAX : (a + b); } constexpr u64 sat_add(u64 a, u64 b) { - return (((a + b)) < a) ? U64_MAX : (a + b); + return ((a + b) < a) ? U64_MAX : (a + b); } constexpr i8 sat_add(i8 a, u8 b) diff --git a/ashura/std/v.gen.h b/ashura/std/v.gen.h index 22a0e100..0fcd49bb 100644 --- a/ashura/std/v.gen.h +++ b/ashura/std/v.gen.h @@ -1,4 +1,3 @@ - /// SPDX-License-Identifier: MIT /// Meta-Generated Source Code // clang-format off diff --git a/ashura/std/v.h b/ashura/std/v.h index 2ce44050..76cd4fed 100644 --- a/ashura/std/v.h +++ b/ashura/std/v.h @@ -1,4 +1,3 @@ - /// SPDX-License-Identifier: MIT #pragma once #include "ashura/std/v.gen.h" diff --git a/ashura/std/v.py b/ashura/std/v.py index a0d5f512..c262de72 100644 --- a/ashura/std/v.py +++ b/ashura/std/v.py @@ -9,8 +9,7 @@ def out(code): return file.write(code) -out(f""" -/// SPDX-License-Identifier: MIT +out(f"""/// SPDX-License-Identifier: MIT /// Meta-Generated Source Code // clang-format off #pragma once diff --git a/ashura/std/vec.h b/ashura/std/vec.h index 4025d807..ff3f5ad3 100644 --- a/ashura/std/vec.h +++ b/ashura/std/vec.h @@ -17,13 +17,16 @@ struct [[nodiscard]] Vec using Type = T; using Repr = T; - T *storage_ = nullptr; + T * storage_ = nullptr; usize size_ = 0; usize capacity_ = 0; AllocatorImpl allocator_ = {}; explicit constexpr Vec(AllocatorImpl allocator) : - storage_{nullptr}, size_{0}, capacity_{0}, allocator_{allocator} + storage_{nullptr}, + size_{0}, + capacity_{0}, + allocator_{allocator} { } @@ -31,17 +34,20 @@ struct [[nodiscard]] Vec { } - constexpr Vec(AllocatorImpl allocator, T *storage, usize capacity, + constexpr Vec(AllocatorImpl allocator, T * storage, usize capacity, usize size) : - storage_{storage}, size_{size}, capacity_{capacity}, allocator_{allocator} + storage_{storage}, + size_{size}, + capacity_{capacity}, + allocator_{allocator} { } constexpr Vec(Vec const &) = delete; - constexpr Vec &operator=(Vec const &) = delete; + constexpr Vec & operator=(Vec const &) = delete; - constexpr Vec(Vec &&other) : + constexpr Vec(Vec && other) : storage_{other.storage_}, size_{other.size_}, capacity_{other.capacity_}, @@ -53,7 +59,7 @@ struct [[nodiscard]] Vec other.allocator_ = {}; } - constexpr Vec &operator=(Vec &&other) + constexpr Vec & operator=(Vec && other) { if (this == &other) [[unlikely]] { @@ -74,7 +80,7 @@ struct [[nodiscard]] Vec return size_ == 0; } - constexpr T *data() const + constexpr T * data() const { return storage_; } @@ -104,37 +110,37 @@ struct [[nodiscard]] Vec return capacity_; } - constexpr T *begin() const + constexpr T * begin() const { return data(); } - constexpr T *end() const + constexpr T * end() const { return data() + size_; } - constexpr T &first() const + constexpr T & first() const { return get(0); } - constexpr T &last() const + constexpr T & last() const { return get(size_ - 1); } - constexpr T &operator[](usize index) const + constexpr T & operator[](usize index) const { return get(index); } - constexpr T &get(usize index) const + constexpr T & get(usize index) const { return data()[index]; } - constexpr T *try_get(usize index) const + constexpr T * try_get(usize index) const { if (index < size_) [[unlikely]] { @@ -145,7 +151,7 @@ struct [[nodiscard]] Vec } template - constexpr void set(usize index, Args &&...args) const + constexpr void set(usize index, Args &&... args) const { data()[index] = T{static_cast(args)...}; } @@ -188,7 +194,7 @@ struct [[nodiscard]] Vec } else { - T *new_storage; + T * new_storage; if (!allocator_.nalloc(target_capacity, new_storage)) [[unlikely]] { return Err{}; @@ -219,7 +225,7 @@ struct [[nodiscard]] Vec } else { - T *new_storage; + T * new_storage; if (!allocator_.nalloc(size_, new_storage)) [[unlikely]] { return Err{}; @@ -268,7 +274,7 @@ struct [[nodiscard]] Vec } template - constexpr Result<> push(Args &&...args) + constexpr Result<> push(Args &&... args) { if (!grow(size_ + 1)) [[unlikely]] { @@ -336,7 +342,7 @@ struct [[nodiscard]] Vec } template - constexpr Result<> insert(usize pos, Args &&...args) + constexpr Result<> insert(usize pos, Args &&... args) { pos = min(pos, size_); @@ -493,19 +499,21 @@ struct [[nodiscard]] Vec template constexpr Result> vec(AllocatorImpl allocator, usize capacity) { - T *storage; + T * storage; if (!allocator.nalloc(capacity, storage)) [[unlikely]] { return Err{}; } - return Ok{Vec{allocator, storage, capacity, 0}}; + return Ok{ + Vec{allocator, storage, capacity, 0} + }; } template constexpr Result> vec(AllocatorImpl allocator, T (&&data)[N]) { - T *storage; + T * storage; if (!allocator.nalloc(N, storage)) [[unlikely]] { return Err{}; @@ -513,13 +521,15 @@ constexpr Result> vec(AllocatorImpl allocator, T (&&data)[N]) obj::relocate_non_overlapping(data, storage); - return Ok{Vec{allocator, storage, N, N}}; + return Ok{ + Vec{allocator, storage, N, N} + }; } template constexpr Result> vec(AllocatorImpl allocator, Span data) { - T *storage; + T * storage; if (!allocator.nalloc(data.size(), storage)) [[unlikely]] { return Err{}; @@ -527,7 +537,9 @@ constexpr Result> vec(AllocatorImpl allocator, Span data) obj::copy_construct(data, storage); - return Ok{Vec{allocator, storage, data.size(), data.size()}}; + return Ok{ + Vec{allocator, storage, data.size(), data.size()} + }; } /// @brief A vector with elements pinned to memory, The address of the vector is @@ -538,27 +550,33 @@ constexpr Result> vec(AllocatorImpl allocator, Span data) template struct [[nodiscard]] PinVec { - T *storage_; + T * storage_; usize size_; usize capacity_; AllocatorImpl allocator_; constexpr PinVec() : - storage_{nullptr}, size_{0}, capacity_{0}, allocator_{default_allocator} + storage_{nullptr}, + size_{0}, + capacity_{0}, + allocator_{default_allocator} { } - constexpr PinVec(AllocatorImpl allocator, T *storage, usize capacity, + constexpr PinVec(AllocatorImpl allocator, T * storage, usize capacity, usize size) : - storage_{storage}, size_{size}, capacity_{capacity}, allocator_{allocator} + storage_{storage}, + size_{size}, + capacity_{capacity}, + allocator_{allocator} { } constexpr PinVec(PinVec const &) = delete; - constexpr PinVec &operator=(PinVec const &) = delete; + constexpr PinVec & operator=(PinVec const &) = delete; - constexpr PinVec(PinVec &&other) : + constexpr PinVec(PinVec && other) : storage_{other.storage_}, size_{other.size_}, capacity_{other.capacity_}, @@ -570,7 +588,7 @@ struct [[nodiscard]] PinVec other.allocator_ = default_allocator; } - constexpr PinVec &operator=(PinVec &&other) + constexpr PinVec & operator=(PinVec && other) { if (this == &other) [[unlikely]] { @@ -608,7 +626,7 @@ struct [[nodiscard]] PinVec return size_ == 0; } - constexpr T *data() const + constexpr T * data() const { return storage_; } @@ -638,32 +656,32 @@ struct [[nodiscard]] PinVec return capacity_; } - constexpr T *begin() const + constexpr T * begin() const { return data(); } - constexpr T *end() const + constexpr T * end() const { return data() + size_; } - constexpr T &first() const + constexpr T & first() const { return get(0); } - constexpr T &last() const + constexpr T & last() const { return get(size_ - 1); } - constexpr T &operator[](usize index) const + constexpr T & operator[](usize index) const { return get(index); } - constexpr T &get(usize index) const + constexpr T & get(usize index) const { return data()[index]; } @@ -694,7 +712,7 @@ struct [[nodiscard]] PinVec } template - constexpr Result<> push(Args &&...args) + constexpr Result<> push(Args &&... args) { if ((size_ + 1) > capacity_) [[unlikely]] { @@ -712,13 +730,15 @@ struct [[nodiscard]] PinVec template constexpr Result> pin_vec(AllocatorImpl allocator, usize capacity) { - T *storage; + T * storage; if (!allocator.nalloc(capacity, storage)) [[unlikely]] { return Err{}; } - return Ok{PinVec{allocator, storage, capacity, 0}}; + return Ok{ + PinVec{allocator, storage, capacity, 0} + }; } template @@ -740,15 +760,16 @@ struct [[nodiscard]] BitVec constexpr BitVec(BitVec const &) = delete; - constexpr BitVec &operator=(BitVec const &) = delete; + constexpr BitVec & operator=(BitVec const &) = delete; - constexpr BitVec(BitVec &&other) : - repr_{static_cast &&>(other.repr_)}, bit_size_{other.bit_size_} + constexpr BitVec(BitVec && other) : + repr_{static_cast &&>(other.repr_)}, + bit_size_{other.bit_size_} { other.bit_size_ = 0; } - constexpr BitVec &operator=(BitVec &&other) + constexpr BitVec & operator=(BitVec && other) { if (this == &other) [[unlikely]] { @@ -761,12 +782,12 @@ struct [[nodiscard]] BitVec constexpr ~BitVec() = default; - constexpr Vec const &repr() const + constexpr Vec const & repr() const { return repr_; } - constexpr Vec &repr() + constexpr Vec & repr() { return repr_; } @@ -993,25 +1014,25 @@ struct [[nodiscard]] BitVec }; template -constexpr auto bit_span(BitVec &container) -> BitSpan +constexpr auto bit_span(BitVec & container) -> BitSpan { return BitSpan{container.data(), container.size()}; } template -constexpr auto bit_span(BitVec const &container) -> BitSpan +constexpr auto bit_span(BitVec const & container) -> BitSpan { return BitSpan{container.data(), container.size()}; } template -constexpr auto span(BitVec &container) -> BitSpan +constexpr auto span(BitVec & container) -> BitSpan { return BitSpan{container.data(), container.size()}; } template -constexpr auto span(BitVec const &container) -> BitSpan +constexpr auto span(BitVec const & container) -> BitSpan { return BitSpan{container.data(), container.size()}; } @@ -1030,12 +1051,12 @@ struct [[nodiscard]] InplaceVec constexpr InplaceVec() = default; - constexpr InplaceVec(InplaceVec const &other) : size_{other.size_} + constexpr InplaceVec(InplaceVec const & other) : size_{other.size_} { copy_construct(Span{other.data(), other.size_}, data()); } - constexpr InplaceVec &operator=(InplaceVec const &other) + constexpr InplaceVec & operator=(InplaceVec const & other) { if (this == &other) [[unlikely]] { @@ -1046,13 +1067,13 @@ struct [[nodiscard]] InplaceVec return *this; } - constexpr InplaceVec(InplaceVec &&other) : size_{other.size_} + constexpr InplaceVec(InplaceVec && other) : size_{other.size_} { obj::relocate_non_overlapping(Span{other.data(), other.size_}, data()); other.size_ = 0; } - constexpr InplaceVec &operator=(InplaceVec &&other) + constexpr InplaceVec & operator=(InplaceVec && other) { if (this == &other) [[unlikely]] { @@ -1073,12 +1094,12 @@ struct [[nodiscard]] InplaceVec return size_ == 0; } - constexpr T *data() + constexpr T * data() { return reinterpret_cast(storage_); } - constexpr T const *data() const + constexpr T const * data() const { return reinterpret_cast(storage_); } @@ -1108,67 +1129,67 @@ struct [[nodiscard]] InplaceVec return Capacity; } - constexpr T *begin() + constexpr T * begin() { return data(); } - constexpr T const *begin() const + constexpr T const * begin() const { return data(); } - constexpr T *end() + constexpr T * end() { return data() + size_; } - constexpr T const *end() const + constexpr T const * end() const { return data() + size_; } - constexpr T &first() + constexpr T & first() { return get(0); } - constexpr T const &first() const + constexpr T const & first() const { return get(0); } - constexpr T &last() + constexpr T & last() { return get(size_ - 1); } - constexpr T const &last() const + constexpr T const & last() const { return get(size_ - 1); } - constexpr T &operator[](usize index) + constexpr T & operator[](usize index) { return get(index); } - constexpr T const &operator[](usize index) const + constexpr T const & operator[](usize index) const { return get(index); } - constexpr T &get(usize index) + constexpr T & get(usize index) { return data()[index]; } - constexpr T const &get(usize index) const + constexpr T const & get(usize index) const { return data()[index]; } - constexpr T *try_get(usize index) + constexpr T * try_get(usize index) { if (index >= size_) [[unlikely]] { @@ -1178,7 +1199,7 @@ struct [[nodiscard]] InplaceVec return data() + index; } - constexpr T const *try_get(usize index) const + constexpr T const * try_get(usize index) const { if (index >= size_) [[unlikely]] { @@ -1189,7 +1210,7 @@ struct [[nodiscard]] InplaceVec } template - constexpr void set(usize index, Args &&...args) + constexpr void set(usize index, Args &&... args) { data()[index] = T{static_cast(args)...}; } @@ -1237,7 +1258,7 @@ struct [[nodiscard]] InplaceVec } template - constexpr Result<> push(Args &&...args) + constexpr Result<> push(Args &&... args) { if ((size_ + 1) > Capacity) [[unlikely]] { @@ -1306,7 +1327,7 @@ struct [[nodiscard]] InplaceVec } template - constexpr Result<> insert(usize pos, Args &&...args) + constexpr Result<> insert(usize pos, Args &&... args) { pos = min(pos, size_); @@ -1487,7 +1508,7 @@ struct IsTriviallyRelocatable> namespace fmt { -inline bool push(Context const &ctx, Spec const &spec, Vec str) +inline bool push(Context const & ctx, Spec const & spec, Vec str) { return push(ctx, spec, span(str)); }