From fd3483c83730a0a59f7b731e9cceabacb759ab20 Mon Sep 17 00:00:00 2001 From: Romain Vimont Date: Wed, 3 Aug 2022 15:17:44 +0200 Subject: [PATCH] Extract conversion from float to u16 fixed-point PR #3369 --- app/src/control_msg.c | 12 +----------- app/src/util/binary.h | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/app/src/control_msg.c b/app/src/control_msg.c index 0d68c45c..4aa0944c 100644 --- a/app/src/control_msg.c +++ b/app/src/control_msg.c @@ -78,16 +78,6 @@ write_string(const char *utf8, size_t max_len, unsigned char *buf) { return 4 + len; } -static uint16_t -to_fixed_point_16(float f) { - assert(f >= 0.0f && f <= 1.0f); - uint32_t u = f * 0x1p16f; // 2^16 - if (u >= 0xffff) { - u = 0xffff; - } - return (uint16_t) u; -} - size_t sc_control_msg_serialize(const struct sc_control_msg *msg, unsigned char *buf) { buf[0] = msg->type; @@ -109,7 +99,7 @@ sc_control_msg_serialize(const struct sc_control_msg *msg, unsigned char *buf) { sc_write64be(&buf[2], msg->inject_touch_event.pointer_id); write_position(&buf[10], &msg->inject_touch_event.position); uint16_t pressure = - to_fixed_point_16(msg->inject_touch_event.pressure); + sc_float_to_u16fp(msg->inject_touch_event.pressure); sc_write16be(&buf[22], pressure); sc_write32be(&buf[24], msg->inject_touch_event.buttons); return 28; diff --git a/app/src/util/binary.h b/app/src/util/binary.h index e77f5e82..734ab1d0 100644 --- a/app/src/util/binary.h +++ b/app/src/util/binary.h @@ -3,6 +3,7 @@ #include "common.h" +#include #include #include @@ -43,4 +44,18 @@ sc_read64be(const uint8_t *buf) { return ((uint64_t) msb << 32) | lsb; } +/** + * Convert a float between 0 and 1 to an unsigned 16-bit fixed-point value + */ +static inline uint16_t +sc_float_to_u16fp(float f) { + assert(f >= 0.0f && f <= 1.0f); + uint32_t u = f * 0x1p16f; // 2^16 + if (u >= 0xffff) { + assert(u == 0x10000); // for f == 1.0f + u = 0xffff; + } + return (uint16_t) u; +} + #endif