Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
@file:OptIn(ExperimentalSkikoApi::class)

package org.jetbrains.skia

import org.jetbrains.skia.gpu.ganesh.makeFromImage
import org.jetbrains.skia.gpu.ganesh.makeRenderTarget
import org.jetbrains.skia.impl.use
import org.jetbrains.skiko.Arch
import org.jetbrains.skiko.ExperimentalSkikoApi
import org.jetbrains.skiko.KotlinBackend
import org.jetbrains.skiko.OS
import org.jetbrains.skiko.hostArch
import org.jetbrains.skiko.hostOs
import org.jetbrains.skiko.kotlinBackend
import org.jetbrains.skiko.tests.TestGlContext
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotEquals

class GaneshMeshTest {
@Test
fun rasterizesMeshOnAGpuSurface() {
if (!TestGlContext.isAvailable()) return

if (hostOs == OS.Linux && kotlinBackend == KotlinBackend.Native && hostArch == Arch.Arm64) {
// TODO: fix test on Linux arm64 using EGL
return
}

makeSpecification().use { specification ->
MeshVertexBuffer.make(QUAD_VERTICES).use { vertexBuffer ->
Mesh.make(
specification = specification,
mode = Mesh.Mode.TRIANGLES,
vertexBuffer = vertexBuffer,
vertexCount = 6,
bounds = Rect.makeLTRB(0f, 0f, SURFACE_SIZE.toFloat(), SURFACE_SIZE.toFloat()),
uniforms = null
).use { mesh ->
val pixels = TestGlContext.run {
DirectContext.makeGL().useContext { context ->
Surface.makeRenderTarget(
context,
budgeted = false,
ImageInfo.makeN32Premul(SURFACE_SIZE, SURFACE_SIZE)
).use { surface ->
surface.canvas.clear(Color.WHITE)
Paint().use { paint ->
surface.canvas.drawMesh(mesh, BlendMode.SRC, paint)
}
surface.makeImageSnapshot().use { Bitmap.makeFromImage(it, context) }
}
}
}
pixels.use {
val inside = it.getColor(SURFACE_SIZE / 2, SURFACE_SIZE / 2)
assertNotEquals(Color.WHITE, inside, "The mesh left the surface unchanged")
assertEquals(0xFF, Color.getA(inside), "Expected an opaque mesh pixel")
assertEquals(Color.WHITE, it.getColor(0, 0), "Drew outside the mesh bounds")
}
}
}
}
}
}

private const val SURFACE_SIZE = 16

private const val QUAD_MIN = 2f
private const val QUAD_MAX = 14f

/** Two triangles covering a quad inset from the edges of the surface. */
private val QUAD_VERTICES = floatArrayOf(
QUAD_MIN, QUAD_MIN, QUAD_MAX, QUAD_MIN, QUAD_MIN, QUAD_MAX,
QUAD_MAX, QUAD_MIN, QUAD_MAX, QUAD_MAX, QUAD_MIN, QUAD_MAX,
)

private fun makeSpecification(): MeshSpecification = MeshSpecification.make(
attributes = arrayOf(MeshSpecification.Attribute(MeshSpecification.Attribute.Type.FLOAT2, 0, "pos")),
vertexStride = 8,
varyings = emptyArray(),
vertexShader = """
Varyings main(const Attributes a) {
Varyings v;
v.position = a.pos;
return v;
}
""",
fragmentShader = """
float2 main(const Varyings v, out float4 color) {
color = float4(1, 0, 0, 1);
return v.position;
}
"""
)
117 changes: 117 additions & 0 deletions skiko/src/commonMain/cpp/common/include/MeshInterop.hh
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
#pragma once

#include <cstdint>
#include <cstring>
#include <string_view>
#include <utility>
#include <vector>

#include "SkBlender.h"
#include "SkColorFilter.h"
#include "SkData.h"
#include "SkMesh.h"
#include "SkRuntimeEffect.h"
#include "SkRefCnt.h"
#include "SkShader.h"

// Accumulates values for the uniforms declared by an SkMeshSpecification into the flat buffer that
// SkMesh::Make expects. The buffer is sized from the specification and zero-filled, so uniforms that
// are never written read as zero.
class MeshUniformBuilder {
public:
// Status codes shared with the Kotlin peer.
enum Status : int32_t {
kOk = 0,
kUnknownUniform = 1,
kSizeMismatch = 2,
kKindMismatch = 3,
};

// The two kinds of value a uniform holds. An int and a float are the same width, so a write
// states which kind it carries and the declared type decides whether it fits.
enum class ValueKind {
kInt,
kFloat,
};

explicit MeshUniformBuilder(sk_sp<SkMeshSpecification> specification)
: fSpecification(std::move(specification))
, fUniforms(fSpecification->uniformSize(), 0) {}

// Overwrites the named uniform with sizeInBytes bytes of kind read from values.
Status write(std::string_view name, ValueKind kind, const void* values, size_t sizeInBytes) {
const SkMeshSpecification::Uniform* uniform = fSpecification->findUniform(name);
if (!uniform) {
return kUnknownUniform;
}
if (uniform->sizeInBytes() != sizeInBytes) {
return kSizeMismatch;
}
if (uniformValueKind(uniform->type) != kind) {
return kKindMismatch;
}
memcpy(fUniforms.data() + uniform->offset, values, sizeInBytes);
return kOk;
}

sk_sp<SkData> build() const {
if (fUniforms.empty()) {
return SkData::MakeEmpty();
}
return SkData::MakeWithCopy(fUniforms.data(), fUniforms.size());
}

private:
static ValueKind uniformValueKind(SkMeshSpecification::Uniform::Type type) {
switch (type) {
case SkMeshSpecification::Uniform::Type::kInt:
case SkMeshSpecification::Uniform::Type::kInt2:
case SkMeshSpecification::Uniform::Type::kInt3:
case SkMeshSpecification::Uniform::Type::kInt4:
return ValueKind::kInt;
case SkMeshSpecification::Uniform::Type::kFloat:
case SkMeshSpecification::Uniform::Type::kFloat2:
case SkMeshSpecification::Uniform::Type::kFloat3:
case SkMeshSpecification::Uniform::Type::kFloat4:
case SkMeshSpecification::Uniform::Type::kFloat2x2:
case SkMeshSpecification::Uniform::Type::kFloat3x3:
case SkMeshSpecification::Uniform::Type::kFloat4x4:
return ValueKind::kFloat;
}
return ValueKind::kFloat;
}

sk_sp<SkMeshSpecification> fSpecification;
std::vector<uint8_t> fUniforms;
};

// The number of ints the Kotlin peer reads per uniform out of the reflection buffer: offset, type,
// count, size and flags, in that order.
inline constexpr int32_t kMeshUniformFields = 5;

// SkMesh::Make reads the uniform data while validating the mesh, so an absent uniform buffer becomes
// empty data rather than null. A specification that declares uniforms then reports the shortfall as
// an error instead of dereferencing null.
inline sk_sp<const SkData> meshUniforms(const SkData* uniforms) {
return uniforms ? sk_ref_sp(uniforms) : SkData::MakeEmpty();
}

// A pointer alone cannot say which SkFlattenable subclass a child must be upcast from, so the Kotlin
// peer sends an SkRuntimeEffect::ChildType alongside each one. This value stands for a child left
// unbound, which no ChildType names.
inline constexpr int32_t kUnboundMeshChild = -1;

inline SkMesh::ChildPtr meshChild(void* child, int32_t type) {
if (type == kUnboundMeshChild) {
return SkMesh::ChildPtr();
}
switch (static_cast<SkRuntimeEffect::ChildType>(type)) {
case SkRuntimeEffect::ChildType::kShader:
return SkMesh::ChildPtr(sk_ref_sp(static_cast<SkShader*>(child)));
case SkRuntimeEffect::ChildType::kColorFilter:
return SkMesh::ChildPtr(sk_ref_sp(static_cast<SkColorFilter*>(child)));
case SkRuntimeEffect::ChildType::kBlender:
return SkMesh::ChildPtr(sk_ref_sp(static_cast<SkBlender*>(child)));
}
return SkMesh::ChildPtr();
}
2 changes: 1 addition & 1 deletion skiko/src/commonMain/kotlin/org/jetbrains/skia/Blender.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import org.jetbrains.skia.impl.interopScope
* Blender represents a custom blend function in the Skia pipeline. A blender combines a source
* color (the result of our paint) and destination color (from the canvas) into a final color.
*/
class Blender internal constructor(ptr: NativePointer) : RefCnt(ptr) {
class Blender internal constructor(ptr: NativePointer) : RefCnt(ptr), RuntimeEffect.Child {
companion object {
init {
staticLoad()
Expand Down
69 changes: 69 additions & 0 deletions skiko/src/commonMain/kotlin/org/jetbrains/skia/Canvas.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package org.jetbrains.skia
import org.jetbrains.skia.ImageFilter.Companion.makeDropShadowOnly
import org.jetbrains.skia.impl.*
import org.jetbrains.skia.impl.Library.Companion.staticLoad
import org.jetbrains.skiko.ExperimentalSkikoApi
import org.jetbrains.skiko.InternalSkikoApi

open class Canvas internal constructor(ptr: NativePointer, managed: Boolean, internal val _owner: Any) :
Expand Down Expand Up @@ -1024,6 +1025,62 @@ open class Canvas internal constructor(ptr: NativePointer, managed: Boolean, int
return this
}

/**
* Draws a mesh using a user-defined specification (see [MeshSpecification]). Requires a GPU
* backend or SkSL to be compiled in.
*
* [blender] is ignored if [mesh]'s specification does not output fragment shader color.
* Otherwise, it combines
* - the [Shader] if [paint] contains [Shader]
* - or the opaque [paint] color if [paint] does not contain [Shader]
*
* as the src of the blend and the mesh's fragment color as the dst.
*
* [MaskFilter], [PathEffect], and antialiasing on [paint] are ignored.
*
* A canvas backed by a raster [Surface] accepts the draw and produces no pixels for it.
*
* @param mesh the mesh vertices and compatible specification.
* @param blender combines vertices colors with [Shader] if present or [paint] opaque color if
* not. Ignored if the custom mesh does not output color.
* @param paint specifies the [Shader], used as mesh texture.
*
* @return this
*/
@ExperimentalSkikoApi
fun drawMesh(mesh: Mesh, blender: Blender, paint: Paint): Canvas {
Stats.onNativeCall()
try {
_nDrawMesh(_ptr, getPtr(mesh), getPtr(blender), getPtr(paint))
} finally {
reachabilityBarrier(this)
reachabilityBarrier(mesh)
reachabilityBarrier(blender)
reachabilityBarrier(paint)
}
return this
}

/**
* Draws [mesh] with a [Blender] built from [blendMode].
*
* @see drawMesh
*
* @return this
*/
@ExperimentalSkikoApi
fun drawMesh(mesh: Mesh, blendMode: BlendMode, paint: Paint): Canvas {
Stats.onNativeCall()
try {
_nDrawMeshBlendMode(_ptr, getPtr(mesh), blendMode.ordinal, getPtr(paint))
} finally {
reachabilityBarrier(this)
reachabilityBarrier(mesh)
reachabilityBarrier(paint)
}
return this
}

/**
*
* Draws Drawable drawable using clip and matrix.
Expand Down Expand Up @@ -1861,6 +1918,18 @@ private external fun _nDrawPatch(
paintPtr: NativePointer
)

@ExternalSymbolName("org_jetbrains_skia_Canvas__1nDrawMesh")
// Needs ForceNativeThreadState: draws a mesh on a canvas that can be GPU-backed, which can call Metal.
// Native call path: SkCanvas::drawMesh -> SkCanvas::onDrawMesh -> SkDevice::drawMesh
@ForceNativeThreadState
private external fun _nDrawMesh(ptr: NativePointer, meshPtr: NativePointer, blenderPtr: NativePointer, paintPtr: NativePointer)

@ExternalSymbolName("org_jetbrains_skia_Canvas__1nDrawMeshBlendMode")
// Needs ForceNativeThreadState: draws a mesh on a canvas that can be GPU-backed, which can call Metal.
// Native call path: SkCanvas::drawMesh -> SkCanvas::onDrawMesh -> SkDevice::drawMesh
@ForceNativeThreadState
private external fun _nDrawMeshBlendMode(ptr: NativePointer, meshPtr: NativePointer, blendMode: Int, paintPtr: NativePointer)


@ExternalSymbolName("org_jetbrains_skia_Canvas__1nDrawDrawable")
// Needs ForceNativeThreadState: calls back into Kotlin to draw the drawable.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import org.jetbrains.skia.impl.*
* All subclasses are required to be reentrant-safe : it must be legal to share
* the same instance between several threads.
*/
class ColorFilter : RefCnt {
class ColorFilter : RefCnt, RuntimeEffect.Child {
companion object {
fun makeComposed(outer: ColorFilter?, inner: ColorFilter?): ColorFilter {
return try {
Expand Down
Loading
Loading