views:

54

answers:

1

I have implemented my version of sutherland-hodgman polygon clipping algorithm, but I believe my implementation could be better. So I am wondering whether there is a standard implementation.

Here is my implementation

bool shclip(stPt** verts, int *n, float left, float right, float bottom, float top)
{
 if (leftclip(verts, n, left) &&
  rightclip(verts, n, right) &&
  bottomclip(verts, n, bottom) &&
  topclip(verts, n, top))
  return true;
 else
  return false;
}

bool leftclip(stPt** verts, int *n, float left)
{
 int v1, v2;
 float x1, x2, y1, y2;
 float relx, rely;

 v1 = v2 = 0;
 while (v1 < *n) {
  x1 = ((*verts)[v1]).x; 
  x2 = ((*verts)[(v1 + 1) % *n]).x;
  if (x1 < left) {
   if (x2 > left) {
    y1 = ((*verts)[v1]).y; y2 = ((*verts)[(v1 + 1) % *n]).y;
    relx = x2 - x1; rely = y2 - y1;
    nverts1[v2].y = (left - x1) * rely / relx + y1;
    nverts1[v2].x = left;
    nverts1[v2+1].y = ((*verts)[(v1 + 1) % *n]).y; 
    nverts1[v2+1].x = ((*verts)[(v1 + 1) % *n]).x;
    v2 += 2; 
   }

  } else {
   if (x2 > left) {
    nverts1[v2].x = ((*verts)[(v1 + 1) % *n]).x; nverts1[v2].y = ((*verts)[(v1 + 1) % *n]).y;
    v2++; 
   } else {
    y1 = ((*verts)[v1]).y; y2 = ((*verts)[(v1 + 1) % *n]).y;
    relx = x2 - x1; rely = y2 - y1;
    nverts1[v2].y = (left - x1) * rely / relx + y1;
    nverts1[v2].x = left;
    v2++; 
   }
  }
  v1++;
 }

 if (v2 != 0) {
  *n = v2;
  (*verts) = nverts1;
  return true;
 } else
  return false; 
}

Thanks.

EDIT
1 It seems that I do not understand the algorithm cause my textbook does not explain it clearly. I looked at the orignal thesis, but could not manage to figure it out.

2 The code I written is not retreent.

3 I pass the vertexs between two clipper by copy from one vertex array to another vertex array which is not efficient. I thought I could use linklist or something that is much better data structure for the algorithm.

4 What I mean with 'standard implementation' better to be the code implementated by the algorithm designer like nicholl-lee-nicholl or implementations in widly used standard library / graphic library.

A: 

What would you accept as a standard? Does it need to be coded by a "well known person"? Or published in a well-known ook, text-bjournal or website?

There are several C implementations out there against which you can compare yours (and of course the algorithm is widely published). Your code looks ok to me. What it is that you don't like about it?

I won't prove you that I can google, as I am sure that you can do that yourself, except to say that this looks like a good page. It is part of a thesis at the Florida Institute of Technology and explains the algorithm and gives a code listing which seems good.

Again, if you have any particular concerns about your own code, could you point them out? It looks fine to me.

LeonixSolutions