Compare commits

..

8 Commits
pr322 ... pr291

Author SHA1 Message Date
icex2
fb1442b734 feat: Add helper to set avs implementations
Doesn't really reduce boiler plate but adds
clarity with a more meaningful function name
what the operation does.
2024-02-25 09:30:53 +01:00
icex2
87b7e53973 feat: Add core module
This module contains the "core" (API) of
bemanitools which includes an abstraction
layer for threads and logging at this time.

The threads API is very close to what
util/thread already was with some structural
enhancements which make it easier to understand
and work with the API, I hope. Some additional
helpers (*-ext module) support in doing common
tasks, e.g. setting up the thread API with other
modules.

The log(ging) part receives a major overhaul to
address known limitations and issues with the
util/log module:
- Cleaner API layer
- Separate sinks from actual logging engine
- Sinks are composable
- Improved and cleaner compatibility layer
  with AVS logging API

Additional "extensions" (*-ext modules) add
various helper functions for common tasks like
setting up the logging engine with a file and stdout
sink.

The sinks also improved significantly with the file
sink now supporting proper appending and log rotation.
Logging to stdout/stderr supports coloring of log
messages which works across logging engines.

Overall, this refactored foundation is expected to
support future developments and removes known
limitations at the current scale of bemanitools such as:
- Reducing boiler plate code across hooks
- Interop of bemanitools and AVS (and setting the foundation
  for addressing currently missing interop, e.g. for
  dealing with property structures without AVS)
- Addressing performance issues in the logging engine
  due to incorrect interop with AVS
2024-02-25 09:30:53 +01:00
icex2
2e45f095ba feat(avs-util): Add helper to translate property errors 2024-02-25 09:30:53 +01:00
icex2
e12cd63ba2 Fix(avs): Incorrect function signature
After getting doubts, I looked this one up again on the
assembly. The decompiled output confused me
and no actual value is being returned there.
2024-02-25 09:30:47 +01:00
icex2
8804e667b3 feat(avs): Add property get and clear error functions
Use these to improve error handling by allowing
one to provide additional error information on
property related operations.
2024-02-25 09:14:42 +01:00
icex2
f5b8af3f2a feat(dev): Add a separate docker dev container
Improve the development experience by providing
an additional docker container that can be started
and used as an interactive development environment.
It provides all the tools and a stable environment
for building (identical to the build container).
2024-02-25 09:14:42 +01:00
icex2
ab6c3fc8bc fix(hook): Add missing hook_table_revert impl
Allow hooks to cleanup when they are shut down.
2024-02-25 09:07:54 +01:00
icex2
7a56fab96e fix(dist): Incorrect versioning for ddr distribution packages
Apparently forgotten to get updated to reflect the
currently supported versions correctly.
2024-02-25 08:51:25 +01:00
59 changed files with 1796 additions and 756 deletions

21
Dockerfile.dev Normal file
View File

@@ -0,0 +1,21 @@
FROM --platform=amd64 debian:11.6-slim@sha256:f7d141c1ec6af549958a7a2543365a7829c2cdc4476308ec2e182f8a7c59b519
LABEL description="Development environment for bemanitools"
# mingw-w64-gcc has 32-bit and 64-bit toolchains
RUN apt-get update && apt-get install -y --no-install-recommends \
mingw-w64 \
mingw-w64-common \
make \
zip \
git \
clang-format \
python3-pip \
&& rm -rf /var/lib/apt/lists/*
RUN pip3 install mdformat
RUN mkdir /bemanitools
WORKDIR /bemanitools
ENV SHELL /bin/bash

View File

@@ -13,8 +13,10 @@ BUILDDIR ?= build
builddir_docker := $(BUILDDIR)/docker builddir_docker := $(BUILDDIR)/docker
docker_container_name := "bemanitools-build" docker_build_container_name := "bemanitools-build"
docker_image_name := "bemanitools-build:latest" docker_build_image_name := "bemanitools-build:latest"
docker_dev_container_name := "bemanitools-dev"
docker_dev_image_name := "bemanitools-dev:latest"
depdir := $(BUILDDIR)/dep depdir := $(BUILDDIR)/dep
objdir := $(BUILDDIR)/obj objdir := $(BUILDDIR)/obj
@@ -41,6 +43,7 @@ FORCE:
.PHONY: \ .PHONY: \
build-docker \ build-docker \
dev-docker \
clean \ clean \
code-format \ code-format \
doc-format \ doc-format \
@@ -89,21 +92,38 @@ version:
$(V)echo "$(gitrev)" > version $(V)echo "$(gitrev)" > version
build-docker: build-docker:
$(V)docker rm -f $(docker_container_name) 2> /dev/null || true $(V)docker rm -f $(docker_build_container_name) 2> /dev/null || true
$(V)docker \ $(V)docker \
build \ build \
-t $(docker_image_name) \ -t $(docker_build_image_name) \
-f Dockerfile \ -f Dockerfile.build \
. .
$(V)docker \ $(V)docker \
run \ run \
--volume $(shell pwd):/bemanitools \ --volume $(shell pwd):/bemanitools \
--name $(docker_container_name) \ --name $(docker_build_container_name) \
$(docker_image_name) $(docker_build_image_name)
dev-docker:
$(V)docker rm -f $(docker_dev_container_name) 2> /dev/null || true
$(V)docker \
build \
-t $(docker_dev_image_name) \
-f Dockerfile.dev \
.
$(V)docker \
run \
--interactive \
--tty \
--volume $(shell pwd):/bemanitools \
--name $(docker_dev_container_name) \
$(docker_dev_image_name)
clean-docker: clean-docker:
$(V)docker rm -f $(docker_container_name) || true $(V)docker rm -f $(docker_dev_container_name) || true
$(V)docker image rm -f $(docker_image_name) || true $(V)docker image rm -f $(docker_dev_image_name) || true
$(V)docker rm -f $(docker_build_container_name) || true
$(V)docker image rm -f $(docker_build_image_name) || true
$(V)rm -rf $(BUILDDIR) $(V)rm -rf $(BUILDDIR)
# #

View File

@@ -100,8 +100,7 @@ include src/main/bstio/Module.mk
include src/main/camhook/Module.mk include src/main/camhook/Module.mk
include src/main/cconfig/Module.mk include src/main/cconfig/Module.mk
include src/main/config/Module.mk include src/main/config/Module.mk
include src/main/d3d9-frame-graph-hook/Module.mk include src/main/core/Module.mk
include src/main/d3d9-monitor-check/Module.mk
include src/main/d3d9-util/Module.mk include src/main/d3d9-util/Module.mk
include src/main/d3d9exhook/Module.mk include src/main/d3d9exhook/Module.mk
include src/main/ddrhook-util/Module.mk include src/main/ddrhook-util/Module.mk
@@ -234,9 +233,6 @@ $(zipdir)/tools.zip: \
build/bin/indep-32/ezusb2-dbg-hook.dll \ build/bin/indep-32/ezusb2-dbg-hook.dll \
build/bin/indep-32/ezusb2-tool.exe \ build/bin/indep-32/ezusb2-tool.exe \
build/bin/indep-32/ezusb-tool.exe \ build/bin/indep-32/ezusb-tool.exe \
build/bin/indep-32/nvgpu.exe \
build/bin/indep-32/d3d9-frame-graph-hook.dll \
build/bin/indep-32/d3d9-monitor-check.exe \
| $(zipdir)/ | $(zipdir)/
$(V)echo ... $@ $(V)echo ... $@
$(V)zip -j $@ $^ $(V)zip -j $@ $^
@@ -251,9 +247,6 @@ $(zipdir)/tools-x64.zip: \
build/bin/indep-64/iidx-ezusb2-exit-hook.dll \ build/bin/indep-64/iidx-ezusb2-exit-hook.dll \
build/bin/indep-64/jbiotest.exe \ build/bin/indep-64/jbiotest.exe \
build/bin/indep-64/mempatch-hook.dll \ build/bin/indep-64/mempatch-hook.dll \
build/bin/indep-64/nvgpu.exe \
build/bin/indep-64/d3d9-frame-graph-hook.dll \
build/bin/indep-64/d3d9-monitor-check.exe \
| $(zipdir)/ | $(zipdir)/
$(V)echo ... $@ $(V)echo ... $@
$(V)zip -j $@ $^ $(V)zip -j $@ $^
@@ -718,6 +711,8 @@ $(zipdir)/ddr-14-to-18.zip: \
build/bin/indep-32/eamio.dll \ build/bin/indep-32/eamio.dll \
build/bin/indep-32/geninput.dll \ build/bin/indep-32/geninput.dll \
dist/ddr/config.bat \ dist/ddr/config.bat \
dist/ddr/gamestart-17.bat \
dist/ddr/gamestart-18.bat \
dist/ddr/gamestart-14.bat \ dist/ddr/gamestart-14.bat \
dist/ddr/gamestart-15.bat \ dist/ddr/gamestart-15.bat \
dist/ddr/gamestart-16.bat \ dist/ddr/gamestart-16.bat \
@@ -736,6 +731,8 @@ $(zipdir)/ddr-16-to-18-x64.zip: \
build/bin/indep-64/eamio.dll \ build/bin/indep-64/eamio.dll \
build/bin/indep-64/geninput.dll \ build/bin/indep-64/geninput.dll \
dist/ddr/config.bat \ dist/ddr/config.bat \
dist/ddr/gamestart-17.bat \
dist/ddr/gamestart-18.bat \
dist/ddr/gamestart-16.bat \ dist/ddr/gamestart-16.bat \
dist/ddr/gamestart-17.bat \ dist/ddr/gamestart-17.bat \
dist/ddr/gamestart-18.bat \ dist/ddr/gamestart-18.bat \

View File

@@ -119,8 +119,6 @@ The following games are supported with their corresponding hook-libraries.
- [extiotest](doc/tools/extiotest.md) - [extiotest](doc/tools/extiotest.md)
- [aciotest](doc/tools/aciotest.md): Command line tool to quickly test ACIO devices - [aciotest](doc/tools/aciotest.md): Command line tool to quickly test ACIO devices
- config: UI input/output configuration tool when using the default bemanitools API (geninput) - config: UI input/output configuration tool when using the default bemanitools API (geninput)
- [d3d9-monitor-check](doc/tools/d3d9-monitor-check.md): Command line tool to check the monitor refresh rate of the
current GPU + monitor configuration
- ir-beat-patch-9/10: Patch the IR beat phase on IIDX 9 and 10 - ir-beat-patch-9/10: Patch the IR beat phase on IIDX 9 and 10
- [mempatch-hook](doc/tools/mempatch-hook.md): Patch raw memory locations in the target process - [mempatch-hook](doc/tools/mempatch-hook.md): Patch raw memory locations in the target process
based on the provided configuration based on the provided configuration

View File

@@ -1,27 +0,0 @@
# D3D9 Monitor Check
A separate application to run the infamous IIDX “monitor check” without having to run the actual
game. The tool can be used to test measure the current avg. monitor refresh rate or debug/check if
that value is fluctuating for some reason.
The final avg. value that is provided at the end of the test can be used as input for other tooling
or settings (e.g. patching charts to a different refresh rate on older games with bemanitools).
Simply run the tool without any arguments to get a full synopsis with usage instructions.
## "Accuracy" remarks
The tool has been tested on an actual cabinet with `nvgpu` setting different custom timings. The
accuracy seems to be even higher than what IIDXs monitor check is actually showing. For example,
with a custom timing of 59.900 hz, this tool yields fairly accurate and stable avg. 59.902 hz.
The monitor check of IIDX 29 shows results of 59.8981 hz to 59.8997 hz on screen. As these are the
only visible values to the user, determining a specific (avg.) value that can be used as input for
other tooling or settings (e.g. patching charts to a different refresh rate on older games with
bemanitools) is difficult. This doesn't mean that the game's monitor checks are actually
inaccurate or wrong. Modern games with a built-in monitor check (starting IIDX 20) are syncing up
fine and don't need any further patching or modifications.
For older games, picking a value that is not as close as possible to an accurate avg. value can
easily lead to issues with sync. So it's recommended to use the d3d9-monitor-check tool to get the
most accurate value.

View File

@@ -220,6 +220,9 @@ void property_file_write(struct property *prop, const char *path);
int property_set_flag(struct property *prop, int flags, int mask); int property_set_flag(struct property *prop, int flags, int mask);
void property_destroy(struct property *prop); void property_destroy(struct property *prop);
avs_error property_get_error(struct property *prop);
void property_clear_error(struct property *prop);
int property_psmap_import( int property_psmap_import(
struct property *prop, struct property *prop,
struct property_node *root, struct property_node *root,

View File

@@ -25,6 +25,8 @@ EXPORTS
property_destroy property_destroy
property_file_write property_file_write
property_insert_read property_insert_read
property_clear_error
property_get_error
property_mem_write property_mem_write
property_read_query_memsize property_read_query_memsize
property_search property_search

View File

@@ -28,6 +28,8 @@ EXPORTS
property_destroy property_destroy
property_file_write property_file_write
property_insert_read property_insert_read
property_clear_error
property_get_error
property_mem_write property_mem_write
property_read_query_memsize property_read_query_memsize
property_search property_search

View File

@@ -26,6 +26,8 @@ EXPORTS
property_desc_to_buffer @246 NONAME property_desc_to_buffer @246 NONAME
property_destroy @247 NONAME property_destroy @247 NONAME
property_insert_read @255 NONAME property_insert_read @255 NONAME
property_clear_error @573 NONAME
property_get_error @573 NONAME
property_node_create @266 NONAME property_node_create @266 NONAME
property_node_datasize @267 NONAME property_node_datasize @267 NONAME
property_node_name @274 NONAME property_node_name @274 NONAME

View File

@@ -25,6 +25,8 @@ EXPORTS
property_desc_to_buffer @201 NONAME property_desc_to_buffer @201 NONAME
property_destroy @264 NONAME property_destroy @264 NONAME
property_insert_read @23 NONAME property_insert_read @23 NONAME
property_clear_error @573 NONAME
property_get_error @573 NONAME
property_node_create @316 NONAME property_node_create @316 NONAME
property_node_datasize @249 NONAME property_node_datasize @249 NONAME
property_node_name @255 NONAME property_node_name @255 NONAME

View File

@@ -25,6 +25,8 @@ EXPORTS
property_desc_to_buffer @201 NONAME == XC058ba50000cd property_desc_to_buffer @201 NONAME == XC058ba50000cd
property_destroy @264 NONAME == XC058ba500010f property_destroy @264 NONAME == XC058ba500010f
property_insert_read @23 NONAME == XC058ba5000016 property_insert_read @23 NONAME == XC058ba5000016
property_clear_error @573 NONAME
property_get_error @573 NONAME
property_node_create @316 NONAME == XC058ba5000143 property_node_create @316 NONAME == XC058ba5000143
property_node_datasize @249 NONAME == XC058ba5000100 property_node_datasize @249 NONAME == XC058ba5000100
property_node_name @255 NONAME == XC058ba5000106 property_node_name @255 NONAME == XC058ba5000106

View File

@@ -24,6 +24,8 @@ EXPORTS
property_desc_to_buffer @131 NONAME property_desc_to_buffer @131 NONAME
property_destroy @130 NONAME property_destroy @130 NONAME
property_insert_read @133 NONAME property_insert_read @133 NONAME
property_clear_error @573 NONAME
property_get_error @573 NONAME
property_node_name @573 NONAME == property_node_name @573 NONAME ==
property_node_read @573 NONAME == property_node_read @573 NONAME ==
property_node_remove @148 NONAME property_node_remove @148 NONAME

View File

@@ -26,6 +26,8 @@ EXPORTS
property_desc_to_buffer @129 NONAME property_desc_to_buffer @129 NONAME
property_destroy @128 NONAME property_destroy @128 NONAME
property_insert_read @131 NONAME property_insert_read @131 NONAME
property_clear_error @573 NONAME
property_get_error @573 NONAME
property_node_create @145 NONAME property_node_create @145 NONAME
property_node_name @150 NONAME property_node_name @150 NONAME
property_node_read @154 NONAME == XCd229cc0000f3 property_node_read @154 NONAME == XCd229cc0000f3

View File

@@ -19,6 +19,8 @@ EXPORTS
property_destroy @125 NONAME property_destroy @125 NONAME
property_desc_to_buffer @126 NONAME property_desc_to_buffer @126 NONAME
property_insert_read @128 NONAME property_insert_read @128 NONAME
property_clear_error @573 NONAME
property_get_error @573 NONAME
property_search @141 NONAME property_search @141 NONAME
property_node_create @142 NONAME property_node_create @142 NONAME
property_node_name @147 NONAME == XCnbrep7000092 property_node_name @147 NONAME == XCnbrep7000092

View File

@@ -19,6 +19,8 @@ EXPORTS
property_destroy @146 NONAME property_destroy @146 NONAME
property_desc_to_buffer @147 NONAME property_desc_to_buffer @147 NONAME
property_insert_read @149 NONAME property_insert_read @149 NONAME
property_clear_error @158 NONAME == XCnbrep700009d
property_get_error @159 NONAME == XCnbrep700009e
property_search @162 NONAME property_search @162 NONAME
property_node_create @163 NONAME property_node_create @163 NONAME
property_node_name @168 NONAME == XCnbrep70000a7 property_node_name @168 NONAME == XCnbrep70000a7

View File

@@ -21,6 +21,8 @@ EXPORTS
property_destroy @146 NONAME property_destroy @146 NONAME
property_desc_to_buffer @147 NONAME property_desc_to_buffer @147 NONAME
property_insert_read @149 NONAME property_insert_read @149 NONAME
property_clear_error @158 NONAME == XCgsqzn000009d
property_get_error @159 NONAME == XCgsqzn000009e
property_search @162 NONAME property_search @162 NONAME
property_node_create @163 NONAME property_node_create @163 NONAME
property_node_name @168 NONAME == XCgsqzn00000a7 property_node_name @168 NONAME == XCgsqzn00000a7

View File

@@ -25,6 +25,8 @@ EXPORTS
property_destroy property_destroy
property_file_write property_file_write
property_insert_read property_insert_read
property_clear_error
property_get_error
property_mem_write property_mem_write
property_read_query_memsize property_read_query_memsize
property_search property_search

View File

@@ -26,6 +26,8 @@ EXPORTS
property_desc_to_buffer @129 NONAME property_desc_to_buffer @129 NONAME
property_destroy @128 NONAME property_destroy @128 NONAME
property_insert_read @131 NONAME property_insert_read @131 NONAME
property_clear_error @573 NONAME
property_get_error @573 NONAME
property_node_create @145 NONAME property_node_create @145 NONAME
property_node_name @150 NONAME property_node_name @150 NONAME
property_node_read @154 NONAME == XCd229cc0000f3 property_node_read @154 NONAME == XCd229cc0000f3

View File

@@ -26,6 +26,8 @@ EXPORTS
property_desc_to_buffer @129 NONAME property_desc_to_buffer @129 NONAME
property_destroy @128 NONAME property_destroy @128 NONAME
property_insert_read @131 NONAME property_insert_read @131 NONAME
property_clear_error @573 NONAME
property_get_error @573 NONAME
property_node_create @145 NONAME property_node_create @145 NONAME
property_node_name @573 NONAME == property_node_name @573 NONAME ==
property_node_read @573 NONAME == property_node_read @573 NONAME ==

View File

@@ -19,6 +19,8 @@ EXPORTS
property_destroy @125 NONAME property_destroy @125 NONAME
property_desc_to_buffer @126 NONAME property_desc_to_buffer @126 NONAME
property_insert_read @128 NONAME property_insert_read @128 NONAME
property_clear_error @573 NONAME
property_get_error @573 NONAME
property_search @141 NONAME property_search @141 NONAME
property_node_create @142 NONAME property_node_create @142 NONAME
property_node_name @147 NONAME == XCnbrep7000092 property_node_name @147 NONAME == XCnbrep7000092

View File

@@ -19,12 +19,14 @@ EXPORTS
property_destroy @146 NONAME property_destroy @146 NONAME
property_desc_to_buffer @147 NONAME property_desc_to_buffer @147 NONAME
property_insert_read @149 NONAME property_insert_read @149 NONAME
property_clear_error @158 NONAME == XCnbrep700009d
property_get_error @159 NONAME == XCnbrep700009e
property_search @162 NONAME property_search @162 NONAME
property_node_create @163 NONAME property_node_create @163 NONAME
property_node_name @168 NONAME == XCnbrep70000a7 property_node_name @168 NONAME == XCnbrep70000a7
property_node_remove @164 NONAME property_node_remove @164 NONAME
property_node_type @169 NONAME == XCnbrep70000a8 property_node_type @169 NONAME == XCnbrep70000a8
property_node_clone @165 NONAME property_node_clone @165 NONAME == XCnbrep70000a4
property_node_traversal @167 NONAME property_node_traversal @167 NONAME
property_node_refdata @166 NONAME == XCnbrep70000a5 property_node_refdata @166 NONAME == XCnbrep70000a5
property_node_datasize @171 NONAME == XCnbrep70000aa property_node_datasize @171 NONAME == XCnbrep70000aa

View File

@@ -21,6 +21,8 @@ EXPORTS
property_destroy @146 NONAME property_destroy @146 NONAME
property_desc_to_buffer @147 NONAME property_desc_to_buffer @147 NONAME
property_insert_read @149 NONAME property_insert_read @149 NONAME
property_clear_error @158 NONAME == XCgsqzn000009d
property_get_error @159 NONAME == XCgsqzn000009e
property_search @162 NONAME property_search @162 NONAME
property_node_create @163 NONAME property_node_create @163 NONAME
property_node_name @168 NONAME == XCgsqzn00000a7 property_node_name @168 NONAME == XCgsqzn00000a7

View File

@@ -3,4 +3,5 @@ libs += avs-util
libs_avs-util := \ libs_avs-util := \
src_avs-util := \ src_avs-util := \
core-interop.c \
error.c \ error.c \

View File

@@ -0,0 +1,16 @@
#include "core/log.h"
#include "core/thread.h"
#include "imports/avs.h"
void avs_util_core_interop_log_avs_impl_set()
{
core_log_impl_set(
log_body_misc, log_body_info, log_body_warning, log_body_fatal);
}
void avs_util_core_interop_thread_avs_impl_set()
{
core_thread_impl_set(
avs_thread_create, avs_thread_join, avs_thread_destroy);
}

View File

@@ -0,0 +1,7 @@
#ifndef AVS_UTIL_CORE_INTEROP_H
#define AVS_UTIL_CORE_INTEROP_H
void avs_util_core_interop_log_avs_impl_set();
void avs_util_core_interop_thread_avs_impl_set();
#endif

View File

@@ -96,4 +96,14 @@ const char *avs_util_error_str(avs_error error)
} }
return avs_util_error_unknown; return avs_util_error_unknown;
}
const char *avs_util_property_error_get_and_clear(struct property *prop)
{
avs_error error;
error = property_get_error(prop);
property_clear_error(prop);
return avs_util_error_str(error);
} }

View File

@@ -5,4 +5,6 @@
const char *avs_util_error_str(avs_error error); const char *avs_util_error_str(avs_error error);
#endif const char *avs_util_property_error_get_and_clear(struct property *prop);
#endif

20
src/main/core/Module.mk Normal file
View File

@@ -0,0 +1,20 @@
libs += core
libs_core := \
util \
src_core := \
log-bt-ext.c \
log-bt.c \
log-sink-async.c \
log-sink-debug.c \
log-sink-file.c \
log-sink-list.c \
log-sink-mutex.c \
log-sink-null.c \
log-sink-std.c \
log.c \
thread-crt-ext.c \
thread-crt.c \
thread.c \

View File

@@ -0,0 +1,67 @@
#include <stdbool.h>
#include "core/log-bt.h"
#include "core/log-sink-debug.h"
#include "core/log-sink-file.h"
#include "core/log-sink-list.h"
#include "core/log-sink-mutex.h"
#include "core/log-sink-std.h"
#include "core/log.h"
void core_log_bt_ext_impl_set()
{
core_log_impl_set(
core_log_bt_log_misc,
core_log_bt_log_info,
core_log_bt_log_warning,
core_log_bt_log_fatal);
}
void core_log_bt_ext_init_with_stdout()
{
struct core_log_sink sink;
core_log_sink_std_out_open(true, &sink);
core_log_bt_init(&sink);
}
void core_log_bt_ext_init_with_stderr()
{
struct core_log_sink sink;
core_log_sink_std_err_open(true, &sink);
core_log_bt_init(&sink);
}
void core_log_bt_ext_init_with_debug()
{
struct core_log_sink sink;
core_log_sink_debug_open(&sink);
core_log_bt_init(&sink);
}
void core_log_bt_ext_init_with_file(
const char *path, bool append, bool rotate, uint8_t max_rotations)
{
struct core_log_sink sink;
core_log_sink_file_open(path, append, rotate, max_rotations, &sink);
core_log_bt_init(&sink);
}
void core_log_bt_ext_init_with_stdout_and_file(
const char *path, bool append, bool rotate, uint8_t max_rotations)
{
struct core_log_sink sinks[2];
struct core_log_sink sink_composed;
struct core_log_sink sink_mutex;
core_log_sink_std_out_open(true, &sinks[0]);
core_log_sink_file_open(path, append, rotate, max_rotations, &sinks[1]);
core_log_sink_list_open(sinks, 2, &sink_composed);
core_log_sink_mutex_open(&sink_composed, &sink_mutex);
core_log_bt_init(&sink_mutex);
}

View File

@@ -0,0 +1,59 @@
#ifndef CORE_LOG_BT_EXT_H
#define CORE_LOG_BT_EXT_H
#include <stdbool.h>
#include <stdint.h>
/**
* Set the current thread API implementation to use the bemanitools log
* implementation
*/
void core_log_bt_ext_impl_set();
/**
* Helper to setup the bemanitools log implementation with a stdout sink.
*/
void core_log_bt_ext_init_with_stdout();
/**
* Helper to setup the bemanitools log implementation with a stderr sink.
*/
void core_log_bt_ext_init_with_stderr();
/**
* Helper to setup the bemanitools log implementation with a OutputDebugStr
* sink.
*/
void core_log_bt_ext_init_with_debug();
/**
* Helper to setup the bemanitools log implementation with a file sink
*
* @param path Path to the log file to write the log output to
* @param append If true, then append to an existing file, false to overwrite
* any existing file
* @param rotate If true, rotates an existing log file and creates a new one
* for this session
* @param max_rotations Max number of rotations for the log files
*/
void core_log_bt_ext_init_with_file(
const char *path, bool append, bool rotate, uint8_t max_rotations);
/**
* Helper to setup the bemanitools log implementation with a stdout and file
* sink
*
* Important: This combined sink is guarded by a mutex to avoid data races on
* logging to two different sinks.
*
* @param path Path to the log file to write the log output to
* @param append If true, then append to an existing file, false to overwrite
* any existing file
* @param rotate If true, rotates an existing log file and creates a new one
* for this session
* @param max_rotations Max number of rotations for the log files
*/
void core_log_bt_ext_init_with_stdout_and_file(
const char *path, bool append, bool rotate, uint8_t max_rotations);
#endif

129
src/main/core/log-bt.c Normal file
View File

@@ -0,0 +1,129 @@
#include <stdarg.h>
#include <stdlib.h>
#include <time.h>
#include "core/log-bt.h"
#include "core/log-sink.h"
#include "core/log.h"
#include "util/mem.h"
#include "util/str.h"
static enum core_log_bt_log_level _core_log_bt_log_level;
static struct core_log_sink *_core_log_bt_sink;
static void _core_log_bt_vformat_write(
enum core_log_bt_log_level level,
const char *module,
const char *fmt,
va_list ap)
{
static const char chars[] = "FFWIM";
char timestamp[64];
/* 64k so we can log data dumps of rs232 without crashing */
char msg[65536];
char line[65536];
int result;
time_t curtime;
struct tm *tm;
curtime = 0;
tm = NULL;
curtime = time(NULL);
tm = localtime(&curtime);
strftime(timestamp, sizeof(timestamp), "[%Y/%m/%d %H:%M:%S]", tm);
str_vformat(msg, sizeof(msg), fmt, ap);
result = str_format(
line,
sizeof(line),
"%s %c:%s: %s\n",
timestamp,
chars[level],
module,
msg);
_core_log_bt_sink->write(_core_log_bt_sink->ctx, line, result);
}
void core_log_bt_init(const struct core_log_sink *sink)
{
if (sink == NULL) {
abort();
}
_core_log_bt_sink = xmalloc(sizeof(struct core_log_sink));
memcpy(_core_log_bt_sink, sink, sizeof(struct core_log_sink));
_core_log_bt_log_level = CORE_LOG_BT_LOG_LEVEL_OFF;
}
void core_log_bt_level_set(enum core_log_bt_log_level level)
{
_core_log_bt_log_level = level;
}
void core_log_bt_fini()
{
log_assert(_core_log_bt_sink);
_core_log_bt_sink->close(_core_log_bt_sink->ctx);
free(_core_log_bt_sink);
}
void core_log_bt_log_fatal(const char *module, const char *fmt, ...)
{
va_list ap;
if (_core_log_bt_log_level >= CORE_LOG_BT_LOG_LEVEL_FATAL) {
va_start(ap, fmt);
_core_log_bt_vformat_write(
CORE_LOG_BT_LOG_LEVEL_FATAL, module, fmt, ap);
va_end(ap);
}
}
void core_log_bt_log_warning(const char *module, const char *fmt, ...)
{
va_list ap;
if (_core_log_bt_log_level >= CORE_LOG_BT_LOG_LEVEL_WARNING) {
va_start(ap, fmt);
_core_log_bt_vformat_write(
CORE_LOG_BT_LOG_LEVEL_WARNING, module, fmt, ap);
va_end(ap);
}
}
void core_log_bt_log_info(const char *module, const char *fmt, ...)
{
va_list ap;
if (_core_log_bt_log_level >= CORE_LOG_BT_LOG_LEVEL_INFO) {
va_start(ap, fmt);
_core_log_bt_vformat_write(CORE_LOG_BT_LOG_LEVEL_INFO, module, fmt, ap);
va_end(ap);
}
}
void core_log_bt_log_misc(const char *module, const char *fmt, ...)
{
va_list ap;
if (_core_log_bt_log_level >= CORE_LOG_BT_LOG_LEVEL_MISC) {
va_start(ap, fmt);
_core_log_bt_vformat_write(CORE_LOG_BT_LOG_LEVEL_MISC, module, fmt, ap);
va_end(ap);
}
}
void core_log_bt_direct_sink_write(const char *chars, size_t nchars)
{
_core_log_bt_sink->write(_core_log_bt_sink->ctx, chars, nchars);
}

87
src/main/core/log-bt.h Normal file
View File

@@ -0,0 +1,87 @@
#ifndef CORE_LOG_BT_H
#define CORE_LOG_BT_H
#include "core/log-sink.h"
/**
* Log API implementation for games/applications without AVS
*/
enum core_log_bt_log_level {
CORE_LOG_BT_LOG_LEVEL_OFF = 0,
CORE_LOG_BT_LOG_LEVEL_FATAL = 1,
CORE_LOG_BT_LOG_LEVEL_WARNING = 2,
CORE_LOG_BT_LOG_LEVEL_INFO = 3,
CORE_LOG_BT_LOG_LEVEL_MISC = 4,
};
/**
* Initialize the logging backend
*
* This must be called as early as possible in your application to setup
* a logging sink according to your needs. Until this is finished, no
* log output is available.
*
* By default, logging is turned off entirely and must be enabled by setting
* a desired logging level explicitly.
*
* @param sink Pointer to a log sink implementation. The caller owns the memory
* of this.
*/
void core_log_bt_init(const struct core_log_sink *sink);
/**
* Set the current logging level. This can be changed at any given time, e.g.
* to increase/decrease verbosity.
*
* @param level The logging level to set.
*/
void core_log_bt_level_set(enum core_log_bt_log_level level);
/**
* Cleanup the logging backend.
*
* Ensure to call this on application exit and cleanup.
*/
void core_log_bt_fini();
/**
* Implementation of the log API.
*/
void core_log_bt_log_fatal(const char *module, const char *fmt, ...);
/**
* Implementation of the log API.
*/
void core_log_bt_log_warning(const char *module, const char *fmt, ...);
/**
* Implementation of the log API.
*/
void core_log_bt_log_info(const char *module, const char *fmt, ...);
/**
* Implementation of the log API.
*/
void core_log_bt_log_misc(const char *module, const char *fmt, ...);
/**
* Allow AVS to by-pass the core log API/engine.
*
* This function must only be called by AVS in an appropriate log callback
* function that is passed to avs_boot.
*
* AVS has it's own logging engine and manages aspects such as async logging,
* log levels and decorating log messages.
*
* Thus, proper interoperability only requires the writer/sink part to be shared
* with AVS.
*
* @param chars Buffer with text data to write to the configured sinks. The
* buffer might contain several log messages separated by newline
* characters.
* @param nchars Number of chars to write to the sink.
*/
void core_log_bt_direct_sink_write(const char *chars, size_t nchars);
#endif

View File

@@ -0,0 +1,23 @@
#include <stdlib.h>
#include "core/log-sink.h"
static void
_core_log_sink_file_write(void *ctx, const char *chars, size_t nchars)
{
// TODO
}
static void _core_log_sink_file_close(void *ctx)
{
// TODO
}
void core_log_sink_async_open(struct core_log_sink *sink)
{
// TODO
sink->ctx = NULL;
sink->write = _core_log_sink_file_write;
sink->close = _core_log_sink_file_close;
}

View File

@@ -0,0 +1,19 @@
#ifndef CORE_LOG_SINK_ASYNC_H
#define CORE_LOG_SINK_ASYNC_H
#include <stdint.h>
#include <stdlib.h>
#include "core/log-sink.h"
/**
* Open a async log sink
*
* The sink passes data to log to a separate thread which executes the actual
* logging of the data.
*
* @param sink Pointer to allocated memory that receives the opened sink
*/
void core_log_sink_async_open(struct core_log_sink *sink);
#endif

View File

@@ -0,0 +1,23 @@
#include <debugapi.h>
#include <stdlib.h>
#include "core/log-sink.h"
static void
_core_log_sink_debug_write(void *ctx, const char *chars, size_t nchars)
{
OutputDebugStringA(chars);
}
static void _core_log_sink_debug_close(void *ctx)
{
// noop
}
void core_log_sink_debug_open(struct core_log_sink *sink)
{
sink->ctx = NULL;
sink->write = _core_log_sink_debug_write;
sink->close = _core_log_sink_debug_close;
}

View File

@@ -0,0 +1,15 @@
#ifndef CORE_LOG_SINK_DEBUG_H
#define CORE_LOG_SINK_DEBUG_H
#include <stdlib.h>
#include "core/log-sink.h"
/**
* Open a log sink that uses OutputDebugStr
*
* @param sink Pointer to allocated memory that receives the opened sink
*/
void core_log_sink_debug_open(struct core_log_sink *sink);
#endif

View File

@@ -0,0 +1,92 @@
#include <windows.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include "core/log-sink.h"
#include "util/fs.h"
#include "util/str.h"
static void _core_log_sink_file_rotate(const char *path, uint8_t max_rotations)
{
uint8_t i;
char rotate_file[MAX_PATH];
char rotate_file_next[MAX_PATH];
char version[8];
char version_next[8];
for (i = max_rotations; i > 0; i++) {
str_cpy(rotate_file, sizeof(rotate_file), path);
str_cpy(rotate_file_next, sizeof(rotate_file_next), path);
if (i - 1 != 0) {
sprintf(version, ".%d", i);
} else {
memset(version, 0, sizeof(version));
}
sprintf(version_next, ".%d", i);
str_cat(rotate_file, sizeof(rotate_file), version);
str_cat(rotate_file_next, sizeof(rotate_file_next), version_next);
if (path_exists(rotate_file)) {
CopyFile(rotate_file, rotate_file_next, FALSE);
}
}
}
static void
_core_log_sink_file_write(void *ctx, const char *chars, size_t nchars)
{
FILE *file;
file = (FILE *) ctx;
fwrite(chars, 1, nchars, file);
}
static void _core_log_sink_file_close(void *ctx)
{
FILE *file;
file = (FILE *) ctx;
fflush(file);
fclose(file);
}
void core_log_sink_file_open(
const char *path,
bool append,
bool rotate,
uint8_t max_rotations,
struct core_log_sink *sink)
{
FILE *file;
if (rotate) {
_core_log_sink_file_rotate(path, max_rotations);
// Appending doesn't matter when file is rotated anyway
file = fopen(path, "w+");
} else {
if (append) {
file = fopen(path, "a+");
} else {
file = fopen(path, "w+");
}
}
if (!file) {
printf("Cannot open log file: %s", path);
abort();
}
sink->ctx = (void *) file;
sink->write = _core_log_sink_file_write;
sink->close = _core_log_sink_file_close;
}

View File

@@ -0,0 +1,28 @@
#ifndef CORE_LOG_SINK_FILE_H
#define CORE_LOG_SINK_FILE_H
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include "core/log-sink.h"
/**
* Open a log sink writing data to a file
*
* @param path Path to the log file to write the log output to
* @param append If true, then append to an existing file, false to overwrite
* any existing file
* @param rotate If true, rotates an existing log file and creates a new one
* for this session
* @param max_rotations Max number of rotations for the log files
* @param sink Pointer to allocated memory that receives the opened sink
*/
void core_log_sink_file_open(
const char *path,
bool append,
bool rotate,
uint8_t max_rotations,
struct core_log_sink *sink);
#endif

View File

@@ -0,0 +1,66 @@
#include <stdint.h>
#include <stdlib.h>
#include "core/log-sink-list.h"
#include "core/log-sink.h"
#include "util/mem.h"
#define MAX_SINKS 8
struct core_log_sink_list {
struct core_log_sink entries[MAX_SINKS];
uint8_t num;
};
static void
_core_log_sink_list_write(void *ctx, const char *chars, size_t nchars)
{
struct core_log_sink_list *sink_list;
int i;
sink_list = (struct core_log_sink_list *) ctx;
for (i = 0; i < sink_list->num; i++) {
sink_list->entries[i].write(sink_list->entries[i].ctx, chars, nchars);
}
}
static void _core_log_sink_list_close(void *ctx)
{
struct core_log_sink_list *sink_list;
int i;
sink_list = (struct core_log_sink_list *) ctx;
for (i = 0; i < sink_list->num; i++) {
sink_list->entries[i].close(sink_list->entries[i].ctx);
}
free(sink_list);
}
void core_log_sink_list_open(
const struct core_log_sink *entry, uint8_t num, struct core_log_sink *sink)
{
struct core_log_sink_list *sink_list;
int i;
if (num > MAX_SINKS) {
abort();
}
sink_list = xmalloc(sizeof(struct core_log_sink_list));
for (i = 0; i < num; i++) {
sink_list->entries[i].ctx = entry[i].ctx;
sink_list->entries[i].write = entry[i].write;
sink_list->entries[i].close = entry[i].close;
}
sink_list->num = num;
sink->ctx = (void *) sink_list;
sink->write = _core_log_sink_list_write;
sink->close = _core_log_sink_list_close;
}

View File

@@ -0,0 +1,24 @@
#ifndef CORE_LOG_SINK_LIST_H
#define CORE_LOG_SINK_LIST_H
#include <stdint.h>
#include <stdlib.h>
#include "core/log-sink.h"
/**
* Combine multiple log sinks into a list of sinks.
*
* Upon invoking a list sink, all sinks contained within the list are
* being invoked in the configured order.
*
* @param entry A pointer to allocated memory with a sequence of opened sinks
* that you want to add to the list. Ownership of these sinks
* is transferred, i.e. closing the list sink closes its children.
* @param num The number of elements in the sequence of opened sinks pointed to.
* @param sink Pointer to allocated memory that receives the opened sink
*/
void core_log_sink_list_open(
const struct core_log_sink *entry, uint8_t num, struct core_log_sink *sink);
#endif

View File

@@ -0,0 +1,53 @@
#include <windows.h>
#include <stdlib.h>
#include "core/log-sink.h"
#include "util/mem.h"
struct core_log_sink_mutex_ctx {
struct core_log_sink *child;
HANDLE mutex;
};
static void
_core_log_sink_mutex_write(void *ctx_, const char *chars, size_t nchars)
{
struct core_log_sink_mutex_ctx *ctx;
ctx = (struct core_log_sink_mutex_ctx *) ctx_;
WaitForSingleObject(ctx->mutex, INFINITE);
ctx->child->write(ctx->child->ctx, chars, nchars);
ReleaseMutex(ctx->mutex);
}
static void _core_log_sink_mutex_close(void *ctx_)
{
struct core_log_sink_mutex_ctx *ctx;
ctx = (struct core_log_sink_mutex_ctx *) ctx_;
CloseHandle(ctx->mutex);
ctx->child->close(ctx->child->ctx);
free(ctx);
}
void core_log_sink_mutex_open(
const struct core_log_sink *child_sink, struct core_log_sink *sink)
{
struct core_log_sink_mutex_ctx *ctx;
ctx = xmalloc(sizeof(struct core_log_sink_mutex_ctx));
memcpy(ctx->child, child_sink, sizeof(struct core_log_sink));
ctx->mutex = CreateMutex(NULL, FALSE, NULL);
sink->ctx = ctx;
sink->write = _core_log_sink_mutex_write;
sink->close = _core_log_sink_mutex_close;
}

View File

@@ -0,0 +1,21 @@
#ifndef CORE_LOG_SINK_MUTEX_H
#define CORE_LOG_SINK_MUTEX_H
#include <stdlib.h>
#include "core/log-sink.h"
/**
* Create a sink that surrounds another sink with a mutex.
*
* Use this to make other sink implementations thread-safe.
*
* @param child_sink Another opened sink to surround with the mutex. Ownership
* of the sink is transferred, i.e. closing the mutex sink
* also closes the wrapped child sink.
* @param sink Pointer to allocated memory that receives the opened sink
*/
void core_log_sink_mutex_open(
const struct core_log_sink *child_sink, struct core_log_sink *sink);
#endif

View File

@@ -0,0 +1,21 @@
#include <stdlib.h>
#include "core/log-sink.h"
static void
_core_log_sink_null_write(void *ctx, const char *chars, size_t nchars)
{
// noop
}
static void _core_log_sink_null_close(void *ctx)
{
// noop
}
void core_log_sink_null_open(struct core_log_sink *sink)
{
sink->ctx = NULL;
sink->write = _core_log_sink_null_write;
sink->close = _core_log_sink_null_close;
}

View File

@@ -0,0 +1,17 @@
#ifndef CORE_LOG_SINK_NULL_H
#define CORE_LOG_SINK_NULL_H
#include <stdlib.h>
#include "core/log-sink.h"
/**
* Create a null/dummy sink.
*
* Use this to disable any logging entirely.
*
* @param sink Pointer to allocated memory that receives the opened sink
*/
void core_log_sink_null_open(struct core_log_sink *sink);
#endif

View File

@@ -0,0 +1,193 @@
#include <windows.h>
#include <stdlib.h>
#include "core/log-sink.h"
#include "util/mem.h"
struct core_log_sink_std_ctx {
HANDLE handle;
bool color;
};
static char _core_log_sink_std_determine_color(const char *str)
{
/* Add some color to make spotting warnings/errors easier.
Based on debug output level identifier. */
/* Avoids colored output on strings like "Windows" */
if (str[1] != ':') {
return 15;
}
switch (str[0]) {
/* green */
case 'M':
return 10;
/* blue */
case 'I':
return 9;
/* yellow */
case 'W':
return 14;
/* red */
case 'F':
return 12;
/* default console color */
default:
return 15;
}
}
static size_t _core_log_sink_std_msg_coloring_len(const char *str)
{
// Expected format example: "I:boot: my log message"
const char *ptr;
size_t len;
int colon_count;
ptr = str;
len = 0;
colon_count = 0;
while (true) {
// End of string = invalid log format
if (*ptr == '\0') {
return 0;
}
if (*ptr == ':') {
colon_count++;
}
if (colon_count == 2) {
// Skip current colon, next char is a space
return len + 1;
}
len++;
ptr++;
}
return 0;
}
static void
_core_log_sink_std_write(void *ctx_, const char *chars, size_t nchars)
{
static const size_t timestamp_len = strlen("[----/--/-- --:--:--]");
struct core_log_sink_std_ctx *ctx;
char color;
size_t color_len;
size_t msg_len;
const char *msg_start;
const char *msg_end;
DWORD written;
DWORD write_pos;
ctx = (struct core_log_sink_std_ctx *) ctx_;
if (ctx->color) {
write_pos = 0;
// Support multiple buffered log messages, e.g. from the AVS logging
// engine
while (write_pos < nchars) {
// Expects the AVS timestamp format
msg_start = chars + timestamp_len + 1; // +1 is the space
color_len = _core_log_sink_std_msg_coloring_len(msg_start);
// Check if we could detect which part to color, otherwise just
// write the whole log message without any coloring logic
if (color_len > 0) {
color = _core_log_sink_std_determine_color(msg_start);
// Timestamp
WriteConsole(
ctx->handle, chars, timestamp_len + 1, &written, NULL);
write_pos += written;
chars += written;
// Log level + module colored
SetConsoleTextAttribute(ctx->handle, color);
WriteConsole(ctx->handle, chars, color_len, &written, NULL);
write_pos += written;
chars += written;
SetConsoleTextAttribute(ctx->handle, 15);
msg_end = strchr(chars, '\n');
if (msg_end != NULL) {
msg_len = msg_end - chars;
// Write \n as well
msg_len++;
// Write actual message non colored
WriteConsole(ctx->handle, chars, msg_len, &written, NULL);
write_pos += written;
chars += written;
} else {
WriteConsole(
ctx->handle, chars, nchars - write_pos, &written, NULL);
write_pos += written;
chars += written;
}
} else {
WriteConsole(
ctx->handle,
chars + write_pos,
nchars - write_pos,
&written,
NULL);
write_pos += written;
}
}
} else {
WriteConsole(ctx->handle, chars, nchars, &written, NULL);
}
}
static void _core_log_sink_std_close(void *ctx_)
{
struct core_log_sink_std_ctx *ctx;
ctx = (struct core_log_sink_std_ctx *) ctx_;
// Remark: Don't close the ctx->handle, see win API docs
free(ctx);
}
void core_log_sink_std_out_open(bool color, struct core_log_sink *sink)
{
struct core_log_sink_std_ctx *ctx;
ctx = xmalloc(sizeof(struct core_log_sink_std_ctx));
ctx->handle = GetStdHandle(STD_OUTPUT_HANDLE);
ctx->color = color;
sink->ctx = (void *) ctx;
sink->write = _core_log_sink_std_write;
sink->close = _core_log_sink_std_close;
}
void core_log_sink_std_err_open(bool color, struct core_log_sink *sink)
{
struct core_log_sink_std_ctx *ctx;
ctx = xmalloc(sizeof(struct core_log_sink_std_ctx));
ctx->handle = GetStdHandle(STD_ERROR_HANDLE);
ctx->color = color;
sink->ctx = (void *) ctx;
sink->write = _core_log_sink_std_write;
sink->close = _core_log_sink_std_close;
}

View File

@@ -0,0 +1,24 @@
#ifndef CORE_LOG_SINK_STD_H
#define CORE_LOG_SINK_STD_H
#include <stdlib.h>
#include "core/log-sink.h"
/**
* Create a sink that writes to stdout.
*
* @param color If true, messages are colored by log level.
* @param sink Pointer to allocated memory that receives the opened sink
*/
void core_log_sink_std_out_open(bool color, struct core_log_sink *sink);
/**
* Create a sink that writes to stderr.
*
* @param color If true, messages are colored by log level.
* @param sink Pointer to allocated memory that receives the opened sink
*/
void core_log_sink_std_err_open(bool color, struct core_log_sink *sink);
#endif

45
src/main/core/log-sink.h Normal file
View File

@@ -0,0 +1,45 @@
#ifndef CORE_LOG_SINK_H
#define CORE_LOG_SINK_H
#include <stdint.h>
/**
* Write function for a log sink implementation.
*
* Write the given data to your target output destination.
*
* @param ctx Context defined by the implementation when opening the sink.
* @param chars Buffer with text data to log. This can contain partial data of
* a single log line, a full log line terminated by a newline
* character or multiple log lines (each terminated by a newline
* character).
* @param nchars Number of characters to write.
*/
typedef void (*core_log_sink_write_t)(
void *ctx, const char *chars, size_t nchars);
/**
* Close your log sink and cleanup resources
*
* Depending on your implementation, you might want to flush any
* outstanding/buffered data.
*
* @param ctx Context defined by the implementation when opening the sink.
*/
typedef void (*core_log_sink_close_t)(void *ctx);
/**
* Log sink structure.
*
* This must be set-up and populated when opening your log sink implementation.
* The ctx field contains any arbitrary data that you need for your log sink
* to operate, e.g. a file handle, additional buffers etc. Make sure these
* resources are cleaned up upon closing the sink.
*/
struct core_log_sink {
void *ctx;
core_log_sink_write_t write;
core_log_sink_close_t close;
};
#endif

74
src/main/core/log.c Normal file
View File

@@ -0,0 +1,74 @@
#include <stdlib.h>
#include "core/log.h"
core_log_message_t _core_log_misc_impl;
core_log_message_t _core_log_info_impl;
core_log_message_t _core_log_warning_impl;
core_log_message_t _core_log_fatal_impl;
void core_log_impl_set(
core_log_message_t misc,
core_log_message_t info,
core_log_message_t warning,
core_log_message_t fatal)
{
if (misc == NULL || info == NULL || warning == NULL || fatal == NULL) {
abort();
}
_core_log_misc_impl = misc;
_core_log_info_impl = info;
_core_log_warning_impl = warning;
_core_log_fatal_impl = fatal;
}
void core_log_impl_assign(core_log_impl_set_t impl_set)
{
if (_core_log_misc_impl == NULL || _core_log_info_impl == NULL ||
_core_log_warning_impl == NULL || _core_log_fatal_impl == NULL) {
abort();
}
impl_set(
_core_log_misc_impl,
_core_log_info_impl,
_core_log_warning_impl,
_core_log_fatal_impl);
}
core_log_message_t core_log_misc_impl_get()
{
if (_core_log_misc_impl == NULL) {
abort();
}
return _core_log_misc_impl;
}
core_log_message_t core_log_info_impl_get()
{
if (_core_log_info_impl == NULL) {
abort();
}
return _core_log_info_impl;
}
core_log_message_t core_log_warning_impl_get()
{
if (_core_log_warning_impl == NULL) {
abort();
}
return _core_log_warning_impl;
}
core_log_message_t core_log_fatal_impl_get()
{
if (_core_log_fatal_impl == NULL) {
abort();
}
return _core_log_fatal_impl;
}

197
src/main/core/log.h Normal file
View File

@@ -0,0 +1,197 @@
#ifndef CORE_LOG_H
#define CORE_LOG_H
#include <stddef.h>
#include <stdlib.h>
#include "util/defs.h"
/**
* The core log API of bemanitools.
*
* To a large extent, this reflects the AVS logging API and allows for swapping
* out the backends with different implementations. Most games should have some
* version of the AVS API available while some (legacy) games do not. These
* can use a bemanitools private logging implementation by configuring it
* in the bootstrapping process.
*/
/* BUILD_MODULE is passed in as a command-line #define by the makefile */
#ifndef LOG_MODULE
#define LOG_MODULE STRINGIFY(BUILD_MODULE)
#endif
/**
* Log a message on misc level
*
* Always use this interface in your application which hides the currently
* configured implementation.
*
* The macro is required to make things work with varargs.
* The log message is only printed if the log level is set to misc
*
* @param fmt printf format string
* @param ... Additional arguments according to the specified arguments in the
* printf format string
*/
#define log_misc(...) _core_log_misc_impl(LOG_MODULE, __VA_ARGS__)
/**
* Log a message on info level
*
* Always use this interface in your application which hides the currently
* configured implementation.
*
* The macro is required to make things work with varargs.
* The log message is only printed if the log level is set to info or lower
*
* @param fmt printf format string
* @param ... Additional arguments according to the specified arguments in the
* printf format string
*/
#define log_info(...) _core_log_info_impl(LOG_MODULE, __VA_ARGS__)
/**
* Log a message on warning level
*
* Always use this interface in your application which hides the currently
* configured implementation.
*
* The macro is required to make things work with varargs.
* The log message is only printed if the log level is set to warning or lower
*
* @param fmt printf format string
* @param ... Additional arguments according to the specified arguments in the
* printf format string
*/
#define log_warning(...) _core_log_warning_impl(LOG_MODULE, __VA_ARGS__)
/**
* Log a message on fatal level
*
* Always use this interface in your application which hides the currently
* configured implementation.
*
* The macro is required to make things work with varargs.
* The log message is only printed if the log level is set to fatal.
*
* This call will also terminate the application.
*
* @param fmt printf format string
* @param ... Additional arguments according to the specified arguments in the
* printf format string
*/
#define log_fatal(...) \
do { \
_core_log_fatal_impl(LOG_MODULE, __VA_ARGS__); \
abort(); \
} while (0)
/**
* Log a message and terminate the application if given condition fails
*
* Always use this interface in your application which hides the currently
* configured implementation.
*
* The macro is required to make things work with varargs.
*
* @param x Condition to evaluate. If false, the application terminates
*/
#define log_assert(x) \
do { \
if (!(x)) { \
_core_log_fatal_impl( \
"assert", \
"%s:%d: function `%s'", \
__FILE__, \
__LINE__, \
__FUNCTION__); \
abort(); \
} \
} while (0)
/**
* Log a message in an exception handler
*
* Only use this function in an exception handler, e.g. for stack traces. It
* logs the message on fatal level but does not terminate.
*
* @param fmt printf format string
* @param ... Additional arguments according to the specified arguments in the
* printf format string
*/
#define log_exception_handler(...) \
_core_log_fatal_impl("exception", __VA_ARGS__)
typedef void (*core_log_message_t)(const char *module, const char *fmt, ...);
typedef void (*core_log_impl_set_t)(
core_log_message_t misc,
core_log_message_t info,
core_log_message_t warning,
core_log_message_t fatal);
/**
* Configure the log API implementations
*
* Advised to do this as early in your application/library module as possible
* as calls to the getter functions below will return the currently configured
* implementations.
*
* @param misc Pointer to a function implementing logging on misc level
* @param info Pointer to a function implementing logging on info level
* @param warning Pointer to a function implementing logging on warning level
* @param fatal Pointer to a function implementing logging on fatal level
*/
void core_log_impl_set(
core_log_message_t misc,
core_log_message_t info,
core_log_message_t warning,
core_log_message_t fatal);
/**
* Supporting function to inject/assign the currently set implementation
* with the given setter function.
*
* @param impl_set Setter function to call with the currently configured log
* function implementations
*/
void core_log_impl_assign(core_log_impl_set_t impl_set);
/**
* Get the currently configured implementation of the misc level log function
*
* @return Pointer to the currently configured implementation of the function
*/
core_log_message_t core_log_misc_impl_get();
/**
* Get the currently configured implementation of the info level log function
*
* @return Pointer to the currently configured implementation of the function
*/
core_log_message_t core_log_info_impl_get();
/**
* Get the currently configured implementation of the warning level log function
*
* @return Pointer to the currently configured implementation of the function
*/
core_log_message_t core_log_warning_impl_get();
/**
* Get the currently configured implementation of the fatal level log function
*
* @return Pointer to the currently configured implementation of the function
*/
core_log_message_t core_log_fatal_impl_get();
// Do not use these directly.
// These are only here to allow usage in the macros above.
extern core_log_message_t _core_log_misc_impl;
extern core_log_message_t _core_log_info_impl;
extern core_log_message_t _core_log_warning_impl;
extern core_log_message_t _core_log_fatal_impl;
#endif

View File

@@ -0,0 +1,8 @@
#include "core/thread-crt.h"
#include "core/thread.h"
void core_thread_crt_ext_impl_set()
{
core_thread_impl_set(
core_thread_crt_create, core_thread_crt_join, core_thread_crt_destroy);
}

View File

@@ -0,0 +1,9 @@
#ifndef CORE_THREAD_CRT_EXT_H
#define CORE_THREAD_CRT_EXT_H
/**
* Set the current thread API implementation to use the C runtime thread API
*/
void core_thread_crt_ext_impl_set();
#endif

View File

@@ -0,0 +1,62 @@
#include <process.h>
#include <windows.h>
#include <stddef.h>
#include <stdint.h>
#include "core/thread-crt.h"
#include "core/thread.h"
#include "util/defs.h"
struct shim_ctx {
HANDLE barrier;
int (*proc)(void *);
void *ctx;
};
static unsigned int STDCALL crt_thread_shim(void *outer_ctx)
{
struct shim_ctx *sctx = outer_ctx;
int (*proc)(void *);
void *inner_ctx;
proc = sctx->proc;
inner_ctx = sctx->ctx;
SetEvent(sctx->barrier);
return proc(inner_ctx);
}
int core_thread_crt_create(
int (*proc)(void *), void *ctx, uint32_t stack_sz, unsigned int priority)
{
struct shim_ctx sctx;
uintptr_t thread_id;
sctx.barrier = CreateEvent(NULL, TRUE, FALSE, NULL);
sctx.proc = proc;
sctx.ctx = ctx;
thread_id = _beginthreadex(NULL, stack_sz, crt_thread_shim, &sctx, 0, NULL);
WaitForSingleObject(sctx.barrier, INFINITE);
CloseHandle(sctx.barrier);
return (int) thread_id;
}
void core_thread_crt_destroy(int thread_id)
{
CloseHandle((HANDLE) (uintptr_t) thread_id);
}
void core_thread_crt_join(int thread_id, int *result)
{
WaitForSingleObject((HANDLE) (uintptr_t) thread_id, INFINITE);
if (result) {
GetExitCodeThread((HANDLE) (uintptr_t) thread_id, (DWORD *) result);
}
}

View File

@@ -0,0 +1,15 @@
#ifndef CORE_THREAD_CRT_H
#define CORE_THREAD_CRT_H
#include <stdint.h>
/**
* Thread API implementation using the C runtime API
*/
int core_thread_crt_create(
int (*proc)(void *), void *ctx, uint32_t stack_sz, unsigned int priority);
void core_thread_crt_join(int thread_id, int *result);
void core_thread_crt_destroy(int thread_id);
#endif

78
src/main/core/thread.c Normal file
View File

@@ -0,0 +1,78 @@
#include <stdlib.h>
#include "core/log.h"
#include "core/thread.h"
core_thread_create_t core_thread_create_impl;
core_thread_join_t core_thread_join_impl;
core_thread_destroy_t core_thread_destroy_impl;
int core_thread_create(
int (*proc)(void *), void *ctx, uint32_t stack_sz, unsigned int priority)
{
log_assert(core_thread_create_impl);
return core_thread_create_impl(proc, ctx, stack_sz, priority);
}
void core_thread_join(int thread_id, int *result)
{
log_assert(core_thread_join_impl);
core_thread_join_impl(thread_id, result);
}
void core_thread_destroy(int thread_id)
{
log_assert(core_thread_destroy_impl);
core_thread_destroy_impl(thread_id);
}
void core_thread_impl_set(
core_thread_create_t create,
core_thread_join_t join,
core_thread_destroy_t destroy)
{
if (create == NULL || join == NULL || destroy == NULL) {
abort();
}
core_thread_create_impl = create;
core_thread_join_impl = join;
core_thread_destroy_impl = destroy;
}
void core_thread_impl_assign(core_thread_impl_set_t impl_set)
{
if (core_thread_create_impl == NULL || core_thread_join_impl == NULL ||
core_thread_destroy_impl == NULL) {
abort();
}
impl_set(
core_thread_create_impl,
core_thread_join_impl,
core_thread_destroy_impl);
}
core_thread_create_t core_thread_create_impl_get()
{
log_assert(core_thread_create_impl);
return core_thread_create_impl;
}
core_thread_join_t core_thread_join_impl_get()
{
log_assert(core_thread_join_impl);
return core_thread_join_impl;
}
core_thread_destroy_t core_thread_destroy_impl_get()
{
log_assert(core_thread_destroy_impl);
return core_thread_destroy_impl;
}

117
src/main/core/thread.h Normal file
View File

@@ -0,0 +1,117 @@
#ifndef CORE_THREAD_H
#define CORE_THREAD_H
#include <stdint.h>
/**
* The core thread API of bemanitools.
*
* This essentially reflects the AVS threading API and allows for swapping out
* the backends with different implementations. Most games should have some
* version of the AVS API available while some (legacy) games do not. These
* can use a bemanitools private threading implementation by configuring it
* in the bootstrapping process.
*/
/**
* Create a thread
*
* Always use this interface in your application which hides the currently
* configured implementation.
*
* @param proc The function to run in a separate thread
* @param ctx Additional data to pass to the function as a parameter
* @param stack_sz The stack size to allocate for the thread in bytes
* @param priority The thread's priority
* @return The ID of the thread once created and started
*/
int core_thread_create(
int (*proc)(void *), void *ctx, uint32_t stack_sz, unsigned int priority);
/**
* Wait for a thread to finish
*
* Always use this interface in your application which hides the currently
* configured implementation.
*
* The caller of this function blocks until the thread has finished executing.
*
* @param thread_id ID of the thread to wait for
* @param result Pointer to a variable to write the return value of the function
* the thread executed to
*/
void core_thread_join(int thread_id, int *result);
/**
* Destroy a thread
*
* Always use this interface in your application which hides the currently
* configured implementation.
*
* The thread must have finished execution before calling this. It is advised
* to make threads terminate their execution flow, join them and destroy.
*
* @param thread_id The ID of the thread to destroy.
*/
void core_thread_destroy(int thread_id);
typedef int (*core_thread_create_t)(
int (*proc)(void *), void *ctx, uint32_t stack_sz, unsigned int priority);
typedef void (*core_thread_join_t)(int thread_id, int *result);
typedef void (*core_thread_destroy_t)(int thread_id);
typedef void (*core_thread_impl_set_t)(
core_thread_create_t create,
core_thread_join_t join,
core_thread_destroy_t destroy);
/**
* Configure the thread API implementations
*
* Advised to do this as early in your application/library module as possible
* as calls to the getter functions below will return the currently configured
* implementations.
*
* @param create Pointer to a function implementing thread creation
* @param join Pointer to a function implementing joining of a thread
* @param destroy Pointer to a function implementing destroying of a thread
*/
void core_thread_impl_set(
core_thread_create_t create,
core_thread_join_t join,
core_thread_destroy_t destroy);
/**
* Supporting function to inject/assign the currently set implementation
* with the given setter function.
*
* @param impl_set Setter function to call with the currently configured thread
* function implementations
*/
void core_thread_impl_assign(core_thread_impl_set_t impl_set);
/**
* Get the currently configured implementation for thread_create
*
* @return Pointer to the currently configured implementation of the
* thread_create function
*/
core_thread_create_t core_thread_create_impl_get();
/**
* Get the currently configured implementation for thread_join
*
* @return Pointer to the currently configured implementation of the thread_join
* function
*/
core_thread_join_t core_thread_join_impl_get();
/**
* Get the currently configured implementation for thread_destroy
*
* @return Pointer to the currently configured implementation of the
* thread_destroy function
*/
core_thread_destroy_t core_thread_destroy_impl_get();
#endif

View File

@@ -1,13 +0,0 @@
exes += d3d9-monitor-check \
ldflags_d3d9-monitor-check := \
-ld3d9 \
-ldwmapi \
-lgdi32 \
-ld3dx9 \
libs_d3d9-monitor-check := \
util \
src_d3d9-monitor-check := \
main.c \

View File

@@ -1,695 +0,0 @@
#include <windows.h>
#include <d3d9.h>
#include <d3dx9core.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "util/time.h"
#include "util/winerr.h"
#define printf_out(fmt, ...) \
fprintf(stdout, fmt, ##__VA_ARGS__)
#define printf_err(fmt, ...) \
fprintf(stderr, fmt, ##__VA_ARGS__)
#define printfln_out(fmt, ...) \
fprintf(stdout, fmt "\n", ##__VA_ARGS__)
#define printfln_err(fmt, ...) \
fprintf(stderr, fmt "\n", ##__VA_ARGS__)
#define printfln_winerr(fmt, ...) \
char *winerr = util_winerr_format_last_error_code(); \
fprintf(stderr, fmt ": %s\n", ##__VA_ARGS__, winerr); \
free(winerr);
static const D3DFORMAT _d3dformat = D3DFMT_X8R8G8B8;
static void _print_synopsis()
{
printfln_err("D3D9 monitor check");
printfln_err("");
printfln_err("Improved open source re-implementation of IIDX's infamous \"monitor check\" screen");
printfln_err("Run a bare D3D9 render loop to measure the refresh rate of the current GPU + monitor configuration");
printfln_err("");
printfln_err("Usage:");
printfln_err(" d3d9-monitor-check <command> <args>");
printfln_err("");
printfln_err("Available commands:");
printfln_err(" adapter: Query adapter information");
printfln_err(" modes: Query adapter modes");
printfln_err(" run <width> <height> <refresh_rate> [--total-warm-up-frame-count n] [--total-frame-count n] [--windowed] [--vsync-off]: Run the monitor check. Ensure that the mandatory parameters for width, height and refresh rate are values that are supported by the adapter's mode. Use the \"modes\" subcommand to get a list of supported modes.");
printfln_err(" width: Width of the rendering resolution to run the test at");
printfln_err(" height: Height of the rendering resolution to run the test at");
printfln_err(" refresh_rate: Target refresh rate to run the test at");
printfln_err(" total-warm-up-frame-count: Optional. Number of frames to warm-up before executing the main run that counts towards the measurement results");
printfln_err(" total-frame-count: Optional. Total number of frames to run the test for that count towards the measurement results");
printfln_err(" windowed: Optional. Run the test in windowed mode (not recommended)");
printfln_err(" vsync-off: Optional. Run the test with vsync off (not recommended)");
}
static bool _create_d3d_context(IDirect3D9 **d3d)
{
// Initialize D3D
*d3d = Direct3DCreate9(D3D_SDK_VERSION);
if (!*d3d) {
printfln_winerr("Creating d3d context failed");
return false;
}
return true;
}
static bool _query_adapter_identifier(IDirect3D9 *d3d, D3DADAPTER_IDENTIFIER9 *identifier)
{
HRESULT hr;
hr = IDirect3D9_GetAdapterIdentifier(d3d, D3DADAPTER_DEFAULT, 0, identifier);
if (hr != D3D_OK) {
printfln_winerr("GetAdapterIdentifier failed");
return false;
}
return true;
}
static bool _create_window(uint32_t width, uint32_t height, HWND *hwnd)
{
WNDCLASSEX wc;
memset(&wc, 0, sizeof(wc));
wc.cbSize = sizeof(wc);
wc.lpfnWndProc = DefWindowProc;
wc.hInstance = GetModuleHandle(NULL);
wc.lpszClassName = "D3D9MonitorCheck";
RegisterClassExA(&wc);
// Create window
*hwnd = CreateWindowA(
wc.lpszClassName,
"D3D9 Monitor Check",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
width,
height,
NULL,
NULL,
wc.hInstance,
NULL);
if (!*hwnd) {
printfln_winerr("Failed to create window");
return false;
}
return true;
}
static bool _create_d3d_device(
HWND hwnd,
IDirect3D9 *d3d,
uint32_t width,
uint32_t height,
uint32_t refresh_rate,
bool windowed,
bool vsync_off,
IDirect3DDevice9 **device)
{
D3DPRESENT_PARAMETERS pp;
HRESULT hr;
memset(&pp, 0, sizeof(pp));
if (windowed) {
ShowWindow(hwnd, SW_SHOW);
pp.Windowed = TRUE;
pp.FullScreen_RefreshRateInHz = 0;
} else {
ShowCursor(FALSE);
pp.Windowed = FALSE;
pp.FullScreen_RefreshRateInHz = refresh_rate;
}
if (vsync_off) {
pp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
} else {
pp.PresentationInterval = D3DPRESENT_INTERVAL_ONE;
}
pp.BackBufferWidth = width;
pp.BackBufferHeight = height;
pp.BackBufferFormat = _d3dformat;
pp.BackBufferCount = 2;
pp.MultiSampleType = D3DMULTISAMPLE_NONE;
pp.MultiSampleQuality = 0;
pp.SwapEffect = D3DSWAPEFFECT_DISCARD;
pp.hDeviceWindow = hwnd;
pp.EnableAutoDepthStencil = TRUE;
pp.AutoDepthStencilFormat = D3DFMT_D16;
pp.Flags = D3DPRESENTFLAG_LOCKABLE_BACKBUFFER;
// Create D3D device
hr = IDirect3D9_CreateDevice(
d3d,
D3DADAPTER_DEFAULT,
D3DDEVTYPE_HAL,
hwnd,
D3DCREATE_HARDWARE_VERTEXPROCESSING,
&pp,
device);
if (hr != D3D_OK) {
printfln_winerr("Creating d3d device failed");
return false;
}
return true;
}
static uint32_t _get_font_height(uint32_t resolution_height)
{
// Default size for 480p
return (uint32_t) (20.0f * resolution_height / 480.0f);
}
static uint32_t _get_text_offset_x(uint32_t resolution_width)
{
// Default offset for 480p
return (uint32_t) (20.0f * resolution_width / 480.0f);
}
static uint32_t _get_text_offset_y(uint32_t resolution_height, uint32_t font_height)
{
// Default offset for 480p
return (uint32_t) (font_height + 10 * (resolution_height / 640.0f));
}
static bool _create_font(IDirect3DDevice9 *device, uint32_t font_height, ID3DXFont **font)
{
HRESULT hr;
hr = D3DXCreateFont(device, font_height, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE,
"Arial", font);
if (hr != D3D_OK) {
printfln_winerr("Creating font failed");
return false;
}
return true;
}
static void _draw_text(IDirect3DDevice9 *device, ID3DXFont *font, uint32_t font_height, int x, int y, const char *fmt, ...)
{
va_list args;
char text[1024];
RECT rect;
va_start(args, fmt);
vsprintf(text, fmt, args);
va_end(args);
rect.left = x;
rect.top = y;
// Base width of 300 is based on 480p
rect.right = x + (480 * (font_height / 20.0f));
rect.bottom = y + font_height;
ID3DXFont_DrawText(font, NULL, text, -1, &rect, DT_LEFT | DT_TOP, D3DCOLOR_XRGB(255, 255, 255));
}
static bool _adapter()
{
IDirect3D9 *d3d;
D3DADAPTER_IDENTIFIER9 identifier;
if (!_create_d3d_context(&d3d)) {
return false;
}
if (!_query_adapter_identifier(d3d, &identifier)) {
IDirect3D9_Release(d3d);
return false;
}
printfln_out("Driver: %s", identifier.Driver);
printfln_out("Description: %s", identifier.Description);
printfln_out("DeviceName: %s", identifier.DeviceName);
#ifdef _WIN32
printfln_out("DriverVersion: %lld", identifier.DriverVersion.QuadPart);
#else
printfln_out("DriverVersion: %lu.%lu", identifier.DriverVersionHighPart, identifier.DriverVersionLowPart);
#endif
printfln_out("VendorId: %lu", identifier.VendorId);
printfln_out("DeviceId: %lu", identifier.DeviceId);
printfln_out("SubSysId: %lu", identifier.SubSysId);
printfln_out("Revision: %lu", identifier.Revision);
printfln_out("DeviceIdentifier: {%08lX-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
identifier.DeviceIdentifier.Data1,
identifier.DeviceIdentifier.Data2,
identifier.DeviceIdentifier.Data3,
identifier.DeviceIdentifier.Data4[0],
identifier.DeviceIdentifier.Data4[1],
identifier.DeviceIdentifier.Data4[2],
identifier.DeviceIdentifier.Data4[3],
identifier.DeviceIdentifier.Data4[4],
identifier.DeviceIdentifier.Data4[5],
identifier.DeviceIdentifier.Data4[6],
identifier.DeviceIdentifier.Data4[7]);
printfln_out("WHQLLevel: %lu", identifier.WHQLLevel);
IDirect3D9_Release(d3d);
return true;
}
static bool _modes()
{
IDirect3D9 *d3d;
HRESULT hr;
UINT mode_count;
D3DDISPLAYMODE mode;
memset(&mode, 0, sizeof(D3DDISPLAYMODE));
if (!_create_d3d_context(&d3d)) {
return false;
}
mode_count = IDirect3D9_GetAdapterModeCount(d3d, D3DADAPTER_DEFAULT, _d3dformat);
printfln_err("Available adapter modes (total %d)", mode_count);
printfln_err("Mode index: width x height @ refresh rate");
for (UINT i = 0; i < mode_count; i++) {
hr = IDirect3D9_EnumAdapterModes(d3d, D3DADAPTER_DEFAULT, _d3dformat, i, &mode);
if (hr != D3D_OK) {
printfln_winerr("EnumAdapterMode index %d failed", i);
IDirect3D9_Release(d3d);
return false;
}
printfln_out("%d: %d x %d @ %d hz", i, mode.Width, mode.Height, mode.RefreshRate);
}
IDirect3D9_Release(d3d);
return true;
}
static bool _run(uint32_t width, uint32_t height, uint32_t refresh_rate, uint32_t total_warm_up_frame_count, uint32_t total_frame_count, bool windowed, bool vsync_off)
{
HWND hwnd;
IDirect3D9 *d3d;
D3DADAPTER_IDENTIFIER9 identifier;
IDirect3DDevice9 *device;
uint32_t font_height;
ID3DXFont *font;
uint32_t text_offset_x;
uint32_t text_offset_y;
MSG msg;
bool exit_loop;
bool warm_up_done;
uint32_t warm_up_frame_count;
uint32_t frame_count;
uint64_t start_time;
uint64_t end_time;
uint64_t elapsed_us;
uint64_t total_elapsed_us;
printfln_err("Creating d3d context ...");
if (!_create_d3d_context(&d3d)) {
return false;
}
printfln_err("Querying adapter identifier ...");
if (!_query_adapter_identifier(d3d, &identifier)) {
IDirect3D9_Release(d3d);
return false;
}
printfln_err("Adapter:");
printfln_err("Driver: %s", identifier.Driver);
printfln_err("Description: %s", identifier.Description);
printfln_err("DeviceName: %s", identifier.DeviceName);
#ifdef _WIN32
printfln_err("DriverVersion: %lld", identifier.DriverVersion.QuadPart);
#else
printfln_err("DriverVersion: %lu.%lu", identifier.DriverVersionHighPart, identifier.DriverVersionLowPart);
#endif
printfln_err("Creating window with %dx%d ...", width, height);
if (!_create_window(width, height, &hwnd)) {
IDirect3D9_Release(d3d);
return false;
}
printfln_err("Creating d3d device %d x %d @ %d hz %s vsync %s ...",
width,
height,
refresh_rate,
windowed ? "windowed" : "fullscreen",
vsync_off ? "off" : "on");
if (!_create_d3d_device(
hwnd,
d3d,
width,
height,
refresh_rate,
windowed,
vsync_off,
&device)) {
IDirect3D9_Release(d3d);
DestroyWindow(hwnd);
return false;
}
printfln_err("Creating font ...");
font_height = _get_font_height(height);
if (!_create_font(device, font_height, &font)) {
IDirect3DDevice9_Release(device);
IDirect3D9_Release(d3d);
DestroyWindow(hwnd);
return false;
}
text_offset_x = _get_text_offset_x(width);
text_offset_y = _get_text_offset_y(height, font_height);
// ---------------------------------------------------------------------------------------------
exit_loop = false;
warm_up_done = false;
warm_up_frame_count = 0;
frame_count = 0;
elapsed_us = 0;
total_elapsed_us = 0;
printfln_err("Warm-up for %d frames ...", total_warm_up_frame_count);
start_time = time_get_counter();
while (warm_up_frame_count + frame_count < total_warm_up_frame_count + total_frame_count) {
// reset when warm-up is done
if (warm_up_frame_count >= total_warm_up_frame_count && !warm_up_done) {
warm_up_done = true;
total_elapsed_us = 0;
printfln_err("Warm-up finished");
printfln_err("Running test for %d frames ...", total_frame_count);
}
// Required to not make windows think we are stuck and not responding
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
if (msg.message == WM_QUIT) {
exit_loop = true;
break;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
if (exit_loop) {
break;
}
if (GetAsyncKeyState(VK_ESCAPE) & 0x8000) {
exit_loop = true;
break;
}
IDirect3DDevice9_Clear(
device,
0,
NULL,
D3DCLEAR_TARGET,
D3DCOLOR_XRGB(0, 0, 0),
1.0f,
0);
IDirect3DDevice9_BeginScene(device);
_draw_text(device, font, font_height, text_offset_x, text_offset_y, "D3D9 Monitor Check");
_draw_text(device, font, font_height, text_offset_x, text_offset_y * 3,
"GPU: %s", identifier.Description);
_draw_text(device, font, font_height, text_offset_x, text_offset_y * 4,
"Spec: %d x %d @ %d hz, %s, vsync %s", width, height, refresh_rate,
windowed ? "windowed" : "fullscreen", vsync_off ? "off" : "on");
if (warm_up_frame_count < total_warm_up_frame_count) {
// First frame won't have any data available causing division by zero in the stats
if (warm_up_frame_count != 0) {
_draw_text(device, font, font_height, text_offset_x, text_offset_y * 6, "Status: Warm-up in progress ...");
_draw_text(device, font, font_height, text_offset_x, text_offset_y * 7,
"Frame: %d / %d", warm_up_frame_count, total_warm_up_frame_count);
_draw_text(device, font, font_height, text_offset_x, text_offset_y * 8,
"Last frame time: %.3f ms", elapsed_us / 1000.0f);
_draw_text(device, font, font_height, text_offset_x, text_offset_y * 9,
"Avg frame time: %.3f ms", total_elapsed_us / warm_up_frame_count / 1000.0f);
_draw_text(device, font, font_height, text_offset_x, text_offset_y * 10,
"Last refresh rate: %.3f Hz", 1000.0f / (elapsed_us / 1000.0f));
_draw_text(device, font, font_height, text_offset_x, text_offset_y * 11,
"Avg refresh rate: %.3f Hz", 1000.0f / (total_elapsed_us / warm_up_frame_count / 1000.0f));
}
} else {
// First frame won't have any data available causing division by zero in the stats
if (frame_count != 0) {
_draw_text(device, font, font_height, text_offset_x, text_offset_y * 6, "Status: Measuring in progress ...");
_draw_text(device, font, font_height, text_offset_x, text_offset_y * 7,
"Frame: %d / %d", frame_count, total_frame_count);
_draw_text(device, font, font_height, text_offset_x, text_offset_y * 8,
"Last frame time: %.3f ms", elapsed_us / 1000.0f);
_draw_text(device, font, font_height, text_offset_x, text_offset_y * 9,
"Avg frame time: %.3f ms", total_elapsed_us / frame_count / 1000.0f);
_draw_text(device, font, font_height, text_offset_x, text_offset_y * 10,
"Last refresh rate: %.3f Hz", 1000.0f / (elapsed_us / 1000.0f));
_draw_text(device, font, font_height, text_offset_x, text_offset_y * 11,
"Avg refresh rate: %.3f Hz", 1000.0f / (total_elapsed_us / frame_count / 1000.0f));
}
}
_draw_text(device, font, font_height, text_offset_x, text_offset_y * 13, "Press ESC to exit early");
IDirect3DDevice9_EndScene(device);
IDirect3DDevice9_Present(device, NULL, NULL, NULL, NULL);
end_time = time_get_counter();
elapsed_us = time_get_elapsed_us(end_time - start_time);
start_time = end_time;
total_elapsed_us += elapsed_us;
if (warm_up_frame_count < total_warm_up_frame_count) {
warm_up_frame_count++;
} else {
frame_count++;
}
}
// ---------------------------------------------------------------------------------------------
printfln_err("Running test finished");
IDirect3DDevice9_Clear(
device,
0,
NULL,
D3DCLEAR_TARGET,
D3DCOLOR_XRGB(0, 0, 0),
1.0f,
0);
IDirect3DDevice9_BeginScene(device);
_draw_text(device, font, font_height, text_offset_x, text_offset_y, "D3D9 Monitor Check");
_draw_text(device, font, font_height, text_offset_x, text_offset_y * 3,
"GPU: %s", identifier.Description);
_draw_text(device, font, font_height, text_offset_x, text_offset_y * 4,
"Spec: %d x %d @ %d hz, %s, vsync %s", width, height, refresh_rate,
windowed ? "windowed" : "fullscreen", vsync_off ? "off" : "on");
if (exit_loop) {
_draw_text(device, font, font_height, text_offset_x, text_offset_y * 6, "Status: Exited early");
} else {
_draw_text(device, font, font_height, text_offset_x, text_offset_y * 6, "Status: Finished");
}
_draw_text(device, font, font_height, text_offset_x, text_offset_y * 7,
"Total warm-up frame count: %d", warm_up_frame_count);
_draw_text(device, font, font_height, text_offset_x, text_offset_y * 8,
"Total sample frame count: %d", frame_count);
_draw_text(device, font, font_height, text_offset_x, text_offset_y * 9,
"Avg frame time: %.3f ms", total_elapsed_us / frame_count / 1000.0f);
_draw_text(device, font, font_height, text_offset_x, text_offset_y * 10,
"Avg refresh rate: %.3f Hz", 1000.0f / (total_elapsed_us / frame_count / 1000.0f));
_draw_text(device, font, font_height, text_offset_x, text_offset_y * 12, "Exiting in 5 seconds ...");
IDirect3DDevice9_EndScene(device);
IDirect3DDevice9_Present(device, NULL, NULL, NULL, NULL);
Sleep(5000);
// ---------------------------------------------------------------------------------------------
printfln_err("Final results");
printfln_out("GPU: %s", identifier.Description);
printfln_out("Spec: %d x %d @ %d hz, %s, vsync %s", width, height, refresh_rate,
windowed ? "windowed" : "fullscreen", vsync_off ? "off" : "on");
printfln_out("Avg frame time (ms): %.3f", total_elapsed_us / frame_count / 1000.0f);
printfln_out("Avg refresh rate (hz): %.3f", 1000.0f / (total_elapsed_us / frame_count / 1000.0f));
ID3DXFont_Release(font);
IDirect3DDevice9_Release(device);
IDirect3D9_Release(d3d);
DestroyWindow(hwnd);
return true;
}
static bool _cmd_adapter()
{
return _adapter();
}
static bool _cmd_modes()
{
return _modes();
}
static bool _cmd_run(int argc, char **argv)
{
uint32_t width;
uint32_t height;
uint32_t refresh_rate;
uint32_t total_warm_up_frame_count;
uint32_t total_frame_count;
bool windowed;
bool vsync_off;
if (argc < 3) {
_print_synopsis();
printfln_err("ERROR: Insufficient arguments");
return false;
}
width = atoi(argv[0]);
if (width == 0 || width > 16384) {
_print_synopsis();
printfln_err("ERROR: Invalid width: %d", width);
return false;
}
height = atoi(argv[1]);
if (height == 0 || height > 16384) {
_print_synopsis();
printfln_err("ERROR: Invalid height: %d", height);
return false;
}
refresh_rate = atoi(argv[2]);
if (refresh_rate == 0 || refresh_rate > 1000) {
_print_synopsis();
printfln_err("ERROR: Invalid refresh rate: %d", refresh_rate);
return false;
}
// Sane defaults
total_warm_up_frame_count = 500;
total_frame_count = 1000;
windowed = false;
vsync_off = false;
for (int i = 3; i < argc; i++) {
if (!strcmp(argv[i], "--total-warm-up-frame-count")) {
if (i + 1 < argc) {
total_warm_up_frame_count = atoi(argv[++i]);
if (total_warm_up_frame_count == 0) {
_print_synopsis();
printfln_err("ERROR: Invalid total warm-up frame count: %d", total_warm_up_frame_count);
return false;
}
} else {
_print_synopsis();
printfln_err("ERROR: Missing argument for --total-warm-up-frame-count");
return false;
}
} else if (!strcmp(argv[i], "--total-frame-count")) {
if (i + 1 < argc) {
total_frame_count = atoi(argv[++i]);
if (total_frame_count == 0) {
_print_synopsis();
printfln_err("ERROR: Invalid total frame count: %d", total_frame_count);
return false;
}
} else {
_print_synopsis();
printfln_err("ERROR: Missing argument for --total-frame-count");
return false;
}
} else if (!strcmp(argv[i], "--windowed")) {
windowed = true;
} else if (!strcmp(argv[i], "--vsync-off")) {
vsync_off = true;
}
}
return _run(width, height, refresh_rate, total_warm_up_frame_count, total_frame_count, windowed, vsync_off);
}
int main(int argc, char **argv)
{
const char *command;
if (argc < 2) {
_print_synopsis();
printfln_err("ERROR: Insufficient arguments");
return 1;
}
command = argv[1];
if (!strcmp(command, "adapter")) {
if (!_cmd_adapter(argc - 2, argv + 2)) {
return 1;
}
} else if (!strcmp(command, "modes")) {
if (!_cmd_modes(argc - 2, argv + 2)) {
return 1;
}
} else if (!strcmp(command, "run")) {
if (!_cmd_run(argc - 2, argv + 2)) {
return 1;
}
} else {
_print_synopsis(argv[0]);
printfln_err("ERROR: Unknown command: %s", command);
return 1;
}
return 0;
}

View File

@@ -15,12 +15,21 @@ static const size_t apiset_prefix_len = sizeof(apiset_prefix) - 1;
static void hook_table_apply_to_all( static void hook_table_apply_to_all(
const char *depname, const struct hook_symbol *syms, size_t nsyms); const char *depname, const struct hook_symbol *syms, size_t nsyms);
static void hook_table_revert_to_all(
const char *depname, const struct hook_symbol *syms, size_t nsyms);
static void hook_table_apply_to_iid( static void hook_table_apply_to_iid(
HMODULE target, HMODULE target,
const pe_iid_t *iid, const pe_iid_t *iid,
const struct hook_symbol *syms, const struct hook_symbol *syms,
size_t nsyms); size_t nsyms);
static void hook_table_revert_to_iid(
HMODULE target,
const pe_iid_t *iid,
const struct hook_symbol *syms,
size_t nsyms);
static bool hook_table_match_module( static bool hook_table_match_module(
HMODULE target, const char *iid_name, const char *depname); HMODULE target, const char *iid_name, const char *depname);
@@ -44,6 +53,23 @@ static void hook_table_apply_to_all(
} }
} }
static void hook_table_revert_to_all(
const char *depname, const struct hook_symbol *syms, size_t nsyms)
{
const peb_dll_t *dll;
HMODULE pe;
for (dll = peb_dll_get_first(); dll != NULL; dll = peb_dll_get_next(dll)) {
pe = peb_dll_get_base(dll);
if (pe == NULL) {
continue; /* ?? Happens sometimes. */
}
hook_table_revert(pe, depname, syms, nsyms);
}
}
void hook_table_apply( void hook_table_apply(
HMODULE target, HMODULE target,
const char *depname, const char *depname,
@@ -73,6 +99,35 @@ void hook_table_apply(
} }
} }
void hook_table_revert(
HMODULE target,
const char *depname,
const struct hook_symbol *syms,
size_t nsyms)
{
const pe_iid_t *iid;
const char *iid_name;
assert(depname != NULL);
assert(syms != NULL || nsyms == 0);
if (target == NULL) {
/* Call out, which will then call us back repeatedly. Awkward, but
viewed from the outside it's good for usability. */
hook_table_revert_to_all(depname, syms, nsyms);
} else {
for (iid = pe_iid_get_first(target); iid != NULL;
iid = pe_iid_get_next(target, iid)) {
iid_name = pe_iid_get_name(target, iid);
if (hook_table_match_module(target, iid_name, depname)) {
hook_table_revert_to_iid(target, iid, syms, nsyms);
}
}
}
}
static void hook_table_apply_to_iid( static void hook_table_apply_to_iid(
HMODULE target, HMODULE target,
const pe_iid_t *iid, const pe_iid_t *iid,
@@ -101,6 +156,33 @@ static void hook_table_apply_to_iid(
} }
} }
static void hook_table_revert_to_iid(
HMODULE target,
const pe_iid_t *iid,
const struct hook_symbol *syms,
size_t nsyms)
{
struct pe_iat_entry iate;
size_t i;
size_t j;
const struct hook_symbol *sym;
i = 0;
while (pe_iid_get_iat_entry(target, iid, i++, &iate) == S_OK) {
for (j = 0; j < nsyms; j++) {
sym = &syms[j];
if (hook_table_match_proc(&iate, sym)) {
// Only revert-able if the original pointer was stored previously
if (sym->link != NULL && *sym->link != NULL) {
pe_patch(iate.ppointer, sym->link, sizeof(*sym->link));
}
}
}
}
}
static bool hook_table_match_module( static bool hook_table_match_module(
HMODULE target, const char *iid_name, const char *depname) HMODULE target, const char *iid_name, const char *depname)
{ {