1
0
Fork 0
mirror of https://github.com/opentx/opentx.git synced 2025-07-15 20:35:17 +03:00

Lua: All usage of double converted to float (#4502)

* Lua: All usage of double converted to float. printf("%f") still uses promotion to double, (floating point va_args are always promoted to double)
Speed improvements:
 * reordering of rotable to put most used tables at the top
 * caching of last found global table
Use real pointer to rotable instead of misusing void* to pass integer value
Lua internal traces now turned on by TRACE_LUA_INTERNALS cmake option

* Replaced floating point division with multiplication (where possible), the hardware FPU is much faster at multiplication vs division.
stb_image: enabled STBI_NO_HDR and STBI_NO_LINEAR (removes code that we don't need)
This commit is contained in:
Damjan Adamic 2017-02-26 12:59:39 +01:00 committed by Bertrand Songis
parent 3b149a22d1
commit a1a58ad8f8
16 changed files with 129 additions and 107 deletions

View file

@ -38,6 +38,7 @@ option(SIMU_LUA_COMPILER "Pre-compile and save Lua scripts in simulator." ON)
option(FAS_PROTOTYPE "Support of old FAS prototypes (different resistors)" OFF)
option(TEMPLATES "Model templates menu" OFF)
option(TRACE_SIMPGMSPACE "Turn on traces in simpgmspace.cpp" ON)
option(TRACE_LUA_INTERNALS "Turn on traces for Lua internals" OFF)
# since we reset all default CMAKE compiler flags for firmware builds, provide an alternate way for user to specify additional flags.
set(FIRMWARE_C_FLAGS "" CACHE STRING "Additional flags for firmware target c compiler (note: all CMAKE_C_FLAGS[_*] are ignored for firmware/bootloader).")
@ -320,6 +321,10 @@ if(TRACE_SIMPGMSPACE)
add_definitions(-DTRACE_SIMPGMSPACE)
endif()
if(TRACE_LUA_INTERNALS)
add_definitions(-DTRACE_LUA_INTERNALS_ENABLED)
endif()
if(EEPROM_VARIANT_NEEDED)
add_definitions(-DEEPROM_VARIANT=${EEPROM_VARIANT})
endif()

View file

@ -661,8 +661,8 @@ int ToneContext::mixBuffer(AudioBuffer * buffer, int volume, unsigned int fade)
if (fragment.tone.freq != state.freq) {
state.freq = fragment.tone.freq;
state.step = limit<float>(1, float(DIM(sineValues)*fragment.tone.freq) / AUDIO_SAMPLE_RATE, 512);
state.volume = evalVolumeRatio(fragment.tone.freq, volume);
state.step = limit<float>(1, float(fragment.tone.freq) * (float(DIM(sineValues))/float(AUDIO_SAMPLE_RATE)), 512);
state.volume = 1.0f / evalVolumeRatio(fragment.tone.freq, volume);
}
if (fragment.tone.freqIncr) {
@ -699,7 +699,7 @@ int ToneContext::mixBuffer(AudioBuffer * buffer, int volume, unsigned int fade)
}
for (int i=0; i<points; i++) {
int16_t sample = sineValues[int(toneIdx)] / state.volume;
int16_t sample = sineValues[int(toneIdx)] * state.volume;
mixSample(&buffer->data[i], sample, fade);
toneIdx += state.step;
if ((unsigned int)toneIdx >= DIM(sineValues))

View file

@ -813,7 +813,7 @@ int cliDisplay(const char ** argv)
else if (!strcmp(argv[1], "dc")) {
DiskCacheStats stats = diskCache.getStats();
uint32_t hitRate = diskCache.getHitRate();
serialPrint("Disk Cache stats: w:%u r: %u, h: %u(%0.1f%%), m: %u", stats.noWrites, (stats.noHits + stats.noMisses), stats.noHits, hitRate/10.0f, stats.noMisses);
serialPrint("Disk Cache stats: w:%u r: %u, h: %u(%0.1f%%), m: %u", stats.noWrites, (stats.noHits + stats.noMisses), stats.noHits, hitRate*0.1f, stats.noMisses);
}
#endif
else if (toLongLongInt(argv, 1, &address) > 0) {

View file

@ -35,22 +35,22 @@ extern "C" {
#endif
#if defined(SIMU)
typedef void (*traceCallbackFunc)(const char * text);
extern traceCallbackFunc traceCallback;
void debugPrintf(const char * format, ...);
typedef void (*traceCallbackFunc)(const char * text);
extern traceCallbackFunc traceCallback;
void debugPrintf(const char * format, ...);
#elif defined(SEMIHOSTING)
#include <stdio.h>
#define debugPrintf(...) printf(__VA_ARGS__)
#include <stdio.h>
#define debugPrintf(...) printf(__VA_ARGS__)
#elif defined(DEBUG) && defined(CLI) && defined(USB_SERIAL)
#define debugPrintf(...) do { if (cliTracesEnabled) serialPrintf(__VA_ARGS__); } while(0)
#define debugPrintf(...) do { if (cliTracesEnabled) serialPrintf(__VA_ARGS__); } while(0)
#elif defined(DEBUG) && defined(CLI)
uint8_t serial2TracesEnabled();
#define debugPrintf(...) do { if (serial2TracesEnabled() && cliTracesEnabled) serialPrintf(__VA_ARGS__); } while(0)
uint8_t serial2TracesEnabled();
#define debugPrintf(...) do { if (serial2TracesEnabled() && cliTracesEnabled) serialPrintf(__VA_ARGS__); } while(0)
#elif defined(DEBUG) && defined(CPUARM)
uint8_t serial2TracesEnabled();
#define debugPrintf(...) do { if (serial2TracesEnabled()) serialPrintf(__VA_ARGS__); } while(0)
uint8_t serial2TracesEnabled();
#define debugPrintf(...) do { if (serial2TracesEnabled()) serialPrintf(__VA_ARGS__); } while(0)
#else
#define debugPrintf(...)
#define debugPrintf(...)
#endif
#if defined(__cplusplus)
@ -68,6 +68,12 @@ uint8_t serial2TracesEnabled();
#define TRACE_WARNING_WP(...) debugPrintf(__VA_ARGS__)
#define TRACE_ERROR(...) debugPrintf("-E- " __VA_ARGS__)
#if defined(TRACE_LUA_INTERNALS_ENABLED)
#define TRACE_LUA_INTERNALS(f_, ...) debugPrintf(("[LUA INT] " f_ "\r\n"), ##__VA_ARGS__)
#else
#define TRACE_LUA_INTERNALS(...)
#endif
#if defined(DEBUG) && !defined(SIMU)
#define TIME_MEASURE_START(id) uint16_t t0 ## id = getTmr2MHz()
#define TIME_MEASURE_STOP(id) TRACE("Measure(" # id ") = %.1fus", float((uint16_t)(getTmr2MHz() - t0 ## id))/2)

View file

@ -176,7 +176,7 @@ bool evalSlopes(int * slopes, int startAngle, int endAngle)
slopes[2] = -100000;
}
else {
float angle1 = float(startAngle) * PI / 180.0f;
float angle1 = float(startAngle) * (PI / 180.0f);
if (startAngle >= 180) {
slopes[1] = -100000;
slopes[2] = cosf(angle1) * 100 / sinf(angle1);
@ -192,7 +192,7 @@ bool evalSlopes(int * slopes, int startAngle, int endAngle)
slopes[3] = 100000;
}
else {
float angle2 = float(endAngle) * PI / 180;
float angle2 = float(endAngle) * (PI / 180.0f);
if (endAngle >= 180) {
slopes[0] = -100000;
slopes[3] = -cosf(angle2) * 100 / sinf(angle2);
@ -701,6 +701,8 @@ BitmapBuffer * BitmapBuffer::load_bmp(const char * filename)
#define STBI_ONLY_BMP
#define STBI_ONLY_GIF
#define STBI_NO_STDIO
#define STBI_NO_HDR
#define STBI_NO_LINEAR
// #define TRACE_STB_MALLOC

View file

@ -153,10 +153,10 @@ static void luaPushLatLon(lua_State* L, TelemetrySensor & telemetrySensor, Telem
/* result is lua table containing members ["lat"] and ["lon"] as lua_Number (doubles) in decimal degrees */
{
lua_createtable(L, 0, 4);
lua_pushtablenumber(L, "lat", telemetryItem.gps.latitude / 1000000.0);
lua_pushtablenumber(L, "pilot-lat", telemetryItem.pilotLatitude / 1000000.0);
lua_pushtablenumber(L, "lon", telemetryItem.gps.longitude / 1000000.0);
lua_pushtablenumber(L, "pilot-lon", telemetryItem.pilotLongitude / 1000000.0);
lua_pushtablenumber(L, "lat", telemetryItem.gps.latitude * 0.000001f); // floating point multiplication is faster than division
lua_pushtablenumber(L, "pilot-lat", telemetryItem.pilotLatitude * 0.000001f);
lua_pushtablenumber(L, "lon", telemetryItem.gps.longitude * 0.000001f);
lua_pushtablenumber(L, "pilot-lon", telemetryItem.pilotLongitude * 0.000001f);
}
static void luaPushTelemetryDateTime(lua_State* L, TelemetrySensor & telemetrySensor, TelemetryItem & telemetryItem)
@ -173,7 +173,7 @@ static void luaPushCells(lua_State* L, TelemetrySensor & telemetrySensor, Teleme
lua_createtable(L, telemetryItem.cells.count, 0);
for (int i = 0; i < telemetryItem.cells.count; i++) {
lua_pushnumber(L, i + 1);
lua_pushnumber(L, telemetryItem.cells.values[i].value / 100.0);
lua_pushnumber(L, telemetryItem.cells.values[i].value * 0.01f);
lua_settable(L, -3);
}
}
@ -215,7 +215,7 @@ void luaGetValueAndPush(lua_State* L, int src)
}
}
else if (src == MIXSRC_TX_VOLTAGE) {
lua_pushnumber(L, float(value)/10.0);
lua_pushnumber(L, float(value) * 0.1f);
}
else {
lua_pushinteger(L, value);
@ -851,8 +851,8 @@ Returns (some of) the general radio settings
static int luaGetGeneralSettings(lua_State * L)
{
lua_newtable(L);
lua_pushtablenumber(L, "battMin", double(90+g_eeGeneral.vBatMin)/10);
lua_pushtablenumber(L, "battMax", double(120+g_eeGeneral.vBatMax)/10);
lua_pushtablenumber(L, "battMin", (90+g_eeGeneral.vBatMin) * 0.1f);
lua_pushtablenumber(L, "battMax", (120+g_eeGeneral.vBatMax) * 0.1f);
lua_pushtableinteger(L, "imperial", g_eeGeneral.imperial);
lua_pushtablestring(L, "language", TRANSLATIONS);
lua_pushtablestring(L, "voice", currentLanguagePack->id);

View file

@ -619,15 +619,17 @@ LUA_API int lua_pushthread (lua_State *L) {
LUA_API void lua_getglobal (lua_State *L, const char *var) {
TValue value;
luaR_result found;
TRACE_LUA_INTERNALS("lua_getglobal() '%s'", var);
Table *reg = hvalue(&G(L)->l_registry);
const TValue *gt; /* global table */
lua_lock(L);
lu_byte keytype;
luaR_result res = luaR_findglobal(var, &keytype);
if (res != 0) {
found = luaR_findglobal(var, &value);
if (found && ttislightfunction(&value)) {
setsvalue2s(L, L->top++, luaS_new(L, var));
setlfvalue(L->top - 1, (void*)(size_t)res)
setlfvalue(L->top - 1, lfvalue(&value))
}
else {
gt = luaH_getint(reg, LUA_RIDX_GLOBALS);

View file

@ -958,7 +958,7 @@ void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
(void)ud; (void)osize; /* not used */
if (nsize == 0) {
if (ptr) { // avoid a bunch of NULL pointer free calls
// TRACE("free %p", ptr); FLUSH();
// TRACE_LUA_INTERNALS("free %p", ptr); FLUSH();
free(ptr);
}
return NULL;

View file

@ -207,10 +207,10 @@ void luaD_shrinkstack (lua_State *L) {
int goodsize = inuse + (inuse / 8) + 2*EXTRA_STACK;
if ((L->stacksize - goodsize) < 40) {
//skip shrink
// TRACE("luaD_shrinkstack(skip): L->stacksize: %d, goodsize: %d", L->stacksize, goodsize);
// TRACE_LUA_INTERNALS("luaD_shrinkstack(skip): L->stacksize: %d, goodsize: %d", L->stacksize, goodsize);
return;
}
// TRACE("luaD_shrinkstack(): L->stacksize: %d, goodsize: %d", L->stacksize, goodsize);
// TRACE_LUA_INTERNALS("luaD_shrinkstack(): L->stacksize: %d, goodsize: %d", L->stacksize, goodsize);
if (goodsize > LUAI_MAXSTACK) goodsize = LUAI_MAXSTACK;
if (inuse > LUAI_MAXSTACK || /* handling stack overflow? */
goodsize >= L->stacksize) /* would grow instead of shrink? */

View file

@ -43,14 +43,14 @@ static const luaL_Reg loadedlibs[] = {
/* The read-only tables are defined here */
const luaR_table lua_rotable[] =
{
{LUA_MATHLIBNAME, mathlib, mathlib_vals},
{LUA_BITLIBNAME, bitlib, NULL},
{LUA_IOLIBNAME, iolib, NULL},
{LUA_STRLIBNAME, strlib, NULL},
{"__opentx", opentxLib, opentxConstants},
{"lcd", lcdLib, NULL},
{"model", modelLib, NULL},
{"__baselib", baselib, NULL},
{"__opentx", opentxLib, opentxConstants},
{LUA_IOLIBNAME, iolib, NULL},
{LUA_STRLIBNAME, strlib, NULL},
{LUA_MATHLIBNAME, mathlib, mathlib_vals},
{LUA_BITLIBNAME, bitlib, NULL},
{NULL, NULL, NULL}
};

View file

@ -80,7 +80,7 @@ void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) {
if (nsize > realosize && g->gcrunning)
luaC_fullgc(L, 1); /* force a GC whenever possible */
#endif
// TRACE("ALLOC %d %d", (int)osize, (int)nsize);
// TRACE_LUA_INTERNALS("ALLOC %d %d", (int)osize, (int)nsize);
newblock = (*g->frealloc)(g->ud, block, osize, nsize);
if (newblock == NULL && nsize > 0) {
api_check(L, nsize > realosize,

View file

@ -10,77 +10,93 @@
#define LUAR_FINDVALUE 1
/* Utility function: find a key in a given table (of functions or constants) */
static luaR_result luaR_findkey(const void *where, const char *key, int type, int *found) {
static luaR_result luaR_findkey(const void * where, const char * key, int type, TValue * found) {
const char *pname;
const luaL_Reg *pf = (luaL_Reg*)where;
const luaR_value_entry *pv = (luaR_value_entry*)where;
int isfunction = type == LUAR_FINDFUNCTION;
*found = 0;
if(!where)
return 0;
while(1) {
if (!(pname = isfunction ? pf->name : pv->name))
break;
if (!strcmp(pname, key)) {
*found = 1;
return isfunction ? (luaR_result)(size_t)pf->func : (luaR_result)pv->value;
if (isfunction) {
setlfvalue(found, pf->func);
}
else {
setnvalue(found, pv->value);
}
return 1;
}
pf ++; pv ++;
}
return 0;
}
/* Find a global "read only table" in the constant lua_rotable array */
luaR_result luaR_findglobal(const char *name, lu_byte *ptype) {
unsigned i;
*ptype = LUA_TNIL;
if (strlen(name) > LUA_MAX_ROTABLE_NAME)
char luaR_cachedName[LUA_MAX_ROTABLE_NAME + 1] = {0};
TValue luaR_cachedValue;
static inline void luaR_saveLastFoundGlobal(const char * name, const TValue * val)
{
strcpy(luaR_cachedName, name);
luaR_cachedValue = *val;
}
static inline luaR_result luaR_checkLastFoundGlobal(const char * name, TValue * val)
{
if (!strcmp(luaR_cachedName, name)) {
*val = luaR_cachedValue;
return 1;
}
return 0;
}
/* Find a global "read only table" in the constant lua_rotable array */
luaR_result luaR_findglobal(const char * name, TValue * val) {
unsigned i;
if (strlen(name) > LUA_MAX_ROTABLE_NAME) {
TRACE_LUA_INTERNALS("luaR_findglobal('%s') = NAME TOO LONG", name);
return 0;
}
if (luaR_checkLastFoundGlobal(name, val)){
TRACE_LUA_INTERNALS("luaR_findglobal('%s') = CACHED", name);
return 1;
}
for (i=0; lua_rotable[i].name; i++) {
void * table = (void *)(&lua_rotable[i]);
if (!strcmp(lua_rotable[i].name, name)) {
*ptype = LUA_TROTABLE;
return i+1;
setrvalue(val, table);
luaR_saveLastFoundGlobal(name, val);
TRACE_LUA_INTERNALS("luaR_findglobal('%s') = TABLE %p (%s)", name, table, lua_rotable[i].name);
return 1;
}
if (!strncmp(lua_rotable[i].name, "__", 2)) {
luaR_result result = luaR_findentry((void *)(size_t)(i+1), name, ptype);
if (result != 0) {
return result;
}
}
}
return 0;
}
int luaR_findfunction(lua_State *L, const luaL_Reg *ptable) {
int found;
const char *key = luaL_checkstring(L, 2);
luaR_result res = luaR_findkey(ptable, key, LUAR_FINDFUNCTION, &found);
if (found)
lua_pushlightfunction(L, (void*)(size_t)res);
else
lua_pushnil(L);
if (luaR_findentry(table, name, val)) {
// luaR_saveLastFoundGlobal(name, val);
TRACE_LUA_INTERNALS("luaR_findglobal('%s') = FOUND in table '%s'", name, lua_rotable[i].name);
return 1;
}
luaR_result luaR_findentry(void *data, const char *key, lu_byte *ptype) {
int found;
unsigned idx = (unsigned)(size_t)data - 1;
luaR_result res;
*ptype = LUA_TNIL;
/* First look at the functions */
res = luaR_findkey(lua_rotable[idx].pfuncs, key, LUAR_FINDFUNCTION, &found);
if (found) {
*ptype = LUA_TLIGHTFUNCTION;
return res;
}
else {
/* Then at the values */
res = luaR_findkey(lua_rotable[idx].pvalues, key, LUAR_FINDVALUE, &found);
if(found) {
*ptype = LUA_TNUMBER;
return res;
}
}
}
TRACE_LUA_INTERNALS("luaR_findglobal() '%s' = NOT FOUND", name);
return 0;
}
luaR_result luaR_findentry(void *data, const char * key, TValue * val) {
luaR_table * table = (luaR_table *)data;
/* First look at the functions */
if (luaR_findkey(table->pfuncs, key, LUAR_FINDFUNCTION, val)) {
TRACE_LUA_INTERNALS("luaR_findentry(%p[%s], '%s') = FUNCTION %p", table, table->name, key, lfvalue(val));
return 1;
}
else if (luaR_findkey(table->pvalues, key, LUAR_FINDVALUE, val)) {
/* Then at the values */
TRACE_LUA_INTERNALS("luaR_findentry(%p[%s], '%s') = NUMBER %g", table, table->name, key, nvalue(val));
return 1;
}
TRACE_LUA_INTERNALS("luaR_findentry(%p[%s], '%s') = NOT FOUND", table, table->name, key);
return 0;
}

View file

@ -6,8 +6,9 @@
#include "lua.h"
#include "llimits.h"
#include "lauxlib.h"
#include "lobject.h"
typedef lua_Number luaR_result;
typedef uint8_t luaR_result;
// A number entry in the read only table
typedef struct
@ -30,8 +31,7 @@ typedef struct
extern const luaR_table lua_rotable[];
luaR_result luaR_findglobal(const char *key, lu_byte *ptype);
int luaR_findfunction(lua_State *L, const luaL_Reg *ptable);
luaR_result luaR_findentry(void *data, const char *key, lu_byte *ptype);
luaR_result luaR_findglobal(const char * name, TValue * val);
luaR_result luaR_findentry(void * data, const char * key, TValue * val);
#endif

View file

@ -398,8 +398,8 @@
** ===================================================================
*/
#define LUA_NUMBER_DOUBLE
#define LUA_NUMBER double
#define LUA_NUMBER_FLOAT
#define LUA_NUMBER float
/*
@@ LUAI_UACNUMBER is the result of an 'usual argument conversion'
@ -414,8 +414,8 @@
@@ lua_number2str converts a number to a string.
@@ LUAI_MAXNUMBER2STR is maximum size of previous conversion.
*/
#define LUA_NUMBER_SCAN "%lf"
#define LUA_NUMBER_FMT "%.14g"
#define LUA_NUMBER_SCAN "%f"
#define LUA_NUMBER_FMT "%.7g"
#define lua_number2str(s,n) sprintf((s), LUA_NUMBER_FMT, (n))
#define LUAI_MAXNUMBER2STR 32 /* 16 digits, sign, point, and \0 */
@ -423,7 +423,7 @@
/*
@@ l_mathop allows the addition of an 'l' or 'f' to all math operations
*/
#define l_mathop(x) (x)
#define l_mathop(x) (x##f)
/*
@ -434,10 +434,10 @@
** systems, you can leave 'lua_strx2number' undefined and Lua will
** provide its own implementation.
*/
#define lua_str2number(s,p) strtod((s), (p))
#define lua_str2number(s,p) strtof((s), (p))
#if defined(LUA_USE_STRTODHEX)
#define lua_strx2number(s,p) strtod((s), (p))
#define lua_strx2number(s,p) strtof((s), (p))
#endif

View file

@ -121,14 +121,9 @@ void luaV_gettable (lua_State *L, const TValue *t, TValue *key, StkId val) {
setnilvalue(val);
if (ttisstring(key)) {
char keyname[LUA_MAX_ROTABLE_NAME + 1];
lu_byte keytype;
lua_getcstr(keyname, rawtsvalue(key), LUA_MAX_ROTABLE_NAME);
// TRACE("luaV_gettable(key=%s)", keyname);
luaR_result res = luaR_findentry(rvalue(t), keyname, &keytype);
if (keytype == LUA_TLIGHTFUNCTION)
setlfvalue(val, (void*)(size_t)res)
else if (keytype == LUA_TNUMBER)
setnvalue(val, (lua_Number)res)
TRACE_LUA_INTERNALS("luaV_gettable(%s)", keyname);
luaR_findentry(rvalue(t), keyname, val);
}
return;
}
@ -627,23 +622,15 @@ void luaV_execute (lua_State *L) {
int b = GETARG_B(i);
if (ttisstring(RKC(i))) {
char keyname[LUA_MAX_ROTABLE_NAME + 1];
lu_byte keytype;
lua_getcstr(keyname, rawtsvalue(RKC(i)), LUA_MAX_ROTABLE_NAME);
luaR_result res = luaR_findglobal(keyname, &keytype);
if (keytype == LUA_TROTABLE) {
setrvalue(ra, (void*)(size_t)res)
TRACE_LUA_INTERNALS("luaV_execute(OP_GETTABUP, %s)", keyname);
if (luaR_findglobal(keyname, ra)) {
break;
}
else if (keytype == LUA_TLIGHTFUNCTION)
setlfvalue(ra, (void*)(size_t)res)
else if (keytype == LUA_TNUMBER)
setnvalue(ra, (lua_Number)res)
else
}
TRACE_LUA_INTERNALS("luaV_execute(OP_GETTABUP, %d) OLD WAY", b);
Protect(luaV_gettable(L, cl->upvals[b]->v, RKC(i), ra));
}
else {
Protect(luaV_gettable(L, cl->upvals[b]->v, RKC(i), ra));
}
}
break;
case OP_GETTABLE:

View file

@ -1190,10 +1190,14 @@ STBIDEF void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; }
STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; }
#endif
#ifndef STBI_NO_HDR
static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f;
STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1/gamma; }
STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1/scale; }
#endif // STBI_NO_HDR
//////////////////////////////////////////////////////////////////////////////