Individual Instance Coloring

So I had a bit o free time today and decided to try and individually color the instances I’ve created with my geo shader. With a bit of googling I found an article on explaining how to attach data to an instance and then look it up from the shader side. I decided to attach the UV coordinates of where each instance is placed on the parent surface and then use those to get a color in a utility shader. This way u just add this utility shader to your shading network and connect a map to query.

This is how I drop the info into the instance:

		sprintf(uv_coord_name, "uv%i", i);
		miVector uv_coord;
		uv_coord.x = state->tex_list[0].x;
		uv_coord.y = state->tex_list[0].y;
		uv_coord.z = 0;
		int data_size = sizeof(uv_data );
		uv_data *objdata = (uv_data *)mi_mem_allocate( data_size );
		objdata->uv_vector = uv_coord;
		miUserdata *udata = mi_api_data_begin( mi_mem_strdup(uv_coord_name), 0, (void*) data_size );
		mi_api_data_byte_copy( data_size, (miUchar*)objdata );
		miTag newdatatag = mi_api_data_end();
		inst->userdata = mi_api_data_append(newdatatag, inst->userdata);

And here is where I pluck it back out in the utility shader:

		miVector uv;
        int size;
	miTag user_data_tag;
        struct uv_data *user_data;

        if (mi_query(miQ_INST_DATA, state, state->instance, &user_data_tag) &&
	    mi_query(miQ_DATA_PARAM_SIZE, state, user_data_tag, &size) &&
	    mi_query(miQ_DATA_PARAM, state, user_data_tag, &user_data) &&
            size == sizeof(struct uv_data)) {

	  if (user_data->uv_vector) {
		uv = *mi_eval_vector(user_data->uv_vector);
		state->tex_list[0].x = uv.x;
		state->tex_list[0].y = uv.y;
		result = *mi_eval_color(param->input_color);
		return miTRUE;
	  *result = user_data->default_color;
	  result->a = 1.0;


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: