function img = rendervol(imgpath, volpath, texture)
% Renders a volume which has been generated by the VRN lua script.

vol = readvol(volpath, [192 192 200]);

im = imread(imgpath);

Q = isosurface(vol);
Q.vertices(:,3) = Q.vertices(:,3) * 0.5;
Q.EdgeColor = 'none';
Q.FaceColor = [120 154 194]/255;

if texture
    red = double(im(:,:,1));
    green = double(im(:,:,2));
    blue = double(im(:,:,3));
    [vcx,vcy] = meshgrid(1:192,1:192);
    vc = [vcx(:) vcy(:) red(:) green(:) blue(:)];
    cols = knnsearch(vc(:,1:2), Q.vertices(:,1:2));
    Q.FaceVertexCData = uint8(vc(cols,3:5));
    Q.FaceColor = 'interp';
end

figure
imshow(im, 'Border', 'tight');
hold on
patch(Q);
hold on
h = camlight;
lightangle(h, -10, 80)
lighting gouraud
material dull
view(0,90)
cap = getframe;
img = cap.cdata;
