Skip to content

Instantly share code, notes, and snippets.

@maxkarelov
Last active September 14, 2020 22:26
Show Gist options
  • Save maxkarelov/293b5e4235c1e7dcdb40 to your computer and use it in GitHub Desktop.
Save maxkarelov/293b5e4235c1e7dcdb40 to your computer and use it in GitHub Desktop.
Code of Cohen-Sutherland Algoritm for Line Clipping in C++ Programming language
// Cohen–Sutherland Algorithm
bool clip(point &A, point &B, point Pmin, point Pmax) {
while (true) {
unsigned int C1 = 0;
if (A.x < Pmin.x) C1 += 1;
if (A.x > Pmax.x) C1 += 2;
if (A.y < Pmin.y) C1 += 4;
if (A.y > Pmax.y) C1 += 8;
unsigned int C2 = 0;
if (B.x < Pmin.x) C2 += 1;
if (B.x > Pmax.x) C2 += 2;
if (B.y < Pmin.y) C2 += 4;
if (B.y > Pmax.y) C2 += 8;
if ((C1 == C2) && (C1 == 0)) return true;
if ((C1 & C2) != 0) return false;
if (C1 == 0) {
std::swap(A, B);
}
if ((C1 & 1) != 0) {
A.y = B.y - (B.x - Pmin.x) * (B.y - A.y) / (B.x - A.x);
A.x = Pmin.x;
} else if ((C1 & 2) != 0) {
A.y = B.y - (B.x - Pmax.x) * (B.y - A.y) / (B.x - A.x);
A.x = Pmax.x;
} else if ((C1 & 4) != 0) {
A.x = B.x - (B.y - Pmin.y) * (B.x - A.x) / (B.y - A.y);
A.y = Pmin.y;
} else if ((C1 & 8) != 0) {
A.x = B.x - (B.y - Pmax.y) * (B.x - A.x) / (B.y - A.y);
A.y = Pmax.y;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment