Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add tracy profiler integration #5258

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ dependencies {
// Natives for JNBullet
natives(group = "org.terasology.jnbullet", name = "JNBullet", version = "1.0.4", ext = "zip")

// Natives for Tracy bindings (embedded in JAR)
natives("io.github.benjaminamos.TracyJavaBindings:TracyJavaBindings:1.0.0-SNAPSHOT")
}

tasks.register<Copy>("extractWindowsNatives") {
Expand Down Expand Up @@ -135,14 +137,22 @@ tasks.register<Copy>("extractNativeBulletNatives") {
into("$dirNatives")
}

tasks.register<Copy>("extractTracyJNINatives") {
description = "Extracts the Tracy JNI natives from the module jar"
from(configurations["natives"].filter { it.name.contains("TracyJavaBindings") }.map { zipTree(it) })
into(dirNatives)
exclude("io/**", "META-INF/**")
}

tasks.register("extractNatives") {
description = "Extracts all the native lwjgl libraries from the downloaded zip"
dependsOn(
"extractWindowsNatives",
"extractLinuxNatives",
"extractMacOSXNatives",
"extractJNLuaNatives",
"extractNativeBulletNatives"
"extractNativeBulletNatives",
"extractTracyJNINatives"
)
// specifying the outputs directory lets gradle have an up-to-date check, and automatic clean task
outputs.dir("$dirNatives")
Expand Down
2 changes: 2 additions & 0 deletions engine/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,8 @@ dependencies {
implementation("org.terasology.crashreporter:cr-terasology:5.0.0")

api(project(":subsystems:TypeHandlerLibrary"))

implementation("io.github.benjaminamos.TracyJavaBindings:TracyJavaBindings:1.0.0-SNAPSHOT")
}

protobuf {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,12 @@ public class SystemConfig extends AutoConfig {
name("${engine:menu#settings-monitoring-enabled}")
);

public final Setting<Boolean> tracyProfilerEnabled = setting(
type(Boolean.class),
defaultValue(false),
name("${engine:menu#settings-tracy-profiler-enabled}")
);

public final Setting<Boolean> writeSaveGamesEnabled = setting(
type(Boolean.class),
defaultValue(true),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -468,12 +468,10 @@ public synchronized void runMain() {
*/
@SuppressWarnings("checkstyle:EmptyBlock")
private void mainLoop() {
PerformanceMonitor.startActivity("Other");
// MAIN GAME LOOP
while (tick()) {
/* do nothing */
}
PerformanceMonitor.endActivity();
}

/**
Expand All @@ -482,6 +480,7 @@ private void mainLoop() {
* @return true if the loop requesting a tick should continue running
*/
public boolean tick() {
PerformanceMonitor.startActivity("Tick");
if (shutdownRequested) {
return false;
}
Expand Down Expand Up @@ -524,8 +523,8 @@ public boolean tick() {
}
assetTypeManager.disposedUnusedAssets();

PerformanceMonitor.endActivity();
PerformanceMonitor.rollCycle();
PerformanceMonitor.startActivity("Other");
return true;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
*/
public final class PerformanceMonitor {
private static PerformanceMonitorInternal instance;
private static boolean tracyEnabled;

static {
instance = new NullPerformanceMonitor();
Expand Down Expand Up @@ -127,6 +128,10 @@ public static TObjectDoubleMap<String> getAllocationMean() {
return instance.getAllocationMean();
}

public static void setTracyEnabled(boolean enabled) {
tracyEnabled = enabled;
}

/**
* Enables or disables the Performance Monitoring system.
* <br><br>
Expand All @@ -136,8 +141,14 @@ public static TObjectDoubleMap<String> getAllocationMean() {
*/
public static void setEnabled(boolean enabled) {
if (enabled && !(instance instanceof PerformanceMonitorImpl)) {
instance = new PerformanceMonitorImpl();
if (instance != null) {
instance.shutdown();
}
instance = new PerformanceMonitorImpl(tracyEnabled);
} else if (!enabled && !(instance instanceof NullPerformanceMonitor)) {
if (instance != null) {
instance.shutdown();
}
instance = new NullPerformanceMonitor();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,7 @@ public TObjectDoubleMap<String> getAllocationMean() {
return metrics;
}

@Override
public void shutdown() {
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
package org.terasology.engine.monitoring.impl;

import io.github.benjaminamos.tracy.Tracy;
import com.google.common.collect.Lists;
import com.google.common.collect.Queues;
import gnu.trove.map.TObjectDoubleMap;
Expand Down Expand Up @@ -31,6 +32,7 @@ public class PerformanceMonitorImpl implements PerformanceMonitorInternal {
// on the main thread. Not strictly necessary (these processes are ignored by the PerformanceMonitor
// anyway) an instance of this class offers a slight performance improvement over standard Activity
// implementations as it doesn't call the PerformanceMonitor.endActivity() method.
private static boolean tracyEnabled = false;

private final Activity activityInstance = new ActivityInstance();

Expand All @@ -57,7 +59,7 @@ public class PerformanceMonitorImpl implements PerformanceMonitorInternal {
private final Thread mainThread;
private final EngineTime timer;

public PerformanceMonitorImpl() {
public PerformanceMonitorImpl(boolean enableTracy) {
activityStack = Queues.newArrayDeque();
executionData = Lists.newLinkedList();
allocationData = Lists.newLinkedList();
Expand All @@ -78,6 +80,11 @@ public PerformanceMonitorImpl() {

timer = (EngineTime) CoreRegistry.get(Time.class);
mainThread = Thread.currentThread();

if (enableTracy && !tracyEnabled) {
Tracy.startupProfiler();
tracyEnabled = true;
}
}

@Override
Expand All @@ -101,6 +108,12 @@ public void rollCycle() {

currentExecutionData = new TObjectLongHashMap<>();
currentAllocationData = new TObjectLongHashMap<>();

activityStack.clear();

if (tracyEnabled) {
Tracy.markFrame();
}
}

@Override
Expand All @@ -111,6 +124,13 @@ public Activity startActivity(String activityName) {

ActivityInfo newActivity = new ActivityInfo(activityName).initialize();

if (tracyEnabled) {
StackWalker.StackFrame caller = java.security.AccessController.doPrivileged((java.security.PrivilegedAction<StackWalker.StackFrame>) () ->
StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE).walk(s -> s.skip(4).findFirst()).get());
long sourceLocation = Tracy.allocSourceLocation(caller.getLineNumber(), caller.getFileName(), caller.getClassName() + "#" + caller.getMethodName(), activityName, 0);
newActivity.zoneContext = Tracy.zoneBegin(sourceLocation, 1);
}

if (!activityStack.isEmpty()) {
ActivityInfo currentActivity = activityStack.peek();
currentActivity.ownTime += newActivity.startTime - ((currentActivity.resumeTime > 0)
Expand All @@ -133,6 +153,10 @@ public void endActivity() {

ActivityInfo oldActivity = activityStack.pop();

if (tracyEnabled) {
Tracy.zoneEnd(oldActivity.zoneContext);
}

long endTime = timer.getRealTimeInMs();
long totalTime = (oldActivity.resumeTime > 0)
? oldActivity.ownTime + endTime - oldActivity.resumeTime
Expand All @@ -152,6 +176,7 @@ public void endActivity() {
}
}


@Override
public TObjectDoubleMap<String> getRunningMean() {
TObjectDoubleMap<String> activityToMeanMap = new TObjectDoubleHashMap<>();
Expand Down Expand Up @@ -179,13 +204,23 @@ public TObjectDoubleMap<String> getAllocationMean() {
return activityToMeanMap;
}

@Override
public void shutdown() {
if (tracyEnabled) {
tracyEnabled = false;
Tracy.shutdownProfiler();
}
}

private class ActivityInfo {
public String name;
public long startTime;
public long resumeTime;
public long ownTime;
public long startMem;
public long ownMem;
public StackWalker.StackFrame caller;
public Tracy.ZoneContext zoneContext;

ActivityInfo(String activityName) {
this.name = activityName;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,6 @@ public interface PerformanceMonitorInternal {
TObjectDoubleMap<String> getDecayingSpikes();

TObjectDoubleMap<String> getAllocationMean();

void shutdown();
}
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,7 @@ protected boolean isEscapeToCloseAllowed() {
*/
public void toggleMetricsMode() {
MetricsMode mode = debugMetricsSystem.toggle();
PerformanceMonitor.setTracyEnabled(systemConfig.tracyProfilerEnabled.get());
PerformanceMonitor.setEnabled(mode.isPerformanceManagerMode());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,7 @@
"settings-debug-mode": "settings-debug-mode",
"settings-language": "settings-language",
"settings-monitoring-enabled": "settings-monitoring-enabled",
"settings-tracy-profiler-enabled": "settings-tracy-profiler-enabled",
"settings-saves-enabled": "settings-saves-enabled",
"settings-seconds-between-saves": "settings-seconds-between-saves",
"settings-title": "settings-title",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,7 @@
"settings-debug-mode": "Debug mode",
"settings-language": "Language",
"settings-monitoring-enabled": "Monitoring",
"settings-tracy-profiler-enabled": "Tracy Profiler",
"settings-saves-enabled": "Game saves",
"settings-seconds-between-saves": "Seconds between saves",
"settings-title": "Settings",
Expand Down
Loading