britzl / extension-imgui

Dear ImGUI extension for Defold
MIT License
58 stars 19 forks source link

input_float #10

Closed 8bitskull closed 3 years ago

8bitskull commented 3 years ago

We have input_int and input_float3/4, but not input_float. The latter would be useful!

8bitskull commented 3 years ago

I actually gave it a stab myself by looking at the other functions and made it work! Given I've never touched C++ before I'm pretty happy.

static int imgui_InputFloat(lua_State* L)
{
    DM_LUA_STACK_CHECK(L, 2);
    imgui_NewFrame();
    const char* label = luaL_checkstring(L, 1);
    float value = luaL_checknumber(L, 2);
    bool changed = ImGui::InputFloat(label, &value);
    lua_pushboolean(L, changed);
    if (changed)
    {
        lua_pushnumber(L, value);
    }
    else
    {
        lua_pushnil(L);
    }
    return 2;
}

However, I note that floats in C++ or imgui have automated rounding. I realised I could change the decimal precision, for example by setting "changed" to this:

bool changed = ImGui::InputFloat(label, &value,  0.01f, 1.0f, "%.10f");

But that raises the question: What decimal precision is right? Or should it be offered as an option? If the latter, then my C++ knowledge is definitely not enough.

I'm also not sure what the step and step_fast (the two values preceeding the format value) should be.

britzl commented 3 years ago

I actually gave it a stab myself by looking at the other functions and made it work! Given I've never touched C++ before I'm pretty happy.

Cool! I'm happy to hear that you gave it a try!

Or should it be offered as an option?

Yes, definitely an option! You can check if an argument is a number before reading it and if it is not a number (ie nil or something that can't be converted) you set a default. Example:

float step = 0.01f; // default value
// check if the third argument is a number
if (lua_isnumber(L, 3)
{
    step = luaL_checknumber(L, 3);  // read the third argument
}
8bitskull commented 3 years ago

Makes sense for step and step_fast. What about checking/setting the default decimal precision ("%.3f")?

dlannan commented 3 years ago

Precision in Lua is all double (when it gets to lua side). I would personally leave the function to use float with how you have it above. Remember this is for input - you really shouldnt be typing in large precision numbers, and if you are it needs to be double anyway so we can add a "input_double" if needed down the track.

britzl commented 3 years ago

Closed by #11