SpriteKit中的默认混合如何工作?

时间:2015-11-09 23:25:29

标签: ios opengl-es sprite-kit fragment-shader alphablending

我第一次开始修补SpriteKit(Xcode 7.1 iOS9),我看到了一些意想不到的结果(包括设备和模拟器)。

我希望能够通过着色器将精灵中的像素设置为完全透明,但由于某些原因,这不符合我的预期。

这里是一个示例ViewController:

class ViewController: UIViewController {
    @IBOutlet var sceneView: SKView!
    private var scene = SKScene()

    override func viewDidLoad() {
        super.viewDidLoad()
        sceneView.showsDrawCount = true
        sceneView.showsNodeCount = true
        sceneView.showsFPS = true
        scene.scaleMode = .ResizeFill
        scene.backgroundColor = UIColor.redColor()
        let node = SKSpriteNode()
        node.size = CGSizeMake(64, 64)
        node.position = CGPointMake(64, 64)
        node.shader = SKShader(fileNamed: "Test")
        scene.addChild(node)
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.view.layoutIfNeeded()
        sceneView.presentScene(scene)
    }
}

这是一个示例着色器:

void main()
{
    if (v_tex_coord.x < 0.5) {
        gl_FragColor = vec4(0.0, 1.0, 0.0, 0.0);
    } else {
        gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);
    }
}

使用SKBlendModeAlpha的默认混合模式,我希望看到精灵的左半部分为完全透明(显示红色背景),右半部分为绿色。但相反,这就是我所看到的:

Sprite on red background

SKBlendModeAlpha的混合公式不应该是: R =(D *(1-A))+(S * A)

在这种情况下应该导致:

    D   A   S   R
R   1   0   0   1
G   0   0   1   0
B   0   0   0   0

    D   A   S   R
R   1   1   0   0
G   0   1   1   1
B   0   1   0   0

(左边是红色,右边是绿色)

我尝试在节点上手动设置混合模式,但没有区别。

这是一个错误,还是我错过了一些明显的东西?

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

当然,我的问题有一个简单的解释。 gl_FragColor中返回的颜色预计会有倍前的alpha值。因此,而不是返回颜色值:

javax.validation.constraints

我应该返回颜色值:

gl_FragColor = vec4(0.0, 1.0, 0.0, 0.0);

我错误地假设零alpha意味着忽略了颜色分量。