Question

I'm trying to create a vertex attribute array for storing vectors and indices in a mesh. I realise that vertex attributes can be made up from vector2, vector3 and/or vector4 so i'd like to create a class that caters for them all without constraining methods to return a certain type of object. As a test, i've written the following class making use of NSMutableData:

//VertexAttributeArray.h

@interface VertexAttributeArray : NSObject
{
    NSMutableData *vertexData;
}

- (void *)data;
- (CGRect *)rect;

//VertexAttributeArray.m

- (id)init
{
    self = [super init];

    if(self)
    {
        vertexData = [[NSMutableData alloc] initWithLength:0];
    }

    return self;
}

- (void *)data
{
    return [vertexData mutableBytes];
}

- (CGRect *)rect
{
    return [vertexData mutableBytes];
}

- (void)dealloc
{
    if(vertexData)
    {
        [vertexData release];
        vertexData = nil;
    }

    [super dealloc];
}

From within my mesh class, i'd like to be able to call something like:

VertexAttributeArray *vertexAttributeArray = [[VertexAttributeArray alloc] init];

[vertexAttributeArray data][0] = CGRectMake(0.0, 0.0, 0.0, 0.0); //doesn't work - compiler error
[vertexAttributeArray rect][0] = CGRectMake(0.0, 0.0, 0.0, 0.0); //works fine

The first method accessing data would be preferred as this doesn't constrain the class to work with a specific type of struct but Xcode just throws the warning "Incomplete type 'void' is not assignable."

I don't want to have multiple methods for different types of data structures but I can't see any way to get around this currently. Having methods that return pointers to different types doesn't look very elegant and adds a lot of vestigial unused (and unwanted) code.

Is there a way to work around this to create an agnostic data store? I'd prefer for my mesh class to have different VertexAttributeArray objects to store vertices, indices, normals and colours etc so storing vector2, vector3 and vector4 is ideally where i'd like to be. How would I work around achieving this?

Was it helpful?

Solution

There is no way to do what you want. It's not known at compile-time what size the objects inside data is. ((void *)foo)[x] would be illegal in C as well. The compiler must know what struct is stored inside the array for you to be able to index it.

You can change the call to:

((CGRect *)[vertexAttributeArray data])[0] = CGRectMake(0.0, 0.0, 0.0, 0.0);

if you prefer, since then it's known that there is sizeof(CGRect) distance between the objects inside data.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top