Any way to refactor this code? [ dynamic casting point() ]

   397   1   1
User Avatar
Member
900 posts
Joined: 2月 2016
Offline
I made a Vex function that takes any float, vector2, vector, and vector4 attribute and unroll the value of each component into an array.
For example:
if u@attrib1 = {0.1, 0.4},  the resulting array should be [0.1, 0.4]

Here it's my attempt, with a messy but working function, and another simpler but not working function.
Do you have any idea how to refactor this code?
(I attach also the .hip file for your convenience)


void unroll_OK(int ptnum; int attrib_size; string attrib_name; float attrib_values[])
{
    if (attrib_size == 1) { // Single float value
        attrib_values[0] = point(0, attrib_name, ptnum);
    } else if (attrib_size == 2) { // Vector2 value
        vector2 val = point(0, attrib_name, ptnum);
        for (int i = 0; i < attrib_size; i++) {
            attrib_values[i] = val[i];
        }
    } else if (attrib_size == 3) { // Vector value
        vector val = point(0, attrib_name, ptnum);
        for (int i = 0; i < attrib_size; i++) {
            attrib_values[i] = val[i];
        }
    } else if (attrib_size == 4) { // Vector4 value
        vector4 val = point(0, attrib_name, ptnum);
        for (int i = 0; i < attrib_size; i++) {
            attrib_values[i] = val[i];
        }
    }
}


// Simpler, but not working 
void unroll_badRefactor(int ptnum; int attrib_size; string attrib_name; float attrib_values[])
{
    // Use the largest vector type (vector4) and then extract the needed components
    vector4 val = point(0, attrib_name, ptnum);  // I don't know how to dynamically cast the attrib to its the correct data type
    for (int i = 0; i < attrib_size; i++) {
        attrib_values[i] = val[i];
    }
}



string attrib_name = "attrib1";
int attrib_size = attribsize(0, "point", attrib_name);


float unroll_OK[];
unroll_OK(@ptnum, attrib_size,  attrib_name, unroll_OK);
f[]@unroll_OK = unroll_OK;


float unroll_badRefactor[];
unroll_badRefactor(@ptnum, attrib_size,  attrib_name, unroll_badRefactor);
f[]@unroll_badRefactor = unroll_badRefactor;
Edited by Andr - 2023年12月1日 21:59:08

Attachments:
unroll_components_to_array.hiplc (73.1 KB)

User Avatar
Member
46 posts
Joined: 4月 2016
Offline
i assume you need function overloading link [www.sidefx.com]
Edited by vicvvsh - 2023年12月2日 01:03:07
  • Quick Links