// SPDX-License-Identifier: CC0-1.0
/*
 * c8_glasses: Monado's driver for the XREAL glasses cont8nuum knows
 * (the 1 Pro+ and its kin), whose motion comes over their USB network
 * (TCP 169.254.2.1:52998) rather than HID, so Monado's xreal_air driver
 * doesn't see them. The fusion is the compositor's own (compositor/src/
 * imu.c, built here as it is, with this folder's imu-host.h), so the
 * head moves the same in a game as on the desktop.
 *
 * A thread runs the IMU's event loop (connecting, the watchdog, the
 * reader); Monado asks for poses from its own threads, so both sides
 * hold `lock`. The display is whatever mode the glasses are in when c8
 * starts Monado (C8_GLASSES_MODE=WxH@mHz, from the output it leases):
 * their 3D mode is 3840x1080 at 60, an eye each half; their 2D mode is
 * one 1920x1080 picture for both eyes (up to 120 Hz), so both views
 * are that one picture from between the eyes: no depth, but the head
 * tracks and games run. Pressing their 3D button changes the display,
 * and c8 starts Monado again for the new one.
 *
 * Settings come from cont8nuum's config.ini, [glasses]: fov (the
 * diagonal, degrees), tilt, steady, neck, latency and scanout, read
 * once at start.
 * C8_XR_IMU=HOST:PORT reads a mock stream (tests) and also makes the
 * builder claim a head without the glasses plugged in.
 */
#include <math.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>

#include "xrt/xrt_config_drivers.h"
#include "xrt/xrt_defines.h"
#include "xrt/xrt_device.h"
#include "xrt/xrt_prober.h"
#include "xrt/xrt_system.h"
#include "os/os_time.h"
#include "math/m_api.h"
#include "util/u_builders.h"
#include "util/u_debug.h"
#include "util/u_device.h"
#include "util/u_distortion_mesh.h"
#include "util/u_logging.h"
#include "util/u_misc.h"
#include "util/u_time.h"
#include "util/u_visibility_mask.h"

#include "imu.h"
#include "c8_glasses_interface.h"

#define XREAL_VID 0x3318
/* The ones whose motion comes over the network, as far as is known:
 * the 1 Pro+ (read from one), and the One / One Pro / 1S, whose drivers
 * elsewhere (xreal-linux) use the same port */
static const uint16_t product_ids[] = { 0x0444, 0x0435, 0x0436, 0x0437 };

#define EYE_W 1920
#define EYE_H 1080
#define LATENCY_AT_MS (1000.0 / 90) // as glasses.c: [glasses] latency's refresh
#define POLL_MS 2 // the IMU thread: how often it takes what has come

DEBUG_GET_ONCE_LOG_OPTION(c8_glasses_log, "C8_GLASSES_LOG", U_LOGGING_INFO)

enum u_logging_level c8_glasses_log_level;

struct settings {
	double fov, tilt, neck_up, neck_ahead;
	double latency, scanout; // ms; scanout < 0: a refresh
	double ipd; // mm, the 3D mode's eyes apart
	bool steady;
};

struct c8_glasses {
	struct xrt_device base;
	struct settings settings;

	pthread_mutex_t lock;
	pthread_t thread;
	bool running;
	struct wl_event_loop *loop;
	struct c8_imu *imu;
	bool mono; // the 2D mode: one picture for both eyes
	/* Added to Monado's display times: [glasses] latency against what
	 * Monado already counts (the refresh before scanout) */
	int64_t ahead_ns;
};

static struct c8_glasses *c8_glasses(struct xrt_device *xdev) {
	return (struct c8_glasses *)xdev;
}

/* imu-host.h's, here */

int64_t c8_now_ns(void) {
	return (int64_t)os_monotonic_get_ns();
}

int64_t c8_now_ms(void) {
	return c8_now_ns() / 1000000;
}

/* As the compositor's util.c: the gyro bias is shared with it, so a
 * game starts from what the desktop learnt and the other way round */
bool c8_state_path(const char *name, char *path, size_t size, bool make) {
	const char *state = getenv("XDG_STATE_HOME"), *home = getenv("HOME");
	char dir[4096];
	if (state && *state) {
		snprintf(dir, sizeof(dir), "%s/cont8nuum", state);
	} else if (home && *home) {
		snprintf(dir, sizeof(dir), "%s/.local/state/cont8nuum", home);
	} else {
		return false;
	}
	if (make) {
		char parent[4096];
		snprintf(parent, sizeof(parent), "%s", dir);
		char *slash = strrchr(parent, '/');
		if (slash) {
			*slash = '\0';
			mkdir(parent, 0755);
		}
		mkdir(dir, 0755);
	}
	return snprintf(path, size, "%s/%s", dir, name) < (int)size;
}

/* config.ini's [glasses], with the compositor's defaults and bounds */
static void read_settings(struct settings *s) {
	*s = (struct settings){
		.fov = 57, .tilt = 40, .neck_up = 0.075, .neck_ahead = 0.08,
		.latency = 15, .scanout = -1, .steady = true, .ipd = 63,
	};
	const char *cfg = getenv("XDG_CONFIG_HOME"), *home = getenv("HOME");
	char path[4096];
	if (cfg && *cfg) {
		snprintf(path, sizeof(path), "%s/cont8nuum/config.ini", cfg);
	} else if (home && *home) {
		snprintf(path, sizeof(path), "%s/.config/cont8nuum/config.ini", home);
	} else {
		return;
	}
	FILE *f = fopen(path, "r");
	if (f == NULL) {
		return;
	}
	char line[512];
	bool in = false;
	while (fgets(line, sizeof(line), f)) {
		char *p = line;
		while (*p == ' ' || *p == '\t') {
			p++;
		}
		if (*p == '[') {
			in = strncmp(p, "[glasses]", 9) == 0;
			continue;
		}
		char key[64], value[256];
		if (!in || *p == '#' || *p == ';' ||
				sscanf(p, " %63[^= \t] = %255[^\n#;]", key, value) != 2) {
			continue;
		}
		double v = atof(value), a, b;
		if (strcmp(key, "fov") == 0 && v >= 20 && v <= 140) {
			s->fov = v;
		} else if (strcmp(key, "tilt") == 0 && v >= -90 && v <= 90) {
			s->tilt = v;
		} else if (strcmp(key, "steady") == 0) {
			s->steady = strncmp(value, "true", 4) == 0 ||
				strncmp(value, "yes", 3) == 0 || strncmp(value, "on", 2) == 0 ||
				strncmp(value, "1", 1) == 0;
		} else if (strcmp(key, "ipd") == 0 && v >= 45 && v <= 85) {
			s->ipd = v;
		} else if (strcmp(key, "latency") == 0 && v >= 0 && v <= 100) {
			s->latency = v;
		} else if (strcmp(key, "scanout") == 0) {
			s->scanout = strncmp(value, "auto", 4) == 0 ? -1 :
				v >= 0 && v <= 50 ? v : s->scanout;
		} else if (strcmp(key, "neck") == 0 &&
				sscanf(value, "%lf %lf", &a, &b) == 2 &&
				fabs(a) <= 0.3 && fabs(b) <= 0.3) {
			s->neck_up = a;
			s->neck_ahead = b;
		}
	}
	fclose(f);
}

/* The IMU's host: ours, not the compositor's */

static void imu_changed(void *data, bool settled) {
	U_LOG_IFL_I(c8_glasses_log_level, "c8_glasses: tracking %s",
		settled ? "settled" : "changed");
}

static void imu_settings(void *data, double *tilt_deg, bool *steady) {
	struct c8_glasses *g = data;
	*tilt_deg = g->settings.tilt;
	*steady = g->settings.steady;
}

static void imu_silent(void *data) {
	U_LOG_IFL_W(c8_glasses_log_level, "c8_glasses: the glasses aren't "
		"sending their motion: check their network shows up, and turn "
		"off their own Anchor or Stabiliser mode");
}

static void *imu_thread(void *data) {
	struct c8_glasses *g = data;
	struct timespec nap = { 0, POLL_MS * 1000000L };
	pthread_mutex_lock(&g->lock);
	while (g->running) {
		c8_imu_read(g->imu);
		wl_event_loop_dispatch(g->loop, 0);
		pthread_mutex_unlock(&g->lock);
		nanosleep(&nap, NULL);
		pthread_mutex_lock(&g->lock);
	}
	pthread_mutex_unlock(&g->lock);
	return NULL;
}

/* The device */

static void glasses_destroy(struct xrt_device *xdev) {
	struct c8_glasses *g = c8_glasses(xdev);
	if (g->running) {
		pthread_mutex_lock(&g->lock);
		g->running = false;
		pthread_mutex_unlock(&g->lock);
		pthread_join(g->thread, NULL);
	}
	c8_imu_destroy(g->imu); // saves the bias
	if (g->loop) {
		wl_event_loop_destroy(g->loop);
	}
	pthread_mutex_destroy(&g->lock);
	u_device_free(&g->base);
}

static xrt_result_t glasses_get_tracked_pose(struct xrt_device *xdev,
		enum xrt_input_name name, int64_t at_timestamp_ns,
		struct xrt_space_relation *out) {
	struct c8_glasses *g = c8_glasses(xdev);
	if (name != XRT_INPUT_GENERIC_HEAD_POSE) {
		U_LOG_XDEV_UNSUPPORTED_INPUT(&g->base, c8_glasses_log_level, name);
		return XRT_ERROR_INPUT_UNSUPPORTED;
	}
	struct quat q = { 1, 0, 0, 0 };
	pthread_mutex_lock(&g->lock);
	bool tracked = c8_imu_orientation(g->imu, at_timestamp_ns + g->ahead_ns,
		&q);
	pthread_mutex_unlock(&g->lock);

	struct xrt_space_relation r = XRT_SPACE_RELATION_ZERO;
	/* The head's axes are OpenXR's (+x right, +y up, -z ahead) */
	r.pose.orientation = (struct xrt_quat){
		(float)q.x, (float)q.y, (float)q.z, (float)q.w,
	};
	math_quat_normalize(&r.pose.orientation);
	/* The neck model, as tracker.c: the head turns about the neck, so
	 * a turn carries the eyes a few cm */
	struct xrt_vec3 eyes = {
		0, (float)g->settings.neck_up, (float)-g->settings.neck_ahead,
	};
	struct xrt_vec3 moved;
	math_quat_rotate_vec3(&r.pose.orientation, &eyes, &moved);
	r.pose.position = (struct xrt_vec3){
		moved.x - eyes.x, moved.y - eyes.y, moved.z - eyes.z,
	};
	r.relation_flags = XRT_SPACE_RELATION_ORIENTATION_VALID_BIT |
		XRT_SPACE_RELATION_POSITION_VALID_BIT;
	if (tracked) {
		r.relation_flags |= XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT;
	}
	*out = r;
	return XRT_SUCCESS;
}

/* The 2D mode: both eyes see one picture, so both views are from
 * between them (no eye relation). The 3D mode: [glasses] ipd apart,
 * not Monado's fixed 63 mm */
static xrt_result_t glasses_get_view_poses(struct xrt_device *xdev,
		const struct xrt_vec3 *default_eye_relation, int64_t at_timestamp_ns,
		enum xrt_view_type view_type, uint32_t view_count,
		struct xrt_space_relation *out_head_relation,
		struct xrt_fov *out_fovs, struct xrt_pose *out_poses) {
	static const struct xrt_vec3 none = { 0, 0, 0 };
	struct c8_glasses *g = c8_glasses(xdev);
	struct xrt_vec3 eyes = { (float)(g->settings.ipd / 1000), 0, 0 };
	return u_device_get_view_poses(xdev, g->mono ? &none : &eyes,
		at_timestamp_ns, view_type, view_count, out_head_relation, out_fovs,
		out_poses);
}

/* The glasses light their rows top down, over [glasses] scanout or a
 * refresh: Monado then poses the bottom of the picture later than the
 * top, as glasses.c does, or a turn shears every window */
static xrt_result_t glasses_get_compositor_info(struct xrt_device *xdev,
		const struct xrt_device_compositor_mode *mode,
		struct xrt_device_compositor_info *out_info) {
	struct c8_glasses *g = c8_glasses(xdev);
	out_info->scanout_direction = XRT_SCANOUT_DIRECTION_TOP_TO_BOTTOM;
	out_info->scanout_time_ns = g->settings.scanout >= 0 ?
		(int64_t)(g->settings.scanout * 1e6) : mode->frame_interval_ns;
	return XRT_SUCCESS;
}

/* C8_GLASSES_MODE=WxH@mHz, as c8 found the display; else the 3D mode */
static void read_mode(int *w, int *h, int *mhz) {
	*w = EYE_W * 2;
	*h = EYE_H;
	*mhz = 60000;
	const char *mode = getenv("C8_GLASSES_MODE");
	int a, b, c;
	if (mode && sscanf(mode, "%dx%d@%d", &a, &b, &c) == 3 &&
			a > 0 && b > 0 && c > 1000) {
		*w = a;
		*h = b;
		*mhz = c;
	}
}

static xrt_result_t glasses_get_visibility_mask(struct xrt_device *xdev,
		enum xrt_visibility_mask_type type, uint32_t view_index,
		struct xrt_visibility_mask **out_mask) {
	struct xrt_fov fov = xdev->hmd->distortion.fov[view_index];
	u_visibility_mask_get_default(type, &fov, out_mask);
	return XRT_SUCCESS;
}

struct xrt_device *c8_glasses_create(void) {
	enum u_device_alloc_flags flags = (enum u_device_alloc_flags)(
		U_DEVICE_ALLOC_HMD | U_DEVICE_ALLOC_TRACKING_NONE);
	struct c8_glasses *g = U_DEVICE_ALLOCATE(struct c8_glasses, flags, 1, 0);
	if (g == NULL) {
		return NULL;
	}
	pthread_mutex_init(&g->lock, NULL);
	read_settings(&g->settings);

	/* Light added to what you see: black is see-through */
	size_t idx = 0;
	g->base.hmd->blend_modes[idx++] = XRT_BLEND_MODE_ADDITIVE;
	g->base.hmd->blend_modes[idx++] = XRT_BLEND_MODE_OPAQUE;
	g->base.hmd->blend_mode_count = idx;

	g->base.update_inputs = u_device_noop_update_inputs;
	g->base.get_tracked_pose = glasses_get_tracked_pose;
	g->base.get_view_poses = glasses_get_view_poses;
	/* Rolling scanout: Monado poses the top row and the bottom one a
	 * scanout later, and warps the rows between (its compute
	 * compositor; the graphics one by our Monado commit). Left off
	 * once, when the world swung against every turn with it on (the
	 * 1 Pro+ at 120 Hz, the compute compositor), but every frame was
	 * a refresh late then. Without it a turn sheared every window, the
	 * bottom trailing the top (2026-12-02, at 90 Hz, frames on time). */
	g->base.get_compositor_info = glasses_get_compositor_info;
	g->base.supported.compositor_info = true;
	g->base.get_visibility_mask = glasses_get_visibility_mask;
	g->base.destroy = glasses_destroy;

	snprintf(g->base.str, XRT_DEVICE_NAME_LEN, "XREAL glasses");
	snprintf(g->base.serial, XRT_DEVICE_NAME_LEN, "c8-glasses");
	g->base.name = XRT_DEVICE_GENERIC_HMD;
	g->base.device_type = XRT_DEVICE_TYPE_HMD;
	g->base.inputs[0].name = XRT_INPUT_GENERIC_HEAD_POSE;
	g->base.supported.orientation_tracking = true;
	g->base.supported.position_tracking = false;

	/* The mode's own refresh: Monado paces by it until direct mode has
	 * read the real one, and a 60 here on a 120 Hz display left every
	 * frame a refresh late */
	int w, h, mhz;
	read_mode(&w, &h, &mhz);
	g->mono = w < EYE_W * 2;
	int eye_w = g->mono ? w : w / 2;
	int64_t refresh_ns = (int64_t)(1e12 / mhz);
	g->base.hmd->screens[0].nominal_frame_interval_ns = refresh_ns;
	g->base.hmd->screens[0].w_pixels = w;
	g->base.hmd->screens[0].h_pixels = h;
	/* [glasses] latency reaches the middle row; Monado's display time is
	 * the refresh after the frame starts, and with the scanout
	 * correction it poses the top row then: half a scanout sooner */
	double refresh_ms = refresh_ns / 1e6;
	double scanout_ms = g->settings.scanout >= 0 ?
		g->settings.scanout : refresh_ms;
	g->ahead_ns = (int64_t)((g->settings.latency * refresh_ms /
		LATENCY_AT_MS - refresh_ms - scanout_ms / 2) * 1e6);

	/* Each eye's field from the diagonal, as glasses.c's eye_fov; both
	 * centred (birdbath optics, no lens offset) */
	double t = tan(g->settings.fov * M_PI / 360);
	double d = sqrt((double)eye_w * eye_w + (double)h * h);
	double fov_x = 2 * atan(t * eye_w / d), fov_y = 2 * atan(t * h / d);
	for (int eye = 0; eye < 2; eye++) {
		if (!math_compute_fovs(1, 0.5, fov_x, 1, 0.5, fov_y,
				&g->base.hmd->distortion.fov[eye])) {
			U_LOG_IFL_E(c8_glasses_log_level, "c8_glasses: bad field of view");
			glasses_destroy(&g->base);
			return NULL;
		}
		/* In the 2D mode both views fill the one picture: the same
		 * picture, drawn twice */
		g->base.hmd->views[eye].display.w_pixels = eye_w;
		g->base.hmd->views[eye].display.h_pixels = h;
		g->base.hmd->views[eye].viewport.x_pixels = g->mono ? 0 : eye * eye_w;
		g->base.hmd->views[eye].viewport.y_pixels = 0;
		g->base.hmd->views[eye].viewport.w_pixels = eye_w;
		g->base.hmd->views[eye].viewport.h_pixels = h;
		g->base.hmd->views[eye].rot = u_device_rotation_ident;
	}
	u_distortion_mesh_set_none(&g->base);

	g->loop = wl_event_loop_create();
	struct c8_imu_host host = {
		.loop = g->loop,
		.changed = imu_changed,
		.settings = imu_settings,
		.silent = imu_silent,
		.data = g,
	};
	g->imu = g->loop ? c8_imu_create(&host) : NULL;
	if (g->imu == NULL) {
		glasses_destroy(&g->base);
		return NULL;
	}
	c8_imu_set_wanted(g->imu, true);
	g->running = true;
	if (pthread_create(&g->thread, NULL, imu_thread, g) != 0) {
		g->running = false;
		glasses_destroy(&g->base);
		return NULL;
	}
	U_LOG_IFL_I(c8_glasses_log_level, "c8_glasses: %dx%d at %.1f Hz, %s; "
		"%.0f degrees diagonal, %.1f by %.1f an eye; poses %.1f ms on",
		w, h, mhz / 1000.0, g->mono ? "2D (one picture, no depth)" : "3D",
		g->settings.fov, fov_x * 180 / M_PI, fov_y * 180 / M_PI,
		g->ahead_ns / 1e6);
	return &g->base;
}

/* The builder: claims a head when the glasses are on USB */

static const char *driver_list[] = { "c8_glasses" };

static bool present(struct xrt_prober *xp) {
	if (getenv("C8_XR_IMU")) {
		return true;
	}
	struct xrt_prober_device **devs = NULL;
	size_t count = 0;
	if (xrt_prober_lock_list(xp, &devs, &count) != XRT_SUCCESS) {
		return false;
	}
	bool found = false;
	for (size_t i = 0; i < ARRAY_SIZE(product_ids) && !found; i++) {
		found = u_builder_find_prober_device(devs, count, XREAL_VID,
			product_ids[i], XRT_BUS_TYPE_USB) != NULL;
	}
	xrt_prober_unlock_list(xp, &devs);
	return found;
}

static xrt_result_t estimate_system(struct xrt_builder *xb, cJSON *config,
		struct xrt_prober *xp, struct xrt_builder_estimate *estimate) {
	U_ZERO(estimate);
	estimate->certain.head = present(xp);
	return XRT_SUCCESS;
}

static xrt_result_t open_system(struct xrt_builder *xb, cJSON *config,
		struct xrt_prober *xp, struct xrt_tracking_origin *origin,
		struct xrt_system_devices *xsysd, struct xrt_frame_context *xfctx,
		struct u_builder_roles_helper *ubrh) {
	c8_glasses_log_level = debug_get_log_option_c8_glasses_log();
	struct xrt_device *head = c8_glasses_create();
	if (head == NULL) {
		return XRT_ERROR_DEVICE_CREATION_FAILED;
	}
	xsysd->xdevs[xsysd->xdev_count++] = head;
	ubrh->head = head;
	return XRT_SUCCESS;
}

static void builder_destroy(struct xrt_builder *xb) {
	free(xb);
}

struct xrt_builder *c8_glasses_builder_create(void) {
	struct u_builder *ub = U_TYPED_CALLOC(struct u_builder);
	ub->base.estimate_system = estimate_system;
	ub->base.open_system = u_builder_open_system_static_roles;
	ub->base.destroy = builder_destroy;
	ub->base.identifier = "c8_glasses";
	ub->base.name = "XREAL glasses (cont8nuum)";
	ub->base.driver_identifiers = driver_list;
	ub->base.driver_identifier_count = ARRAY_SIZE(driver_list);
	ub->open_system_static_roles = open_system;
	return &ub->base;
}
