Coloring Particles

The ParticleBlinkScript node can be used to change the color of particles according to things like their age or velocity. The following example kernel changes the color of particles over their lifetime. Individual knobs for four colors are created and a Catmull-Rom spline is used to interpolate smoothly between the colors as the particles age.

The resulting effect of the following particle coloring kernel

Example node graph for the following kernel

kernel ParticleColorKernel : ImageComputationKernel<ePixelWise>

{

Image<eReadWrite> p_color;

Image<eReadWrite> p_startTime;

Image<eReadWrite> p_life;

 

param:

float4 _color1;

float4 _color2;

float4 _color3;

float4 _color4;

float _systemTime;

 

local:

float4 _colors[6];

 

void define() {

defineParam(_color1, "pa_color1", float4(1.0f, 0.0f, 0.0f, 1.0f));

defineParam(_color2, "pa_color2", float4(1.0f, 0.0f, 0.0f, 1.0f));

defineParam(_color3, "pa_color3", float4(1.0f, 0.0f, 0.0f, 1.0f));

defineParam(_color4, "pa_color4", float4(1.0f, 0.0f, 0.0f, 1.0f));

defineParam(_systemTime, "_systemTime", 0.0f);

}

 

void init() {

// Repeat the first and last color for the spline tangents

_colors[0] = _color1;

_colors[1] = _color1;

_colors[2] = _color2;

_colors[3] = _color3;

_colors[4] = _color4;

_colors[5] = _color4;

}

 

// Catmull-Rom spline

float4 spline(float x, int numKnots)

{

int numSpans = numKnots - 1;

 

float t = max(0.0f, min(1.0f, x)) * (numSpans-2);

int span = int(floor(t));

t -= span;

 

float4 k0 = _colors[span];

float4 k1 = _colors[span+1];

float4 k2 = _colors[min(numSpans, span+2)];

float4 k3 = _colors[min(numSpans, span+3)];

 

return 0.5f*(2.0f*k1

+ (-k0 + k2)*t

+ (2.0f*k0 - 5.0f*k1 + 4.0f*k2 - k3)*t*t

+ (-k0 + 3.0f*k1 - 3.0f*k2 + k3)*t*t*t);

}

 

void process() {

float t = (_systemTime-p_startTime())/p_life();

p_color() = spline(t, 6);

}

};