I'm coding an applet that displays 2D vector fields in Processing.
On a 1000x1000 canvas, I'm drawing a 20-pixel-long arrow starting from every point identified by a grid on the canvas with a direction relative to the components of the vector calculated at that point. Now, I need to show a colormap of the divergence and a colormap of the curl of the field, where different colors are relative to different values of divergence (or curl). Given that the compiler by itself can't do differential operations (partial derivatives or, in this case, building the 2D scalar field of divergence), I need to find a different way.
MY APPROACH FOR DIVERGENCE: For each vector on the plane, I subtract (vector-subtract) the vector itself at the 4 nearby vector (the one above, below, right and left). I then dot-product the vector itself with each of the results of these 4 subtractions. I then find the average of the results of these dot products and I map it to the color value.
The color map that results is, though, not correct. My approach looks also very messy and, most of all, all the calculations done at every frame for every vector do really lower the framerate.
As Curl concerns, the method is the same, but the dot product is now a cross product. Do you suggest any other approach?
v is the vector itself
calcI and calcJ calculate the vector I and J component
PVector diff1 = PVector.sub(new PVector(calcI(x-1,y-1), calcJ(x-1,y-1)), v);
PVector diff2 = PVector.sub(new PVector(calcI(x,y-1), calcJ(x,y-1)), v);
PVector diff3 = PVector.sub(new PVector(calcI(x+1,y-1), calcJ(x+1,y-1)), v);
PVector diff4 = PVector.sub(new PVector(calcI(x-1,y), calcJ(x-1,y)), v);
PVector diff5 = PVector.sub(new PVector(calcI(x+1,y), calcJ(x+1, y)), v);
PVector diff6 = PVector.sub(new PVector(calcI(x-1,y+1), calcJ(x-1,y+1)), v);
PVector diff7 = PVector.sub(new PVector(calcI(x,y+1), calcJ(x,y+1)), v);
PVector diff8 = PVector.sub(new PVector(calcI(x+1,y+1), calcJ(x+1,y+1)), v);
diff1.normalize();
diff2.normalize();
diff3.normalize();
diff4.normalize();
diff5.normalize();
diff6.normalize();
diff7.normalize();
diff8.normalize();
v.normalize();
float divergence = (PVector.dot(v, diff1)+PVector.dot(v, diff2)+PVector.dot(v, diff3)+PVector.dot(v, diff4)+
PVector.dot(v, diff5)+PVector.dot(v, diff6)+PVector.dot(v, diff7)+PVector.dot(v, diff8))/8;
c = color( map(divergence, 0,1, 0,255) , 0, map(divergence, -1,0, 255,0) );
fill(c, 10);