From 8fda30e5a2c1bcb528628a65cebbf73b02a97c23 Mon Sep 17 00:00:00 2001 From: Erin Catto Date: Thu, 24 Sep 2026 13:43:40 -0700 Subject: [PATCH] Update UI (#169) Port Box2D UI update --- samples/main.cpp | 4 + samples/sample.cpp | 1004 ++++++++++++++++++++----------------- samples/sample.h | 29 +- samples/sample_replay.cpp | 18 +- 4 files changed, 594 insertions(+), 461 deletions(-) diff --git a/samples/main.cpp b/samples/main.cpp index d5b32d3..5e0fda5 100644 --- a/samples/main.cpp +++ b/samples/main.cpp @@ -236,6 +236,10 @@ static void OnEvent( const sapp_event* e ) s_context.showMetrics = !s_context.showMetrics; break; + case SAPP_KEYCODE_I: + s_context.showProfile = !s_context.showProfile; + break; + case SAPP_KEYCODE_R: SelectSample( &s_context, s_context.sampleIndex, true ); break; diff --git a/samples/sample.cpp b/samples/sample.cpp index 8ddd8f7..4f6e21b 100644 --- a/samples/sample.cpp +++ b/samples/sample.cpp @@ -121,6 +121,8 @@ void SampleContext::Save() fprintf( file, " \"drawDistance\": %g,\n", drawDistance ); fprintf( file, " \"showHullEdges\": %s,\n", GetEdgeOverlayParams().showHulls ? "true" : "false" ); fprintf( file, " \"showEdgeConvexity\": %s,\n", GetEdgeOverlayParams().showEdgeConvexity ? "true" : "false" ); + fprintf( file, " \"showMetrics\": %s,\n", showMetrics ? "true" : "false" ); + fprintf( file, " \"showProfile\": %s,\n", showProfile ? "true" : "false" ); fprintf( file, " \"replayKeyframeBudgetMB\": %d,\n", replayKeyframeBudgetMB ); fprintf( file, " \"replayKeyframeMinInterval\": %d\n", replayKeyframeMinInterval ); fprintf( file, "}\n" ); @@ -267,6 +269,16 @@ void SampleContext::Load() p.showEdgeConvexity = strncmp( s, "true", 4 ) == 0; SetEdgeOverlayParams( &p ); } + else if ( jsoneq( data, &tokens[i], "showMetrics" ) == 0 ) + { + const char* s = data + tokens[i + 1].start; + showMetrics = strncmp( s, "true", 4 ) == 0; + } + else if ( jsoneq( data, &tokens[i], "showProfile" ) == 0 ) + { + const char* s = data + tokens[i + 1].start; + showProfile = strncmp( s, "true", 4 ) == 0; + } else if ( jsoneq( data, &tokens[i], "replayKeyframeBudgetMB" ) == 0 ) { replayKeyframeBudgetMB = b3ClampInt( ParseInt( data, tokens[i + 1] ), 64, 4096 ); @@ -301,6 +313,7 @@ Sample::Sample( SampleContext* context ) m_mouseFraction = 0.0f; m_mouseForceScale = 100.0f; + m_textX = 5; m_textLine = 0; m_textIncrement = 22; m_stepCount = 0; @@ -362,7 +375,11 @@ void Sample::FinishRecording() b3World_StopRecording( m_worldId ); // The buffer is freed either way, so a failed write has to be said out loud - if ( b3SaveRecordingToFile( m_recording, m_context->recordingFile ) == false ) + if ( b3SaveRecordingToFile( m_recording, m_context->recordingFile ) ) + { + snprintf( m_context->savedRecordingFile, sizeof( m_context->savedRecordingFile ), "%s", m_context->recordingFile ); + } + else { fprintf( stderr, "Failed to write recording '%s'\n", m_context->recordingFile ); } @@ -409,6 +426,12 @@ void Sample::ResetText() { m_textLine = (int)( 3.0f * fontSize ); } + + m_textX = 5; + if ( IsProfileVisible() ) + { + m_textX += (int)( GetProfilePanelWidth() + 0.5f * fontSize ); + } } void Sample::Step() @@ -571,6 +594,8 @@ void FrameSelection( SampleContext* context ) void Sample::ResetProfile() { + // Keeps the elapsed recording length intact across a profile reset + m_recordStartStep -= m_stepCount; m_stepCount = 0; memset( m_profiles, 0, sizeof( m_profiles ) ); m_currentProfileIndex = 0; @@ -614,9 +639,314 @@ float AddSegment( ImDrawList* dl, float availWidth, float t, float stepNow, ImU3 return x; } -// Bottom diagnostics drawer (M). Tabs: Profile, Counters, Renderer, and the -// optional ImPlot frame-time chart. Anchored along the window bottom, clear -// of the right info panel. +#define PROFILE_SECTION_WIDTH 8.0f +#define PROFILE_INDENT_WIDTH 0.75f +#define PROFILE_VALUE_WIDTH 3.0f +#define PROFILE_BAR_WIDTH 4.0f +#define PROFILE_COLUMN_COUNT 5 + +// Shared by the profile panel and the frame time plot so the two views read alike +static const ImU32 s_colorStep = IM_COL32( 230, 230, 230, 255 ); +static const ImU32 s_colorPairs = IM_COL32( 102, 153, 255, 255 ); +static const ImU32 s_colorCollide = IM_COL32( 255, 140, 51, 255 ); +static const ImU32 s_colorSolve = IM_COL32( 102, 204, 102, 255 ); +static const ImU32 s_colorSolveChild = IM_COL32( 150, 190, 150, 255 ); +static const ImU32 s_colorConstraintChild = IM_COL32( 110, 200, 190, 255 ); +static const ImU32 s_colorSensors = IM_COL32( 200, 120, 220, 255 ); +static const ImU32 s_colorOther = IM_COL32( 140, 140, 140, 255 ); + +// Well apart from both row background shades so the track reads the same on every row +static const ImU32 s_colorTrack = IM_COL32( 70, 70, 74, 255 ); + +bool Sample::IsProfileVisible() const +{ + return m_context->showUI && m_context->showProfile && HasProfile(); +} + +float Sample::GetProfilePanelWidth() const +{ + if ( IsProfileVisible() == false ) + { + return 0.0f; + } + + const ImGuiStyle& style = ImGui::GetStyle(); + float fontSize = ImGui::GetFontSize(); + float width = PROFILE_SECTION_WIDTH + 3.0f * PROFILE_VALUE_WIDTH + PROFILE_BAR_WIDTH; + return width * fontSize + 2.0f * PROFILE_COLUMN_COUNT * style.CellPadding.x + 2.0f * style.WindowPadding.x; +} + +// Left profile panel (I). Full height under the menu bar, clear of the right info panel. +void Sample::DrawProfile() +{ + if ( IsProfileVisible() == false ) + { + return; + } + + float fontSize = ImGui::GetFontSize(); + float menuBarHeight = ImGui::GetFrameHeight(); + float panelWidth = GetProfilePanelWidth(); + + ImGui::SetNextWindowPos( { 0.5f * fontSize, menuBarHeight + 0.5f * fontSize } ); + ImGui::SetNextWindowSize( { panelWidth, m_camera->m_height - menuBarHeight - fontSize } ); + + ImGui::Begin( "Profile", nullptr, + ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | + ImGuiWindowFlags_NoTitleBar ); + + int count = m_profileWriteIndex - m_profileReadIndex; + + // Unroll ring buffer into per-field histories. + constexpr int kRowCount = 22; + float histories[kRowCount][m_profileCapacity]; + float totals[kRowCount] = {}; + for ( int i = 0; i < count; ++i ) + { + int idx = ( m_profileReadIndex + i ) & ( m_profileCapacity - 1 ); + const b3Profile& p = m_profiles[idx]; + histories[0][i] = p.step; + histories[1][i] = p.pairs; + histories[2][i] = p.collide; + histories[3][i] = p.solve; + histories[4][i] = p.solverSetup; + histories[5][i] = p.constraints; + histories[6][i] = p.prepareConstraints; + histories[7][i] = p.integrateVelocities; + histories[8][i] = p.warmStart; + histories[9][i] = p.solveImpulses; + histories[10][i] = p.integratePositions; + histories[11][i] = p.relaxImpulses; + histories[12][i] = p.restitution; + histories[13][i] = p.storeImpulses; + histories[14][i] = p.splitIslands; + histories[15][i] = p.transforms; + histories[16][i] = p.jointEvents; + histories[17][i] = p.hitEvents; + histories[18][i] = p.refit; + histories[19][i] = p.sleepIslands; + histories[20][i] = p.bullets; + histories[21][i] = p.sensors; + for ( int j = 0; j < kRowCount; ++j ) + { + totals[j] += histories[j][i]; + } + } + + // Smoothed over the last few frames so bars don't jitter visibly. + constexpr int kNowWindow = 10; + float now[kRowCount] = {}; + { + int n = count < kNowWindow ? count : kNowWindow; + if ( n > 0 ) + { + float inv = 1.0f / n; + for ( int r = 0; r < kRowCount; ++r ) + { + float sum = 0.0f; + for ( int i = count - n; i < count; ++i ) + { + sum += histories[r][i]; + } + now[r] = sum * inv; + } + } + } + + float avg[kRowCount] = {}; + if ( count > 0 ) + { + float scale = 1.0f / count; + for ( int i = 0; i < kRowCount; ++i ) + { + avg[i] = scale * totals[i]; + } + } + + float rowMax[kRowCount] = {}; + for ( int r = 0; r < kRowCount; ++r ) + { + for ( int i = 0; i < count; ++i ) + { + if ( histories[r][i] > rowMax[r] ) + { + rowMax[r] = histories[r][i]; + } + } + } + + const RowDef rows[kRowCount] = { + { "step", 0, s_colorStep }, + { "pairs", 0, s_colorPairs }, + { "collide", 0, s_colorCollide }, + { "solve", 0, s_colorSolve }, + { "setup", 1, s_colorSolveChild }, + { "constraints", 1, s_colorSolveChild }, + { "prepare", 2, s_colorConstraintChild }, + { "velocities", 2, s_colorConstraintChild }, + { "warm start", 2, s_colorConstraintChild }, + { "bias", 2, s_colorConstraintChild }, + { "positions", 2, s_colorConstraintChild }, + { "relax", 2, s_colorConstraintChild }, + { "restitution", 2, s_colorConstraintChild }, + { "store", 2, s_colorConstraintChild }, + { "split", 2, s_colorConstraintChild }, + { "transforms", 1, s_colorSolveChild }, + { "joint events", 1, s_colorSolveChild }, + { "hit events", 1, s_colorSolveChild }, + { "refit BVH", 1, s_colorSolveChild }, + { "sleep", 1, s_colorSolveChild }, + { "bullets", 1, s_colorSolveChild }, + { "sensors", 0, s_colorSensors }, + }; + + float stepNow = b3MaxFloat( now[0], 0.001f ); + + if ( ImGui::Button( "Reset" ) ) + { + ResetProfile(); + } + ImGui::SameLine(); + ImGui::Text( " step %.2f ms", now[0] ); + + // Flame strip: step subdivided by top-level children. + { + float pairsT = now[1]; + float collideT = now[2]; + float solveT = now[3]; + float sensorsT = now[21]; + float otherT = b3MaxFloat( stepNow - pairsT - collideT - solveT - sensorsT, 0.0f ); + + float availWidth = ImGui::GetContentRegionAvail().x; + float barHeight = 1.5f * fontSize; + ImDrawList* dl = ImGui::GetWindowDrawList(); + ImVec2 cursor = ImGui::GetCursorScreenPos(); + float x = cursor.x; + + x = AddSegment( dl, availWidth, pairsT, stepNow, s_colorPairs, x, cursor, barHeight ); + x = AddSegment( dl, availWidth, collideT, stepNow, s_colorCollide, x, cursor, barHeight ); + x = AddSegment( dl, availWidth, solveT, stepNow, s_colorSolve, x, cursor, barHeight ); + x = AddSegment( dl, availWidth, sensorsT, stepNow, s_colorSensors, x, cursor, barHeight ); + x = AddSegment( dl, availWidth, otherT, stepNow, s_colorOther, x, cursor, barHeight ); + + ImGui::Dummy( ImVec2( availWidth, barHeight ) ); + } + + const ImGuiTableFlags tableFlags = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit; + + if ( ImGui::BeginTable( "profile", PROFILE_COLUMN_COUNT, tableFlags ) ) + { + ImGui::TableSetupColumn( "section", ImGuiTableColumnFlags_WidthFixed, PROFILE_SECTION_WIDTH * fontSize ); + ImGui::TableSetupColumn( "now", ImGuiTableColumnFlags_WidthFixed, PROFILE_VALUE_WIDTH * fontSize ); + ImGui::TableSetupColumn( "avg", ImGuiTableColumnFlags_WidthFixed, PROFILE_VALUE_WIDTH * fontSize ); + ImGui::TableSetupColumn( "max", ImGuiTableColumnFlags_WidthFixed, PROFILE_VALUE_WIDTH * fontSize ); + ImGui::TableSetupColumn( "%", ImGuiTableColumnFlags_WidthFixed, PROFILE_BAR_WIDTH * fontSize ); + ImGui::TableHeadersRow(); + + for ( int r = 0; r < kRowCount; ++r ) + { + const RowDef& d = rows[r]; + + ImGui::TableNextRow(); + + ImGui::TableNextColumn(); + float indent = d.indent * PROFILE_INDENT_WIDTH * fontSize; + ImGui::SetCursorPosX( ImGui::GetCursorPosX() + indent ); + ImGui::PushStyleColor( ImGuiCol_Text, d.color ); + ImGui::TextUnformatted( d.name ); + ImGui::PopStyleColor(); + + // Dim rows that would print as zero so the costly sections stand out + bool idle = avg[r] < 0.005f; + if ( idle ) + { + ImGui::PushStyleColor( ImGuiCol_Text, ImGui::GetStyleColorVec4( ImGuiCol_TextDisabled ) ); + } + ImGui::TableNextColumn(); + ImGui::Text( "%6.2f", now[r] ); + ImGui::TableNextColumn(); + ImGui::Text( "%6.2f", avg[r] ); + ImGui::TableNextColumn(); + ImGui::Text( "%6.2f", rowMax[r] ); + if ( idle ) + { + ImGui::PopStyleColor(); + } + + ImGui::TableNextColumn(); + + // The step itself is measured against the frame budget to show headroom + bool isBudget = r == 0 && m_context->hertz > 0.0f; + float reference = isBudget ? 1000.0f / m_context->hertz : stepNow; + float frac = b3ClampFloat( now[r] / reference, 0.0f, 1.0f ); + + // Text line height instead of a framed progress bar keeps the rows tight + float barWidth = ImGui::GetContentRegionAvail().x; + float barHeight = ImGui::GetTextLineHeight(); + ImVec2 p = ImGui::GetCursorScreenPos(); + ImDrawList* drawList = ImGui::GetWindowDrawList(); + drawList->AddRectFilled( p, ImVec2( p.x + barWidth, p.y + barHeight ), s_colorTrack ); + drawList->AddRectFilled( p, ImVec2( p.x + frac * barWidth, p.y + barHeight ), d.color ); + ImGui::Dummy( ImVec2( barWidth, barHeight ) ); + if ( isBudget ) + { + ImGui::SetItemTooltip( "%.0f%% of %.1f ms frame", 100.0f * now[r] / reference, reference ); + } + else + { + ImGui::SetItemTooltip( "%.0f%% of step", 100.0f * now[r] / reference ); + } + } + ImGui::EndTable(); + } + + ImGui::End(); +} + +// Vertical bars scaled to a shared maximum, one per value. Stands in for a table that would not +// fit the drawer, so the caller reports each bar's count from the returned hover index. +static int DrawBarChart( const char* id, const int* values, const ImU32* colors, int count, int scaleMax, ImVec2 size ) +{ + ImVec2 origin = ImGui::GetCursorScreenPos(); + ImGui::InvisibleButton( id, size ); + bool hovered = ImGui::IsItemHovered(); + float mouseX = ImGui::GetIO().MousePos.x; + + ImDrawList* drawList = ImGui::GetWindowDrawList(); + float slot = size.x / count; + float gap = b3MinFloat( 2.0f, 0.25f * slot ); + float invMax = scaleMax > 0 ? 1.0f / scaleMax : 0.0f; + float bottom = origin.y + size.y; + + int hoveredIndex = -1; + for ( int i = 0; i < count; ++i ) + { + float x0 = origin.x + i * slot; + float x1 = x0 + slot - gap; + + // Empty slots still show, so a gap in the sequence reads as a gap + drawList->AddRectFilled( ImVec2( x0, origin.y ), ImVec2( x1, bottom ), s_colorTrack ); + + float height = b3ClampFloat( values[i] * invMax, 0.0f, 1.0f ) * size.y; + if ( values[i] > 0 ) + { + // A tiny count keeps a visible sliver + height = b3MaxFloat( height, 1.0f ); + drawList->AddRectFilled( ImVec2( x0, bottom - height ), ImVec2( x1, bottom ), colors[i] ); + } + + if ( hovered && x0 <= mouseX && mouseX < x0 + slot ) + { + hoveredIndex = i; + drawList->AddRect( ImVec2( x0, origin.y ), ImVec2( x1, bottom ), IM_COL32( 255, 255, 255, 200 ) ); + } + } + + return hoveredIndex; +} + +// Bottom metrics drawer (M). Tabs: the ImPlot frame time chart, Counters, and Renderer. +// Anchored along the window bottom, between the profile panel and the right info panel. void Sample::DrawMetrics() { if ( m_context->showMetrics == false ) @@ -627,9 +957,14 @@ void Sample::DrawMetrics() float fontSize = ImGui::GetFontSize(); float menuWidth = InfoPanelWidthEm() * fontSize; float drawerHeight = 16.0f * fontSize; - float drawerWidth = m_camera->m_width - menuWidth - 1.5f * fontSize; + float drawerX = 0.5f * fontSize; + if ( IsProfileVisible() ) + { + drawerX += GetProfilePanelWidth() + 0.5f * fontSize; + } + float drawerWidth = m_camera->m_width - menuWidth - fontSize - drawerX; - ImGui::SetNextWindowPos( { 0.5f * fontSize, m_camera->m_height - drawerHeight - 0.5f * fontSize } ); + ImGui::SetNextWindowPos( { drawerX, m_camera->m_height - drawerHeight - 0.5f * fontSize } ); ImGui::SetNextWindowSize( { drawerWidth, drawerHeight } ); ImGui::Begin( "Metrics", nullptr, @@ -642,445 +977,179 @@ void Sample::DrawMetrics() return; } - if ( ImGui::BeginTabItem( "Profile" ) ) + if ( HasProfile() && ImGui::BeginTabItem( "Frame Time" ) ) { + float maxValue = 0.0f; + float times[m_profileCapacity]; + float stepTimes[m_profileCapacity]; + float pairsTimes[m_profileCapacity]; + float collideTimes[m_profileCapacity]; + float solveTimes[m_profileCapacity]; + float sensorsTimes[m_profileCapacity]; int count = m_profileWriteIndex - m_profileReadIndex; - - // Unroll ring buffer into per-field histories. - constexpr int kRowCount = 22; - float histories[kRowCount][m_profileCapacity]; - float totals[kRowCount] = {}; for ( int i = 0; i < count; ++i ) { - int idx = ( m_profileReadIndex + i ) & ( m_profileCapacity - 1 ); - const b3Profile& p = m_profiles[idx]; - histories[0][i] = p.step; - histories[1][i] = p.pairs; - histories[2][i] = p.collide; - histories[3][i] = p.solve; - histories[4][i] = p.solverSetup; - histories[5][i] = p.constraints; - histories[6][i] = p.prepareConstraints; - histories[7][i] = p.integrateVelocities; - histories[8][i] = p.warmStart; - histories[9][i] = p.solveImpulses; - histories[10][i] = p.integratePositions; - histories[11][i] = p.relaxImpulses; - histories[12][i] = p.restitution; - histories[13][i] = p.storeImpulses; - histories[14][i] = p.splitIslands; - histories[15][i] = p.transforms; - histories[16][i] = p.jointEvents; - histories[17][i] = p.hitEvents; - histories[18][i] = p.refit; - histories[19][i] = p.sleepIslands; - histories[20][i] = p.bullets; - histories[21][i] = p.sensors; - - totals[0] += p.step; - totals[1] += p.pairs; - totals[2] += p.collide; - totals[3] += p.solve; - totals[4] += p.solverSetup; - totals[5] += p.constraints; - totals[6] += p.prepareConstraints; - totals[7] += p.integrateVelocities; - totals[8] += p.warmStart; - totals[9] += p.solveImpulses; - totals[10] += p.integratePositions; - totals[11] += p.relaxImpulses; - totals[12] += p.restitution; - totals[13] += p.storeImpulses; - totals[14] += p.splitIslands; - totals[15] += p.transforms; - totals[16] += p.jointEvents; - totals[17] += p.hitEvents; - totals[18] += p.refit; - totals[19] += p.sleepIslands; - totals[20] += p.bullets; - totals[21] += p.sensors; + int index = ( m_profileReadIndex + i ) & ( m_profileCapacity - 1 ); + times[i] = i / 60.0f; + stepTimes[i] = m_profiles[index].step; + pairsTimes[i] = m_profiles[index].pairs; + collideTimes[i] = m_profiles[index].collide; + solveTimes[i] = m_profiles[index].solve; + sensorsTimes[i] = m_profiles[index].sensors; + maxValue = b3MaxFloat( stepTimes[i], maxValue ); } - // Smoothed over the last few frames so bars don't jitter visibly. - constexpr int kNowWindow = 10; - float now[kRowCount] = {}; + // ImPlot picks a 5 second major interval at this width, leaving one bright line among the half seconds + ImPlot::PushStyleVar( ImPlotStyleVar_MinorAlpha, 1.0f ); + ImPlot::PushStyleColor( ImPlotCol_AxisGrid, IM_COL32( 255, 255, 255, 15 ) ); + + ImVec2 plotSize = ImGui::GetContentRegionAvail(); + if ( ImPlot::BeginPlot( "Profile", plotSize, ImPlotFlags_NoTitle ) ) { - int n = count < kNowWindow ? count : kNowWindow; - if ( n > 0 ) - { - float inv = 1.0f / n; - for ( int r = 0; r < kRowCount; ++r ) - { - float sum = 0.0f; - for ( int i = count - n; i < count; ++i ) - { - sum += histories[r][i]; - } - now[r] = sum * inv; - } - } + ImPlot::SetupAxes( nullptr, "ms" ); + ImPlot::SetupAxisLimits( ImAxis_X1, 0.0, m_profileCapacity / 60.0 ); + ImPlot::SetupAxisLimits( ImAxis_Y1, 0.0, b3MaxFloat( maxValue, 1.0f ) * 1.05, ImPlotCond_Always ); + ImPlot::SetNextLineStyle( ImGui::ColorConvertU32ToFloat4( s_colorStep ) ); + ImPlot::PlotLine( "step", times, stepTimes, count ); + ImPlot::SetNextLineStyle( ImGui::ColorConvertU32ToFloat4( s_colorPairs ) ); + ImPlot::PlotLine( "pairs", times, pairsTimes, count ); + ImPlot::SetNextLineStyle( ImGui::ColorConvertU32ToFloat4( s_colorCollide ) ); + ImPlot::PlotLine( "collide", times, collideTimes, count ); + ImPlot::SetNextLineStyle( ImGui::ColorConvertU32ToFloat4( s_colorSolve ) ); + ImPlot::PlotLine( "solve", times, solveTimes, count ); + ImPlot::SetNextLineStyle( ImGui::ColorConvertU32ToFloat4( s_colorSensors ) ); + ImPlot::PlotLine( "sensors", times, sensorsTimes, count ); + ImPlot::EndPlot(); } - // Rolling average - float avg[kRowCount] = {}; - if ( count > 0 ) - { - float scale = 1.0f / count; - for ( int i = 0; i < kRowCount; ++i ) - { - avg[i] = scale * totals[i]; - } - } - - float rowMax[kRowCount] = {}; - for ( int r = 0; r < kRowCount; ++r ) - { - for ( int i = 0; i < count; ++i ) - { - if ( histories[r][i] > rowMax[r] ) - { - rowMax[r] = histories[r][i]; - } - } - } - - // Match Frame Time chart's first three colors so rows read with the line plot. - const ImU32 colorStep = IM_COL32( 102, 153, 255, 255 ); - const ImU32 colorPairs = IM_COL32( 220, 220, 220, 255 ); - const ImU32 colorCollide = IM_COL32( 255, 140, 51, 255 ); - const ImU32 colorSolve = IM_COL32( 102, 204, 102, 255 ); - const ImU32 colorSensors = IM_COL32( 200, 120, 220, 255 ); - const ImU32 colorOther = IM_COL32( 90, 90, 90, 255 ); - const ImU32 colorDefault = IM_COL32( 220, 220, 220, 255 ); - - const RowDef rows[kRowCount] = { - { "step", 0, colorStep }, { "pairs", 0, colorPairs }, { "collide", 0, colorCollide }, - { "solve", 0, colorSolve }, { "setup", 1, colorDefault }, { "constraints", 1, colorDefault }, - { "prepare", 2, colorDefault }, { "velocities", 2, colorDefault }, { "warm start", 2, colorDefault }, - { "bias", 2, colorDefault }, { "positions", 2, colorDefault }, { "relax", 2, colorDefault }, - { "restitution", 2, colorDefault }, { "store", 2, colorDefault }, { "split islands", 2, colorDefault }, - { "transforms", 1, colorDefault }, { "joint events", 1, colorDefault }, { "hit events", 1, colorDefault }, - { "refit BVH", 1, colorDefault }, { "sleep", 1, colorDefault }, { "bullets", 1, colorDefault }, - { "sensors", 0, colorSensors }, - }; - - // Derive parent/child links from the indent levels so we can collapse subtrees. - int parents[kRowCount]; - bool hasChildren[kRowCount] = {}; - { - int stack[8]; - int stackSize = 0; - for ( int i = 0; i < kRowCount; ++i ) - { - while ( stackSize > 0 && rows[stack[stackSize - 1]].indent >= rows[i].indent ) - { - --stackSize; - } - parents[i] = stackSize > 0 ? stack[stackSize - 1] : -1; - stack[stackSize++] = i; - if ( parents[i] >= 0 ) - { - hasChildren[parents[i]] = true; - } - } - } - - static bool s_rowOpen[kRowCount]; - static bool s_showPlots = false; - - // Bars are drawn relative to the step row so the proportions are visually consistent. - const float stepNow = b3MaxFloat( now[0], 0.001f ); - - if ( ImGui::Button( "Reset" ) ) - { - ResetProfile(); - } - ImGui::SameLine(); - ImGui::Checkbox( "Show plots", &s_showPlots ); - ImGui::SameLine(); - ImGui::Text( " step %.2f ms", now[0] ); - - // Flame strip: step subdivided by top-level children. - { - float pairsT = now[1]; - float collideT = now[2]; - float solveT = now[3]; - float sensorsT = now[21]; - float otherT = b3MaxFloat( stepNow - pairsT - collideT - solveT - sensorsT, 0.0f ); - - float availWidth = ImGui::GetContentRegionAvail().x; - float barHeight = 1.5f * fontSize; - ImDrawList* dl = ImGui::GetWindowDrawList(); - ImVec2 cursor = ImGui::GetCursorScreenPos(); - float x = cursor.x; - - x = AddSegment( dl, availWidth, pairsT, stepNow, colorPairs, x, cursor, barHeight ); - x = AddSegment( dl, availWidth, collideT, stepNow, colorCollide, x, cursor, barHeight ); - x = AddSegment( dl, availWidth, solveT, stepNow, colorSolve, x, cursor, barHeight ); - x = AddSegment( dl, availWidth, sensorsT, stepNow, colorSensors, x, cursor, barHeight ); - x = AddSegment( dl, availWidth, otherT, stepNow, colorOther, x, cursor, barHeight ); - - ImGui::Dummy( ImVec2( availWidth, barHeight ) ); - } - - const ImGuiTableFlags tableFlags = - ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_ScrollY; - - const int colCount = s_showPlots ? 6 : 5; - ImVec2 tableSize = ImGui::GetContentRegionAvail(); - if ( ImGui::BeginTable( "profile", colCount, tableFlags, tableSize ) ) - { - ImGui::TableSetupColumn( "section", ImGuiTableColumnFlags_WidthFixed, 8.0f * fontSize ); - ImGui::TableSetupColumn( "now", ImGuiTableColumnFlags_WidthFixed, 3.0f * fontSize ); - ImGui::TableSetupColumn( "avg", ImGuiTableColumnFlags_WidthFixed, 3.0f * fontSize ); - ImGui::TableSetupColumn( "max", ImGuiTableColumnFlags_WidthFixed, 3.0f * fontSize ); - ImGui::TableSetupColumn( "% step", ImGuiTableColumnFlags_WidthFixed, 8.0f * fontSize ); - if ( s_showPlots ) - { - ImGui::TableSetupColumn( "history", ImGuiTableColumnFlags_WidthFixed, 16.0f * fontSize ); - } - ImGui::TableHeadersRow(); - - const float rowHeight = 1.5f * fontSize; - - for ( int r = 0; r < kRowCount; ++r ) - { - bool visible = true; - for ( int p = parents[r]; p >= 0; p = parents[p] ) - { - if ( !s_rowOpen[p] ) - { - visible = false; - break; - } - } - if ( !visible ) - { - continue; - } - - // Hide leaf rows that are entirely zero. Parents stay so structure reads. - if ( !hasChildren[r] && now[r] == 0.0f && avg[r] == 0.0f && rowMax[r] == 0.0f ) - { - continue; - } - - const RowDef& d = rows[r]; - const float* hist = histories[r]; - - ImGui::TableNextRow(); - - ImGui::TableNextColumn(); - if ( d.indent > 0 ) - { - ImGui::Indent( d.indent * fontSize ); - } - if ( hasChildren[r] ) - { - ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | - ImGuiTreeNodeFlags_NoTreePushOnOpen; - ImGui::PushStyleColor( ImGuiCol_Text, d.color ); - s_rowOpen[r] = ImGui::TreeNodeEx( d.name, flags ); - ImGui::PopStyleColor(); - } - else - { - float leafIndent = ImGui::GetTreeNodeToLabelSpacing(); - ImGui::Indent( leafIndent ); - ImGui::PushStyleColor( ImGuiCol_Text, d.color ); - ImGui::TextUnformatted( d.name ); - ImGui::PopStyleColor(); - ImGui::Unindent( leafIndent ); - } - if ( d.indent > 0 ) - { - ImGui::Unindent( d.indent * fontSize ); - } - - ImGui::TableNextColumn(); - ImGui::Text( "%6.2f", now[r] ); - ImGui::TableNextColumn(); - ImGui::Text( "%6.2f", avg[r] ); - ImGui::TableNextColumn(); - ImGui::Text( "%6.2f", rowMax[r] ); - - ImGui::TableNextColumn(); - float frac = b3ClampFloat( now[r] / stepNow, 0.0f, 1.0f ); - ImGui::PushStyleColor( ImGuiCol_PlotHistogram, d.color ); - ImGui::ProgressBar( frac, ImVec2( -FLT_MIN, 0.0f ), "" ); - ImGui::PopStyleColor(); - - if ( s_showPlots ) - { - ImGui::TableNextColumn(); - if ( count > 1 ) - { - char id[16]; - snprintf( id, sizeof( id ), "##h%d", r ); - ImGui::PushStyleColor( ImGuiCol_PlotLines, d.color ); - ImGui::PlotLines( id, hist, count, 0, nullptr, 0.0f, rowMax[r] * 1.05f + 0.001f, - ImVec2( -FLT_MIN, rowHeight ) ); - ImGui::PopStyleColor(); - } - } - } - ImGui::EndTable(); - } + ImPlot::PopStyleColor(); + ImPlot::PopStyleVar(); ImGui::EndTabItem(); } if ( ImGui::BeginTabItem( "Counters" ) ) { - ImGui::BeginChild( "##counters_scroll" ); b3Counters s = b3World_GetCounters( m_worldId ); + b3Capacity c = b3World_GetMaxCapacity( m_worldId ); + constexpr int colorCount = sizeof( s.colorCounts ) / sizeof( s.colorCounts[0] ); - const int overflowIndex = colorCount - 1; + constexpr int overflowIndex = colorCount - 1; constexpr int manifoldBucketCount = sizeof( s.manifoldCounts ) / sizeof( s.manifoldCounts[0] ); - // Bars are scaled to the largest non-overflow color so the distribution shape reads clearly; - // overflow gets its own bar against the same scale, with a red tint to flag coupling problems. - int totalCount = 0; - int maxCount = 1; - for ( int i = 0; i < colorCount; ++i ) + // Four fixed columns side by side so the whole tab fits the drawer without scrolling + const ImGuiTableFlags tableFlags = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_SizingFixedFit; + if ( ImGui::BeginTable( "counters_layout", 4, tableFlags ) ) { - totalCount += s.colorCounts[i]; - if ( i != overflowIndex && s.colorCounts[i] > maxCount ) - { - maxCount = s.colorCounts[i]; - } - } - - int totalManifolds = 0; - int maxManifolds = 1; - for ( int i = 0; i < manifoldBucketCount; ++i ) - { - totalManifolds += s.manifoldCounts[i]; - if ( s.manifoldCounts[i] > maxManifolds ) - { - maxManifolds = s.manifoldCounts[i]; - } - } - - ImGui::Text( "bodies/shapes/contacts/joints = %d/%d/%d/%d", s.bodyCount, s.shapeCount, s.contactCount, s.jointCount ); - { - float frac = s.awakeContactCount > 0 - ? b3ClampFloat( (float)s.recycledContactCount / (float)s.awakeContactCount, 0.0f, 1.0f ) - : 0.0f; - - char overlay[32]; - snprintf( overlay, sizeof( overlay ), "%d / %d", s.recycledContactCount, s.awakeContactCount ); - - ImGui::TextUnformatted( "recycled contacts" ); - ImGui::SameLine(); - ImGui::ProgressBar( frac, ImVec2( -FLT_MIN, 0.0f ), overlay ); - } - ImGui::Text( "islands/tasks = %d/%d", s.islandCount, s.taskCount ); - ImGui::Text( "tree height static/movable = %d/%d", s.staticTreeHeight, s.treeHeight ); - ImGui::Text( "sat call/hit = %d/%d", s.satCallCount, s.satCacheHitCount ); - ImGui::Text( "toi d/p/r = %d/%d/%d", s.distanceIterations, s.pushBackIterations, s.rootIterations ); - ImGui::Text( "stack allocator size = %d K", s.stackUsed / 1024 ); - ImGui::Text( "arena capacity = %d K", s.arenaCapacity / 1024 ); - ImGui::Text( "total allocation = %d K", (int)(s.byteCount / 1024) ); - - ImGui::Separator(); - b3Capacity c = b3World_GetMaxCapacity( m_worldId ); - ImGui::Text( "max capacities" ); - ImGui::BulletText( "static shapes/bodies = %d/%d", c.staticShapeCount, c.staticBodyCount ); - ImGui::BulletText( "dynamic shapes/bodies = %d/%d", c.dynamicShapeCount, c.dynamicBodyCount ); - ImGui::BulletText( "contacts = %d", c.contactCount ); - - ImGui::Separator(); - ImGui::Text( "%d constraints across %d colors", totalCount, colorCount ); - - const ImGuiTableFlags tableFlags = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit; - if ( ImGui::BeginTable( "graphColors", 3, tableFlags ) ) - { - ImGui::TableSetupColumn( "color", ImGuiTableColumnFlags_WidthFixed, 3.5f * fontSize ); - ImGui::TableSetupColumn( "count", ImGuiTableColumnFlags_WidthFixed, 5.0f * fontSize ); - ImGui::TableSetupColumn( "share", ImGuiTableColumnFlags_WidthFixed, 16.0f * fontSize ); + ImGui::TableSetupColumn( "world", ImGuiTableColumnFlags_WidthFixed, 11.0f * fontSize ); + ImGui::TableSetupColumn( "memory", ImGuiTableColumnFlags_WidthFixed, 9.0f * fontSize ); + ImGui::TableSetupColumn( "collision", ImGuiTableColumnFlags_WidthFixed, 11.0f * fontSize ); + ImGui::TableSetupColumn( "solver", ImGuiTableColumnFlags_WidthStretch ); ImGui::TableHeadersRow(); + ImGui::TableNextRow(); - const float invMax = 1.0f / static_cast( maxCount ); + ImGui::TableNextColumn(); + ImGui::Text( "bodies %d / %d", s.bodyCount, c.staticBodyCount + c.dynamicBodyCount ); + ImGui::SetItemTooltip( "max static %d, dynamic %d", c.staticBodyCount, c.dynamicBodyCount ); + ImGui::Text( "shapes %d / %d", s.shapeCount, c.staticShapeCount + c.dynamicShapeCount ); + ImGui::SetItemTooltip( "max static %d, dynamic %d", c.staticShapeCount, c.dynamicShapeCount ); + ImGui::Text( "contacts %d / %d", s.contactCount, c.contactCount ); + ImGui::SetItemTooltip( "current / max" ); + ImGui::Text( "joints %d", s.jointCount ); + ImGui::Text( "islands %d", s.islandCount ); + ImGui::Text( "tasks %d", s.taskCount ); + ImGui::TableNextColumn(); + ImGui::Text( "static tree %d", s.staticTreeHeight ); + ImGui::SetItemTooltip( "tree height" ); + ImGui::Text( "movable tree %d", s.treeHeight ); + ImGui::SetItemTooltip( "tree height" ); + ImGui::Text( "alloc %lld K", (long long)( s.byteCount / 1024 ) ); + ImGui::Text( "stack %d K", s.stackUsed / 1024 ); + ImGui::Text( "arena %d K", s.arenaCapacity / 1024 ); + + ImGui::TableNextColumn(); + ImGui::Text( "sat %d / %d", s.satCallCount, s.satCacheHitCount ); + ImGui::SetItemTooltip( "SAT calls / cache hits" ); + ImGui::Text( "toi %d / %d / %d", s.distanceIterations, s.pushBackIterations, s.rootIterations ); + ImGui::SetItemTooltip( "TOI distance / push back / root iterations" ); + + // The world clamps into the second to last bucket, so the last is always empty and the + // second to last means that many or more + constexpr int manifoldBarCount = manifoldBucketCount - 1; + int totalManifolds = 0; + int maxManifolds = 0; + ImU32 manifoldColors[manifoldBarCount]; + for ( int i = 0; i < manifoldBarCount; ++i ) + { + totalManifolds += s.manifoldCounts[i]; + maxManifolds = b3MaxInt( maxManifolds, s.manifoldCounts[i] ); + manifoldColors[i] = s_colorPairs; + } + + ImGui::TextDisabled( "manifolds per pair" ); + ImVec2 manifoldSize = { ImGui::GetContentRegionAvail().x, 4.0f * fontSize }; + int hoveredBucket = + DrawBarChart( "##manifolds", s.manifoldCounts, manifoldColors, manifoldBarCount, maxManifolds, manifoldSize ); + if ( hoveredBucket >= 0 ) + { + const char* plus = hoveredBucket == manifoldBarCount - 1 ? "+" : ""; + ImGui::SetTooltip( "%d%s manifolds: %d of %d pairs", hoveredBucket + 1, plus, s.manifoldCounts[hoveredBucket], + totalManifolds ); + } + + ImGui::TableNextColumn(); + + // Bars are scaled to the largest normal color so the distribution shape reads clearly. Overflow + // gets a share bar of its own below to flag coupling problems. + int totalCount = 0; + int maxCount = 0; + ImU32 colors[overflowIndex]; for ( int i = 0; i < colorCount; ++i ) { - int count = s.colorCounts[i]; - bool isOverflow = ( i == overflowIndex ); - - // Skip empty slots, but always show overflow. - if ( count == 0 && !isOverflow ) + totalCount += s.colorCounts[i]; + if ( i != overflowIndex ) { - continue; + maxCount = b3MaxInt( maxCount, s.colorCounts[i] ); + uint32_t hex = static_cast( b3GetGraphColor( i ) ); + colors[i] = IM_COL32( ( hex >> 16 ) & 0xFF, ( hex >> 8 ) & 0xFF, hex & 0xFF, 255 ); } - - uint32_t hex = static_cast( b3GetGraphColor( i ) ); - ImU32 swatch = IM_COL32( ( hex >> 16 ) & 0xFF, ( hex >> 8 ) & 0xFF, hex & 0xFF, 255 ); - ImU32 barColor = isOverflow ? IM_COL32( 220, 60, 60, 255 ) : swatch; - - ImGui::TableNextRow(); - - ImGui::TableNextColumn(); - if ( isOverflow ) - { - ImGui::PushStyleColor( ImGuiCol_Text, IM_COL32( 220, 60, 60, 255 ) ); - ImGui::TextUnformatted( "over" ); - ImGui::PopStyleColor(); - } - else - { - ImGui::PushStyleColor( ImGuiCol_Text, swatch ); - ImGui::Text( "%d", i ); - ImGui::PopStyleColor(); - } - - ImGui::TableNextColumn(); - ImGui::Text( "%d", count ); - - ImGui::TableNextColumn(); - float frac = b3ClampFloat( count * invMax, 0.0f, 1.0f ); - ImGui::PushStyleColor( ImGuiCol_PlotHistogram, barColor ); - ImGui::ProgressBar( frac, ImVec2( -FLT_MIN, 0.0f ), "" ); - ImGui::PopStyleColor(); } - ImGui::EndTable(); - } + int overflowCount = s.colorCounts[overflowIndex]; - ImGui::Separator(); - ImGui::Text( "%d manifolds across %d buckets", totalManifolds, manifoldBucketCount ); - if ( ImGui::BeginTable( "manifolds", 3, tableFlags ) ) - { - ImGui::TableSetupColumn( "manifolds", ImGuiTableColumnFlags_WidthFixed, 3.5f * fontSize ); - ImGui::TableSetupColumn( "count", ImGuiTableColumnFlags_WidthFixed, 5.0f * fontSize ); - ImGui::TableSetupColumn( "share", ImGuiTableColumnFlags_WidthFixed, 16.0f * fontSize ); - ImGui::TableHeadersRow(); + ImGui::Text( "%d constraints across %d colors", totalCount, overflowIndex ); - const float invMax = 1.0f / static_cast( maxManifolds ); - - for ( int i = 0; i < manifoldBucketCount; ++i ) + ImVec2 colorSize = { ImGui::GetContentRegionAvail().x, 5.0f * fontSize }; + int hoveredColor = DrawBarChart( "##colors", s.colorCounts, colors, overflowIndex, maxCount, colorSize ); + if ( hoveredColor >= 0 ) { - int count = s.manifoldCounts[i]; - if ( count == 0 ) - { - continue; - } - - ImGui::TableNextRow(); - - ImGui::TableNextColumn(); - ImGui::Text( "%d", i + 1 ); - - ImGui::TableNextColumn(); - ImGui::Text( "%d", count ); - - ImGui::TableNextColumn(); - float frac = b3ClampFloat( count * invMax, 0.0f, 1.0f ); - ImGui::ProgressBar( frac, ImVec2( -FLT_MIN, 0.0f ), "" ); + ImGui::SetTooltip( "color %d: %d", hoveredColor, s.colorCounts[hoveredColor] ); } + + // Overflow and recycling share a line to keep the column within the drawer height + float halfWidth = 0.5f * ( ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.x ); + + float overflowFrac = totalCount > 0 ? (float)overflowCount / (float)totalCount : 0.0f; + char overflowOverlay[32]; + snprintf( overflowOverlay, sizeof( overflowOverlay ), "overflow %d", overflowCount ); + ImGui::PushStyleColor( ImGuiCol_PlotHistogram, IM_COL32( 220, 60, 60, 255 ) ); + ImGui::ProgressBar( overflowFrac, ImVec2( halfWidth, 0.0f ), overflowOverlay ); + ImGui::PopStyleColor(); + ImGui::SetItemTooltip( "Constraints in the overflow color, solved serially" ); + ImGui::SameLine(); + + float recycledFrac = s.awakeContactCount > 0 + ? b3ClampFloat( (float)s.recycledContactCount / (float)s.awakeContactCount, 0.0f, 1.0f ) + : 0.0f; + char recycledOverlay[48]; + snprintf( recycledOverlay, sizeof( recycledOverlay ), "recycled %d / %d", s.recycledContactCount, + s.awakeContactCount ); + ImGui::ProgressBar( recycledFrac, ImVec2( -FLT_MIN, 0.0f ), recycledOverlay ); + ImGui::SetItemTooltip( "Awake contacts that reused last step's manifold" ); + ImGui::EndTable(); } - ImGui::EndChild(); ImGui::EndTabItem(); } @@ -1131,39 +1200,6 @@ void Sample::DrawMetrics() ImGui::EndTabItem(); } - if ( ImGui::BeginTabItem( "Frame Time" ) ) - { - float maxValue = 0.0f; - float times[m_profileCapacity]; - float stepTimes[m_profileCapacity]; - float collideTimes[m_profileCapacity]; - float solveTimes[m_profileCapacity]; - int count = m_profileWriteIndex - m_profileReadIndex; - for ( int i = 0; i < count; ++i ) - { - int index = ( m_profileReadIndex + i ) & ( m_profileCapacity - 1 ); - times[i] = i / 60.0f; - stepTimes[i] = m_profiles[index].step; - collideTimes[i] = m_profiles[index].collide; - solveTimes[i] = m_profiles[index].solve; - maxValue = b3MaxFloat( stepTimes[i], maxValue ); - } - - ImVec2 plotSize = ImGui::GetContentRegionAvail(); - if ( ImPlot::BeginPlot( "Profile", plotSize, ImPlotFlags_NoTitle ) ) - { - ImPlot::SetupAxes( "t", "ms" ); - ImPlot::SetupAxisLimits( ImAxis_X1, 0.0, m_profileCapacity / 60.0 ); - ImPlot::SetupAxisLimits( ImAxis_Y1, 0.0, b3MaxFloat( maxValue, 1.0f ) * 1.05, ImPlotCond_Always ); - ImPlot::PlotLine( "step", times, stepTimes, count ); - ImPlot::PlotLine( "collide", times, collideTimes, count ); - ImPlot::PlotLine( "solve", times, solveTimes, count ); - ImPlot::EndPlot(); - } - - ImGui::EndTabItem(); - } - // Sample-specific tabs (the Replay viewer adds Timeline here). DrawMetricsTab(); @@ -1334,7 +1370,7 @@ void Sample::DrawTextLine( const char* text, ... ) char buffer[512]; vsnprintf( buffer, sizeof( buffer ), text, args ); va_end( args ); - DrawScreenString( 5, m_textLine, MakeColor( b3_colorWhite ), buffer ); + DrawScreenString( m_textX, m_textLine, MakeColor( b3_colorWhite ), buffer ); m_textLine += m_textIncrement; } @@ -1374,6 +1410,14 @@ void SelectSample( SampleContext* context, int selection, bool restart ) return; } + if ( restart == false ) + { + context->pause = false; + } + + // Steps queued in a sample that never consumes them must not play out in the next one + context->singleStep = 0; + // delete tolerates the first selection, before any sample exists. delete context->sample; context->sample = nullptr; @@ -1785,7 +1829,8 @@ static void DrawMenuBar( SampleContext* context ) ImGui::EndMenu(); } ImGui::Separator(); - ImGui::MenuItem( "Diagnostics", "M", &context->showMetrics ); + ImGui::MenuItem( "Metrics", "M", &context->showMetrics ); + ImGui::MenuItem( "Profile", "I", &context->showProfile, context->sample->HasProfile() ); ImGui::PushItemWidth( 8.0f * fontSize ); ImGui::SliderFloat( "Draw Distance", &context->drawDistance, 10.0f, Camera::kViewDistance, "%.0f m" ); ImGui::PopItemWidth(); @@ -1875,7 +1920,8 @@ static void DrawMenuBar( SampleContext* context ) if ( ImGui::BeginTable( "keys", 2, ImGuiTableFlags_SizingFixedFit ) ) { DrawRow( "Tab", "Show / hide UI" ); - DrawRow( "M", "Show / hide diagnostics" ); + DrawRow( "M", "Show / hide metrics" ); + DrawRow( "I", "Show / hide profile" ); DrawRow( "P", "Pause / resume" ); DrawRow( ".", "Single step (Shift: 5)" ); DrawRow( ",", "Step back, replay only (Shift: 5)" ); @@ -2030,6 +2076,22 @@ static void DrawSamplePicker( SampleContext* context ) } } +// A dot after the widget that reveals help on hover. Unlike a tooltip on the widget itself, +// it never covers the value being edited, and it is quieter than a "(?)" on every row. +static void HelpMarker( const char* text ) +{ + ImGui::SameLine( 0.0f, ImGui::GetStyle().ItemInnerSpacing.x ); + float width = ImGui::GetFontSize(); + float height = ImGui::GetFrameHeight(); + ImVec2 pos = ImGui::GetCursorScreenPos(); + ImGui::Dummy( { width, height } ); + bool hovered = ImGui::IsItemHovered(); + ImU32 color = ImGui::GetColorU32( ImGuiCol_CheckMark, hovered ? 1.0f : 0.6f ); + ImVec2 center = { pos.x + 0.5f * width, pos.y + 0.5f * height }; + ImGui::GetWindowDrawList()->AddCircleFilled( center, 0.2f * width, color ); + ImGui::SetItemTooltip( "%s", text ); +} + static void DrawInfoPanel( SampleContext* context ) { const SampleEntry& entry = g_sampleEntries[context->sampleIndex]; @@ -2058,7 +2120,7 @@ static void DrawInfoPanel( SampleContext* context ) } const float frameMs = (float)( sapp_frame_duration() * 1000.0 ); - ImGui::TextColored( HexColor( b3_colorSeaGreen ), "%.1f ms", frameMs ); + ImGui::TextColored( HexColor( b3_colorSeaGreen ), "frame %.1f ms", frameMs ); ImGui::TextColored( HexColor( b3_colorSeaGreen ), "step %d", context->sample->m_stepCount ); ImGui::Separator(); @@ -2085,14 +2147,20 @@ static void DrawInfoPanel( SampleContext* context ) { ImGui::PushItemWidth( 6.0f * fontSize ); ImGui::SliderInt( "Sub-steps##Solver", &context->subStepCount, 1, 50 ); - ImGui::SliderInt( "Rest Iters##Solver", &context->restitutionIterations, 0, 8 ); - ImGui::SliderFloat( "Hertz##Solver", &context->hertz, 5.0f, 240.0f, "%.0f hz" ); + HelpMarker( "The solver breaks the full step into several sub-steps.\nMore sub-steps usually lead to more accurate results." ); + + ImGui::SliderInt( "Bounce Iters##Solver", &context->restitutionIterations, 0, 8 ); + HelpMarker( "Iterations for the restitution solver." ); + + ImGui::SliderFloat( "Hertz##Solver", &context->hertz, 5.0f, 240.0f, "%.0f Hz" ); + HelpMarker( "The number of world steps per second." ); if ( ImGui::SliderInt( "Workers##Solver", &context->workerCount, 1, B3_MAX_WORKERS ) ) { context->workerCount = b3ClampInt( context->workerCount, 1, B3_MAX_WORKERS ); SelectSample( context, context->sampleIndex, true ); } + HelpMarker( "The number worker threads used by the world step." ); float recyclingCentimeters = 100.0f * context->recycleDistance; if ( ImGui::SliderFloat( "Recycle##Solver", &recyclingCentimeters, 0.0f, 10.0f, "%.1f cm" ) ) @@ -2100,12 +2168,20 @@ static void DrawInfoPanel( SampleContext* context ) context->recycleDistance = 0.01f * recyclingCentimeters; b3World_SetContactRecycleDistance( context->sample->m_worldId, context->recycleDistance ); } + HelpMarker( "The contact recycling distance tolerance.\nSet to zero to disable recycling." ); ImGui::PopItemWidth(); ImGui::Checkbox( "Sleep##Solver", &context->enableSleep ); + HelpMarker( "Allow bodies to sleep, reducing simulation CPU cost." ); + ImGui::Checkbox( "Warm Starting##Solver", &context->enableWarmStarting ); + HelpMarker( "Enable solver warm starting which usually improves stacking stability." ); + ImGui::Checkbox( "Continuous##Solver", &context->enableContinuous ); - ImGui::Checkbox( "Rest Prop##Solver", &context->enableRestitutionPropagation ); + HelpMarker( "Enable continuous collision detection." ); + + ImGui::Checkbox( "Bounce Propagation##Solver", &context->enableRestitutionPropagation ); + HelpMarker( "Enable restitution solver propagation across all touching contacts points" ); if ( ImGui::Shortcut( ImGuiKey_R ) || ImGui::Button( "Restart" ) ) { @@ -2133,6 +2209,16 @@ static void DrawInfoPanel( SampleContext* context ) { context->sample->StartRecording(); } + + if ( g_replayIndex >= 0 && context->savedRecordingFile[0] != 0 ) + { + if ( ImGui::Button( "Play##Recording" ) ) + { + snprintf( context->replayFile, sizeof( context->replayFile ), "%s", context->savedRecordingFile ); + SelectSample( context, g_replayIndex, false ); + } + ImGui::SetItemTooltip( "Open %s in the replay viewer", context->savedRecordingFile ); + } } else { @@ -2140,7 +2226,20 @@ static void DrawInfoPanel( SampleContext* context ) { context->sample->FinishRecording(); } - ImGui::TextColored( HexColor( b3_colorSeaGreen ), "recording (from step %d)", context->sample->m_recordStartStep ); + } + + if ( context->sample->m_recording != nullptr ) + { + float kilobytes = b3Recording_GetSize( context->sample->m_recording ) / 1024.0f; + int steps = context->sample->m_stepCount - context->sample->m_recordStartStep; + if ( kilobytes < 1024.0f ) + { + ImGui::TextColored( HexColor( b3_colorRed ), "recording %d steps, %.0f KB", steps, kilobytes ); + } + else + { + ImGui::TextColored( HexColor( b3_colorRed ), "recording %d steps, %.1f MB", steps, kilobytes / 1024.0f ); + } } } @@ -2181,7 +2280,8 @@ void DrawUI( SampleContext* context ) // Extra top-level windows (the Replay viewer adds the Outline panel). context->sample->DrawSampleWindows(); - // Bottom diagnostics drawer. Sample controls live in the info panel. + // Sample controls live in the info panel. + context->sample->DrawProfile(); context->sample->DrawMetrics(); } diff --git a/samples/sample.h b/samples/sample.h index ded069a..d457894 100644 --- a/samples/sample.h +++ b/samples/sample.h @@ -50,6 +50,10 @@ struct SampleContext char recordingFile[256] = "recording.b3rec"; char replayFile[256] = ""; + // Last recording saved this session, empty until a save succeeds. The default record path + // may name a stale file from an earlier run, so Play only trusts this one. + char savedRecordingFile[256] = ""; + // Keyframe ring policy the Replay viewer applies on open, persisted across sessions. int replayKeyframeBudgetMB = 512; int replayKeyframeMinInterval = 16; @@ -80,10 +84,13 @@ struct SampleContext // UI visibility (Tab / View > Hide UI). When hidden only the minimal HUD shows. bool showUI = true; - // Bottom diagnostics drawer (M), set by Ctrl+O for the fuzzy picker. + // Bottom metrics drawer (M), set by Ctrl+O for the fuzzy picker. bool showMetrics = false; bool openSamplePicker = false; + // Left profile panel (I) + bool showProfile = false; + // Controls help window (Help > Controls, toggled with ?). Promoted to the // context so the key handler can reach it. Seeded from newUser after Load. bool showControls = false; @@ -145,6 +152,12 @@ public: return true; } + // Allow a sample without a world step to hide the profile panel. + virtual bool HasProfile() const + { + return true; + } + // Width of the right info panel in em. The bottom drawer clears to the same width. A sample that // hosts heavier content there, such as the replay viewer's detail pane, can widen it. virtual float InfoPanelWidthEm() const; @@ -169,10 +182,15 @@ public: void StartRecording(); void FinishRecording(); - // Bottom diagnostics drawer (Profile / Counters / Renderer / Frame Time). + // Left profile panel, a table of the step sections readable at a glance. + bool IsProfileVisible() const; + float GetProfilePanelWidth() const; + void DrawProfile(); + + // Bottom metrics drawer (Frame Time / Counters / Renderer). void DrawMetrics(); - // Append extra tabs to the diagnostics drawer's tab bar (the Replay viewer adds Timeline). + // Append extra tabs to the metrics drawer's tab bar (the Replay viewer adds Timeline). virtual void DrawMetricsTab() { } @@ -221,6 +239,7 @@ public: float m_mouseForceScale; float m_launchSpeedScale; int m_stepCount; + int m_textX; int m_textLine; int m_textIncrement; int m_triangleIndex; @@ -288,8 +307,8 @@ void FrameSelection( SampleContext* context ); // a blocking nested run loop), driven by SampleContext::openReplayPicker. void OpenReplayFileDialog( SampleContext* context ); -// The single host UI callback: menu bar, sample picker, info panel, and the -// bottom diagnostics drawer. +// The single host UI callback: menu bar, sample picker, info panel, profile panel, +// and the bottom metrics drawer. void DrawUI( SampleContext* context ); struct CastClosestContext diff --git a/samples/sample_replay.cpp b/samples/sample_replay.cpp index 328020c..199ad9d 100644 --- a/samples/sample_replay.cpp +++ b/samples/sample_replay.cpp @@ -216,7 +216,7 @@ enum SelectionKind // - right info panel (DrawControls): Show Timeline button, view toggles, frame counter, and the // selection detail // - left Outline window (DrawSampleWindows): the recorded scene tree -// - Timeline tab in the diagnostics drawer (DrawMetricsTab): transport, scrubber, keyframe readout +// - Timeline tab in the metrics drawer (DrawMetricsTab): transport, scrubber, keyframe readout class ReplayViewer : public Sample { public: @@ -695,6 +695,11 @@ public: return false; } + bool HasProfile() const override + { + return false; + } + // Wider than the default so the detail pane, hosted in the info panel, has room for ids and vectors. float InfoPanelWidthEm() const override { @@ -1089,7 +1094,7 @@ public: float menuBarHeight = ImGui::GetFrameHeight(); float top = menuBarHeight + 0.5f * fontSize; - // Stop above the diagnostics drawer when it is open so the panels do not overlap. The 16 em + // Stop above the metrics drawer when it is open so the panels do not overlap. The 16 em // drawer height mirrors DrawMetrics. float bottom = m_context->showMetrics ? ( m_camera->m_height - 16.0f * fontSize - fontSize ) : ( m_camera->m_height - 0.5f * fontSize ); @@ -1667,7 +1672,7 @@ public: } } - // Timeline tab in the diagnostics drawer: file, transport, keyframe readout, scrubber, divergence. + // Timeline tab in the metrics drawer: file, transport, keyframe readout, scrubber, divergence. void DrawMetricsTab() override { ImGuiTabItemFlags flags = m_selectTimelineTab ? ImGuiTabItemFlags_SetSelected : 0; @@ -1754,7 +1759,12 @@ public: b3Counters c = b3World_GetCounters( m_replayWorldId ); ImGui::Text( "frames %d", m_info.frameCount ); ImGui::SameLine(); - ImGui::Text( " %.0f hz, %d sub-steps", hz, m_info.subStepCount ); + ImGui::Text( " %.0f Hz, %d sub-steps", hz, m_info.subStepCount ); + if ( m_info.lengthScale > 0.0f ) + { + ImGui::SameLine(); + ImGui::Text( " %g units/m", m_info.lengthScale ); + } ImGui::SameLine(); ImGui::Text( " bodies %d shapes %d contacts %d joints %d", c.bodyCount, c.shapeCount, c.contactCount, c.jointCount );