code of Liang-Barsky Clipping in opengl (java)

本文介绍Liang-Barsky线段裁剪算法的实现细节,包括2D及3D裁剪过程,并提供了OpenGL及Java代码示例。
 code of Liang-Barsky Line Clipping in opengl

base on my <<computer grapgics>>'s code

typedef struct dcPttype{
float x;
float y;
}
dcPt;

typedef 
struct wcPt2type{
float x;
float y;
}
wcPt2;

#define ROUND(a) ((int)(a+0.5))
#define TRUE 1
#define FALSE 0

int clipTest(float p,float q,float *u1,float *u2)
{
float r;
int retVal=TRUE;
if(p<0.0)
{
r
=q/p;
if(r>*u2)
retVal
=FALSE;
else if(r>*u1)
*u1=r;
}

else
if(p>0.0)
{
r
=q/p;
if(r<*u1)
retVal
=FALSE;
else if(r<*u2)
*u2=r;
}

else
if(q<0.0)
retVal
=FALSE;
return (retVal);
}


void clipLine(dcPt winMin,dcPt winMax,wcPt2 p1,wcPt2 p2)
{
  
float u1=0.0f,u2=1.0f,dx=p2.x-p1.x,dy;
  
if(clipTest(-dx,p1.x-winMin.x,&u1,&u2)&&(choice>2))
  
{
if(clipTest(dx,winMax.x-p1.x,&u1,&u2))
{
 dy
=p2.y-p1.y;
 
if(clipTest(-dy,p1.y-winMin.y,&u1,&u2))
if(clipTest(dy,winMax.y-p1.y,&u1,&u2))
{
 
if(u2<1.0)
 
{
  p2.x
=p1.x+u2*dx;
  p2.y
=p1.y+u2*dy;
 }

 
if(u1>0.0)
 
{
  p1.x
+=u1*dx;
  p1.y
+=u1*dy;
 }

     
//draw the clipped line...
 glColor3f(1,1,1);
 glBegin(GL_LINES);
 glVertex3f(ROUND(p1.x), ROUND(p1.y), 
0.0);
 glVertex3f(ROUND(p2.x), ROUND(p2.y), 
0.0);
 glEnd();
}

}

  }

}

You can find guide of Liang-Barsky line clipping everywhere ,read them for details...
I found that Liang is the only Chinese talked by every computer graphic book. IM LOOKING FORWARD THERE WILL BE MORE LIANGS......


下面是liang barsky 3d线段裁减的java代码,用的是定点数
liang barsky 3D line clipping, based on cldc1 (no float but fixed point)(code)

   

 private static boolean clipTest(int fp_p, int fp_q, int [] fp_u){
        
int fp_r;
        
boolean retVal=true;
        
        
if(fp_p<fp_0){
            fp_r
=MathFP.div(fp_q,fp_p);
            
if(fp_r>fp_u[1])
                retVal
=false;
            
else
                
if(fp_r>fp_u[0])
                    fp_u[
0]=fp_r;
        }
 else
            
if(fp_p>fp_0){
            fp_r
=MathFP.div(fp_q,fp_p);
            
if(fp_r<fp_u[0])
                retVal
=false;
            
else if(fp_r<fp_u[1])
                fp_u[
1]=fp_r;
            }
 else
                
if(fp_q<fp_0)
                    retVal
=false;
        
return retVal;
    }

    
    
/**
     *the default clip plane is from -1 to 1,at x, y
     
*/

    
public static void clipLine2DTest(int fp_x1, int fp_y1, int fp_x2, int fp_y2  ){
        
int [] fp_u=new int[2];
        fp_u[
0]=fp_0;
        fp_u[
1]=MathFP.toFP(1);
        
int fp_dx=fp_x2-fp_x1;
        
int fp_dy;
        
        
int fp_winMin=MathFP.toFP(-1);
        
int fp_winMax=MathFP.toFP(1);
        
        
if(clipTest(-fp_dx, fp_x1-fp_winMin, fp_u))
            
if(clipTest(fp_dx, fp_winMax-fp_x1, fp_u)){
            fp_dy
=fp_y2-fp_y1;
            
if(clipTest(-fp_dy, fp_y1-fp_winMin, fp_u))
                
if(clipTest(fp_dy, fp_winMax-fp_y1, fp_u)){
                
if(fp_u[1< fp_winMax){
                    fp_x2 
= fp_x1 + MathFP.mul(fp_u[1] , fp_dx);
                    fp_y2 
= fp_y1 + MathFP.mul(fp_u[1] , fp_dy);
                }

                
                
if(fp_u[0> fp_winMin){
                    fp_x1 
+= MathFP.mul(fp_u[0] , fp_dx);
                    fp_y1 
+= MathFP.mul(fp_u[0] , fp_dy);
                }

                System.out.println(
"Clipped results:");
                System.out.print(MathFP.toString(fp_x1)
+"");
                System.out.print(MathFP.toString(fp_y1)
+"");
                System.out.print(MathFP.toString(fp_x2)
+"");
                System.out.println(MathFP.toString(fp_y2)
+"");
                }

            }

        
    }

    
    
    
/**
     *the default clip plane is from -1 to 1, at x, y z
     
*/

    
public static void clipLine3DTest(int fp_x1, int fp_y1, int fp_z1, int fp_x2, int fp_y2 , int fp_z2){
        
int [] fp_u=new int[2];
        fp_u[
0]=fp_0;
        fp_u[
1]=MathFP.toFP(1);
        
int fp_dx=fp_x2-fp_x1;
        
int fp_dy;
        
int fp_dz;
        
        
int fp_winMin=MathFP.toFP(-1);
        
int fp_winMax=MathFP.toFP(1);
        
        
if(clipTest(-fp_dx, fp_x1-fp_winMin, fp_u))
            
if(clipTest(fp_dx, fp_winMax-fp_x1, fp_u)){
            fp_dy
=fp_y2-fp_y1;
            
if(clipTest(-fp_dy, fp_y1-fp_winMin, fp_u))
                
if(clipTest(fp_dy, fp_winMax-fp_y1, fp_u)){
                fp_dz
=fp_z2-fp_z1;
                
if(clipTest(-fp_dz, fp_z1-fp_winMin, fp_u))
                    
if(clipTest(fp_dz, fp_winMax-fp_z1, fp_u)){
                    
if(fp_u[1< fp_winMax){
                        fp_x2 
= fp_x1 + MathFP.mul(fp_u[1] , fp_dx);
                        fp_y2 
= fp_y1 + MathFP.mul(fp_u[1] , fp_dy);
                        fp_z2 
= fp_z1 + MathFP.mul(fp_u[1] , fp_dz);
                    }

                    
                    
if(fp_u[0> fp_winMin){
                        fp_x1 
+= MathFP.mul(fp_u[0] , fp_dx);
                        fp_y1 
+= MathFP.mul(fp_u[0] , fp_dy);
                        fp_z1 
+= MathFP.mul(fp_u[0] , fp_dz);
                    }

                    System.out.println(
"Clipped results:");
                    System.out.print(MathFP.toString(fp_x1)
+"");
                    System.out.print(MathFP.toString(fp_y1)
+"");
                    System.out.print(MathFP.toString(fp_z1)
+"");
                    System.out.print(MathFP.toString(fp_x2)
+"");
                    System.out.print(MathFP.toString(fp_y2)
+"");
                    System.out.println(MathFP.toString(fp_z2)
+"");
                    }

                }

            }

        
    }


call these methods

        int x1 = MathFP.toFP(-2);
        int y1 = MathFP.toFP(-2);
        int z1 = MathFP.toFP(-2);
        int x2 = MathFP.toFP(2);
        int y2 = MathFP.toFP(2);
        int z2 = MathFP.toFP(2);
        
        Graphics3D.clipLine2DTest(x1,y1,x2,y2);
        Graphics3D.clipLine3DTest(x1,y1,z1,x2,y2,z2);


result:

Clipped results:
-1.0000, -1.0000, 1.0000, 1.0000, 
Clipped results:
-1.0000, -1.0000, -1.0000, 1.0000, 1.0000, 1.0000,

Cohen-Sutherland 编码裁剪算法是一种高效的二维直线段裁剪算法,用于判断一条线段是否与一个矩形窗口相交,并保留其在窗口内的部分。该算法通过为每个端点分配一个 4 位区域编码(outcode),快速排除完全在窗口外的线段或直接接受完全在窗口内的线段,对部分相交的线段则进行逐步求交和裁剪。 下面我将使用 **Python + Matplotlib** 实现 Cohen-Sutherland 直线裁剪算法,可视化展示三种情况: 1. 完全在矩形内 2. 部分在矩形外 3. 完全在矩形外 --- ### ✅ Cohen-Sutherland 算法实现(Python) ```python import matplotlib.pyplot as plt # 裁剪窗口边界 X_MIN, X_MAX = 1, 8 Y_MIN, Y_MAX = 1, 6 # 4位编码定义:上(8), 下(4), 右(2), 左(1) def compute_outcode(x, y): code = 0 if y > Y_MAX: code |= 8 # 上方 elif y < Y_MIN: code |= 4 # 下方 if x > X_MAX: code |= 2 # 右方 elif x < X_MIN: code |= 1 # 左方 return code # Cohen-Sutherland 裁剪函数 def cohen_sutherland_clip(x1, y1, x2, y2): outcode1 = compute_outcode(x1, y1) outcode2 = compute_outcode(x2, y2) accept = False while True: # 情况1:两个端点都在窗口内 → 接受 if not (outcode1 | outcode2): accept = True break # 情况2:两个端点在同一外部区域 → 拒绝 elif outcode1 & outcode2: break # 情况3:至少有一个点在外部,需要求交点裁剪 else: # 选择一个在外部的点 if outcode1 != 0: oc = outcode1 x, y = x1, y1 else: oc = outcode2 x, y = x2, y2 # 计算交点 if oc & 8: # 上边 y=Y_MAX x_inter = x1 + (x2 - x1) * (Y_MAX - y1) / (y2 - y1) y_inter = Y_MAX elif oc & 4: # 下边 y=Y_MIN x_inter = x1 + (x2 - x1) * (Y_MIN - y1) / (y2 - y1) y_inter = Y_MIN elif oc & 2: # 右边 x=X_MAX y_inter = y1 + (y2 - y1) * (X_MAX - x1) / (x2 - x1) x_inter = X_MAX elif oc & 1: # 左边 x=X_MIN y_inter = y1 + (y2 - y1) * (X_MIN - x1) / (x2 - x1) x_inter = X_MIN # 用交点替换当前外部点 if oc == outcode1: x1, y1 = x_inter, y_inter outcode1 = compute_outcode(x1, y1) else: x2, y2 = x_inter, y_inter outcode2 = compute_outcode(x2, y2) if accept: return (x1, y1), (x2, y2) else: return None # 不在窗口内 # 绘图函数 def plot_clipping(): fig, ax = plt.subplots(1, 1, figsize=(10, 8)) # 绘制裁剪窗口 window = plt.Rectangle((X_MIN, Y_MIN), X_MAX - X_MIN, Y_MAX - Y_MIN, linewidth=2, edgecolor='blue', facecolor='none') ax.add_patch(window) # 测试三条线段(覆盖三种情况) lines = [ ((2, 2), (7, 5)), # 完全在内部 ((0, 3), (5, 7)), # 部分在外部 ((10, 7), (12, 9)), # 完全在外部 ] colors = ['green', 'orange', 'red'] for i, ((x1, y1), (x2, y2)) in enumerate(lines): result = cohen_sutherland_clip(x1, y1, x2, y2) # 原始线段(灰色虚线) ax.plot([x1, x2], [y1, y2], 'gray', linestyle='--', linewidth=1) if result: (cx1, cy1), (cx2, cy2) = result ax.plot([cx1, cx2], [cy1, cy2], color=colors[i], linewidth=2, label=f'Clipped Line {i+1}') # 标注裁剪后点 ax.scatter([cx1, cx2], [cy1, cy2], color=colors[i], s=30) else: ax.text((x1 + x2)/2, (y1 + y2)/2, 'Rejected', color='red', fontsize=10, ha='center') # 设置坐标轴 ax.set_xlim(0, 13) ax.set_ylim(0, 10) ax.grid(True) ax.set_title("Cohen-Sutherland Line Clipping Algorithm") ax.set_xlabel("X") ax.set_ylabel("Y") ax.legend() plt.show() # 运行示例 plot_clipping() ``` --- ### 🔍 代码解释: - `compute_outcode(x, y)`:根据点 `(x,y)` 相对于窗口的位置生成 4 位编码。 - `cohen_sutherland_clip()`: - 使用按位或判断是否全部在窗口内(`code1|code2 == 0`)→ 接受; - 使用按位与判断是否同侧在外(`code1&code2 != 0`)→ 拒绝; - 否则,找交点,迭代裁剪直到完全进入或被拒绝。 - `plot_clipping()`:绘制裁剪窗口、原始线段和裁剪结果,区分三种情况。 --- ### 🧪 输出效果说明: 1. **绿色线段**:完全在窗口内 → 裁剪后整条保留。 2. **橙色线段**:穿过窗口 → 被裁剪成一段在窗口内的线段。 3. **红色线段**:完全在窗口外 → 显示“Rejected”。 --- ### ✅ 扩展:梁友栋-BarskyLiang-Barsky)算法简介(可选实现提示) Liang-Barsky 算法基于参数化形式 $ P(t) = P_1 + t(P_2 - P_1), t \in [0,1] $,利用不等式组求解有效区间 $[t_{min}, t_{max}]$,效率更高,适合硬件实现。 关键思想是构造四个不等式对应四条边,计算 $t$ 的上下界。 若你需要 Liang-Barsky 的 Python 实现,请继续提问! ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值