How to build Skia 和 canvaskit


 

docker鏡像作為編譯環境:

編譯canvaskit的docker相關文件放在:skia/infra/canvaskit/docker

[root@base11:/home/chromium/skia/infra/canvaskit/docker]# ls
canvaskit-emsdk  Makefile
[root@base11:/home/chromium/skia/infra/canvaskit/docker]# more Makefile 
EMSDK_VERSION=3.1.3_v1

publish_canvaskit_emsdk:
	docker build -t canvaskit-emsdk ./canvaskit-emsdk/
	docker tag canvaskit-emsdk gcr.io/skia-public/canvaskit-emsdk:${EMSDK_VERSION}
	docker push gcr.io/skia-public/canvaskit-emsdk:${EMSDK_VERSION}

換目錄,執行這里的,不是上面的了:skia/infra/wasm-common/docker

執行:make publish_canvaskit_emsdk

會自動按照 canvaskit-emsdk 目錄下的 Dockerfile 下載編譯環境。

注釋掉 skia/modules/canvaskit/compile.sh 中需要fq部分。

編譯:docker run -v /home/skia:/SRC -v /home/skia/out:/OUT canvaskit-emsdk /SRC/infra/canvaskit/build_canvaskit.sh  debug

 

這個鏈接包含如何編譯運行文檔:https://github.com/google/skia/blob/main/modules/canvaskit/README.md

infra/wasm-common/docker/README.md 有測試docker環境好用否的命令。

emsdk-base

This image has an Emscripten SDK environment that can be used for compiling projects (e.g. Skia's PathKit) to WASM/asm.js.

This image tracks the official emscripten Docker image and installs python 2 (which some of our scripts still use).

make publish_emsdk_base

For testing the image locally, the following flow can be helpful:

docker build -t emsdk-base ./emsdk-base/
# Run bash in it to poke around and make sure things are properly installed
docker run -it emsdk-base /bin/bash
# Compile PathKit with the local image
docker run -v $SKIA_ROOT:/SRC -v $SKIA_ROOT/out/dockerpathkit:/OUT emsdk-base /SRC/infra/pathkit/build_pathkit.sh

本地環境編譯

1,emsdk Download and install

https://emscripten.org/docs/getting_started/downloads.html

自己更新 emsdk,指定版本:

 emsdk install 3.1.3

# Fetch the latest registry of available tools.
./emsdk update

# Download and install the latest SDK tools.
./emsdk install latest

# Set up the compiler configuration to point to the "latest" SDK.
./emsdk activate latest

# Activate PATH and other environment variables in the current terminal
source ./emsdk_env.sh

2,在目錄 skia/modules/canvaskit

執行執行 ./compile.sh

 

搭建運行本地示例

Compile and Run Local Example

https://github.com/google/skia/blob/main/modules/canvaskit/README.md

# The following installs all npm dependencies and only needs to be when setting up
# or if our npm dependencies have changed (rarely).
npm ci

make release  # make debug is much faster and has better error messages
make local-example

This will print a local endpoint for viewing the example. You can experiment with the CanvasKit API by modifying ./npm_build/example.html and refreshing the page. For some more experimental APIs, there's also ./npm_build/extra.html.

For other available build targets, see Makefile and compile.sh. For example, building a stripped-down version of CanvasKit with no text support or any of the "extras", one might run:

./compile.sh no_skottie no_particles no_font

Such a stripped-down version is about half the size of the default release build.


參考:


什么是 CanvasKit ?

版權聲明:本文為CSDN博主「張馳Terry」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/terrychinaz/article/details/113940795

CanvasKit是以WASM為編譯目標的Web平台圖形繪制接口,其目標是將Skia的圖形API導出到Web平台。從代碼提交記錄來看,CanvasKit作為了一個Module放置在整個代碼倉庫中,最早的一次提交記錄在2018年9月左右,是一個比較新的codebase

本文簡單介紹一下Skia是如何編譯為Web平台的,其性能以及未來的可應用場景

編譯原理
整個canvaskit模塊的代碼量非常少:

.gitignore
CHANGELOG.md
Makefile
WasmAliases.h
canvaskit/ 發布代碼,canvaskit介紹文檔
canvaskit_bindings.cpp
compile.sh 編譯腳本
cpu.js
debug.js
externs.js
fonts/ 字體資源文件
gpu.js
helper.js
htmlcanvas/
interface.js
karma.bench.conf.js
karma.conf.js
package.json
particles_bindings.cpp
perf/ 性能數據
postamble.js
preamble.js
ready.js
release.js
serve.py
skottie.js
skottie_bindings.cpp
tests/ 測試代碼

整個模塊我們可以看到其實沒有修改包括任何skia的代碼文件,只是在編譯時指明了skia的源碼依賴,同時寫了一些膠水代碼,從這里可以看出skia遷移至WASM並沒有付出很多額外的改造工作。

編譯
設置好WASM工具鏈EmscriptenSDK的環境變量后運行compile.sh就會在out文件夾中得到canvaskit.js和canvaskit.wasm這兩個編譯產物,這里為了分析選擇編譯一個debug版本:

./compile.sh debug

debug版本會得到一個未混淆的canvaskit.js,方便我們分析其實現

編譯產物淺析
為了快速了解整個模塊的情況,直接觀察canvaskit.js和canvaskit.wasm文件,先來看下canvaskit.jsjs代碼量比較大,這里摘取一段最能展示其運行原理的代碼:

function makeWebGLContext(canvas, attrs) {
// These defaults come from the emscripten _emscripten_webgl_create_context
var contextAttributes = {
alpha: get(attrs, 'alpha', 1),
depth: get(attrs, 'depth', 1),
stencil: get(attrs, 'stencil', 0),
antialias: get(attrs, 'antialias', 1),
premultipliedAlpha: get(attrs, 'premultipliedAlpha', 1),
preserveDrawingBuffer: get(attrs, 'preserveDrawingBuffer', 0),
preferLowPowerToHighPerformance: get(attrs, 'preferLowPowerToHighPerformance', 0),
failIfMajorPerformanceCaveat: get(attrs, 'failIfMajorPerformanceCaveat', 0),
majorVersion: get(attrs, 'majorVersion', 1),
minorVersion: get(attrs, 'minorVersion', 0),
enableExtensionsByDefault: get(attrs, 'enableExtensionsByDefault', 1),
explicitSwapControl: get(attrs, 'explicitSwapControl', 0),
renderViaOffscreenBackBuffer: get(attrs, 'renderViaOffscreenBackBuffer', 0),
};
if (!canvas) {
SkDebug('null canvas passed into makeWebGLContext');
return 0;
}
// This check is from the emscripten version
if (contextAttributes['explicitSwapControl']) {
SkDebug('explicitSwapControl is not supported');
return 0;
}
// GL is an enscripten provided helper
// See <https://github.com/emscripten-core/emscripten/blob/incoming/src/library_webgl.js>
return GL.createContext(canvas, contextAttributes);
}

CanvasKit.GetWebGLContext = function(canvas, attrs) {
return makeWebGLContext(canvas, attrs);
};

var GL= {
// ...
init:function () {
GL.miniTempBuffer = new Float32Array(GL.MINI_TEMP_BUFFER_SIZE);
for (var i = 0; i < GL.MINI_TEMP_BUFFER_SIZE; i++) {
GL.miniTempBufferViews[i] = GL.miniTempBuffer.subarray(0, i+1);
}
},
//...
createContext:function (canvas, webGLContextAttributes) {
var ctx = (canvas.getContext("webgl", webGLContextAttributes)
|| canvas.getContext("experimental-webgl", webGLContextAttributes));
return ctx && GL.registerContext(ctx, webGLContextAttributes);
},registerContext:function (ctx, webGLContextAttributes) {
var handle = _malloc(8); // Make space on the heap to store GL context attributes that need to be accessible as shared between threads.
assert(handle, 'malloc() failed in GL.registerContext!');
var context = {
handle: handle,
attributes: webGLContextAttributes,
version: webGLContextAttributes.majorVersion,
GLctx: ctx
};
// Store the created context object so that we can access the context given a canvas without having to pass the parameters again.
if (ctx.canvas) ctx.canvas.GLctxObject = context;
GL.contexts[handle] = context;
if (typeof webGLContextAttributes.enableExtensionsByDefault === 'undefined' || webGLContextAttributes.enableExtensionsByDefault) {
GL.initExtensions(context);
}
return handle;
},makeContextCurrent:function (contextHandle) {
GL.currentContext = GL.contexts[contextHandle]; // Active Emscripten GL layer context object.
Module.ctx = GLctx = GL.currentContext && GL.currentContext.GLctx; // Active WebGL context object.
return !(contextHandle && !GLctx);
},
// ...
}

代碼中出現了大量的WebGL指令和2d的繪制js代碼,其實這一塊就是EmscriptenSDK對OpenGL的膠水代碼(https://emscripten.org/docs/porting/multimedia_and_graphics/OpenGL-support.html)), 換言之,canvaskit的繪制代碼沒有脫離瀏覽器提供的webgl和context2d的相關接口,畢竟這也是目前在瀏覽器進行繪制操作的唯一途徑

那編譯的wasm文件做了啥呢?簡單看一下對應wasm的一部分代碼, 這也是一個比較龐大的文件,我們只關注一下wasm和js連接的橋梁代碼:

(import "env" "_eglGetCurrentDisplay" (func $_eglGetCurrentDisplay (result i32)))
(import "env" "_eglGetProcAddress" (func $_eglGetProcAddress (param i32) (result i32)))
(import "env" "_eglQueryString" (func $_eglQueryString (param i32 i32) (result i32)))
(import "env" "_emscripten_glActiveTexture" (func $_emscripten_glActiveTexture (param i32)))
(import "env" "_emscripten_glAttachShader" (func $_emscripten_glAttachShader (param i32 i32)))
(import "env" "_emscripten_glBeginQueryEXT" (func $_emscripten_glBeginQueryEXT (param i32 i32)))
(import "env" "_emscripten_glBindAttribLocation" (func $_emscripten_glBindAttribLocation (param i32 i32 i32)))
(import "env" "_emscripten_glBindBuffer" (func $_emscripten_glBindBuffer (param i32 i32)))
(import "env" "_emscripten_glBindFramebuffer" (func $_emscripten_glBindFramebuffer (param i32 i32)))
(import "env" "_emscripten_glBindRenderbuffer" (func $_emscripten_glBindRenderbuffer (param i32 i32)))
(import "env" "_emscripten_glBindTexture" (func $_emscripten_glBindTexture (param i32 i32)))
(import "env" "_emscripten_glClear" (func $_emscripten_glClear (param i32)))
(import "env" "_emscripten_glClearColor" (func $_emscripten_glClearColor (param f64 f64 f64 f64)))
(import "env" "_emscripten_glClearDepthf" (func $_emscripten_glClearDepthf (param f64)))
(import "env" "_emscripten_glCompileShader" (func $_emscripten_glCompileShader (param i32)))
...

這里省略了一部分,但是仍然可以看出,wasm對繪制的支持全部依賴其運行環境中js注入的函數實現

以這里的_emscripten_glBindTexture函數為例,對應到js為:

var asmGlobalArg = {}

var asmLibraryArg = {
"_emscripten_glBindTexture": _emscripten_glBindTexture // .... 上文wasm中的函數注冊,這里略去,只保留_emscripten_glBindTexture
}
Module['asm'] = function(global, env, providedBuffer) {
// memory was already allocated (so js could use the buffer)
env['memory'] = wasmMemory
;
// import table
env['table'] = wasmTable = new WebAssembly.Table({
'initial': 1155075,
'maximum': 1155075,
'element': 'anyfunc'
});
env['__memory_base'] = 1024; // tell the memory segments where to place themselves
env['__table_base'] = 0; // table starts at 0 by default (even in dynamic linking, for the main module)

var exports = createWasm(env); // 加載WASM對象, env即WASM對象加載時所需要的上下文,包括內存大小,函數表,和堆棧起始地址
assert(exports, 'binaryen setup failed (no wasm support?)');
return exports;
};
// EMSCRIPTEN_START_ASM
var asm =Module["asm"]// EMSCRIPTEN_END_ASM
(asmGlobalArg, asmLibraryArg, buffer);
function _emscripten_glBindTexture(target, texture) {
GL.validateGLObjectID(GL.textures, texture, 'glBindTexture', 'texture');
GLctx.bindTexture(target, GL.textures[texture]);
}

GLctx通過代碼我們也能找到對應:

createContext:function (canvas, webGLContextAttributes) {
var ctx = (canvas.getContext("webgl", webGLContextAttributes)
|| canvas.getContext("experimental-webgl", webGLContextAttributes));
return ctx && GL.registerContext(ctx, webGLContextAttributes);
},registerContext:function (ctx, webGLContextAttributes) {
var handle = _malloc(8); // Make space on the heap to store GL context attributes that need to be accessible as shared between threads.
assert(handle, 'malloc() failed in GL.registerContext!');
var context = {
handle: handle,
attributes: webGLContextAttributes,
version: webGLContextAttributes.majorVersion,
GLctx: ctx
};
// Store the created context object so that we can access the context given a canvas without having to pass the parameters again.
if (ctx.canvas) ctx.canvas.GLctxObject = context;
GL.contexts[handle] = context;
if (typeof webGLContextAttributes.enableExtensionsByDefault === 'undefined' || webGLContextAttributes.enableExtensionsByDefault) {
GL.initExtensions(context);
}
return handle;
},makeContextCurrent:function (contextHandle) {

GL.currentContext = GL.contexts[contextHandle]; // Active Emscripten GL layer context object.
Module.ctx = GLctx = GL.currentContext && GL.currentContext.GLctx; // Active WebGL context object. // GLCtx變量
return !(contextHandle && !GLctx);
}

所以這里的bindTexture實際上就是WebGL的bindTexture指令(https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindTexture#Syntax)

分析到這里,我們可以得到一個基本結論: canvaskit中繪制的實現全部在canvaskit.js中調用瀏覽器繪制API來實現,而計算相關的內容全部放在了wasm中實現

編譯腳本解析
通過對編譯產物的分析,我們可以發現canvaskit絕大部分的繪制都是借助了Web API中的2d或webgl繪制API來完成的。這里需要分析的是canvaskit如何搭建了skia原生繪制代碼和瀏覽器繪制API的橋梁。

看到compile.sh發現最后一句話涉及到很多canvaskit目錄下的文件,因此直接結合編譯日志的相關內容分析。

其他的日志都是常規的skia編譯命令,只不過執行程序換成了em++而已,em++就是EmscriptenSDK中的編譯器命令,可以類比為g++,這些命令會把skia編譯為幾個靜態庫

我們略過之前的skia編譯命令來到最后一段,這是真正生成WASM產物的地方,其中有大量的邏輯是涉及到canvaskit中的膠水代碼的。略去鏈接, 編譯器優化設置, Skia靜態庫路徑的指定, Skia宏定義和頭文件路徑指定,我們將會得到:

script

/Users/JianGuo/VSCodeProject/emsdk/emscripten/1.38.28/em++ \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/debug.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/cpu.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/gpu.js \\
--bind \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/preamble.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/helper.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/interface.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/skottie.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/htmlcanvas/preamble.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/htmlcanvas/util.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/htmlcanvas/color.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/htmlcanvas/font.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/htmlcanvas/canvas2dcontext.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/htmlcanvas/htmlcanvas.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/htmlcanvas/imagedata.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/htmlcanvas/lineargradient.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/htmlcanvas/path2d.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/htmlcanvas/pattern.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/htmlcanvas/radialgradient.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/htmlcanvas/postamble.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/postamble.js \\
--post-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/ready.js \\
/Users/JianGuo/Desktop/skia/skia/modules/canvaskit/fonts/NotoMono-Regular.ttf.cpp \\
/Users/JianGuo/Desktop/skia/skia/modules/canvaskit/canvaskit_bindings.cpp \\
/Users/JianGuo/Desktop/skia/skia/modules/canvaskit/particles_bindings.cpp \\
/Users/JianGuo/Desktop/skia/skia/modules/canvaskit/skottie_bindings.cpp \\
modules/skottie/utils/SkottieUtils.cpp \\
-s ALLOW_MEMORY_GROWTH=1 \\ # 允許申請比TOTAL_MEMORY更大的內存
-s EXPORT_NAME=CanvasKitInit \\ # js中Module的名字
-s FORCE_FILESYSTEM=0 \\ # 開啟文件系統支持,用於js中對native的文件系統進行模擬
-s MODULARIZE=1 \\ #啟用Module的方式生成js,開啟后編譯的js產物將擁有一個Module作用域,而非全局作用域
-s NO_EXIT_RUNTIME=1 \\ # 禁止使用exit函數
-s STRICT=1 \\ # 確保編譯器不使用棄用語法
-s TOTAL_MEMORY=128MB \\ # WASM分配的總內存,如果比此內存更大的場景就需要擴展堆大小
-s USE_FREETYPE=1 \\ # 使用emscripten-ports導出的freetype庫
-s USE_LIBPNG=1 \\ # 使用emscripten-ports導出的libpng庫
-s WARN_UNALIGNED=1 \\ # 編譯時警告未對齊(align)
-s USE_WEBGL2=0 \\ # 不使用WebGL2
-s WASM=1 \\ # 編譯為WASM
-o out/canvaskit_wasm_debug/canvaskit.js # 指定編譯路徑

其中,pre-js <file>表示將指定文件的內容插入到生成的js文件前, post-js表示將指定文件的內容插入到生成的js文件后,我們以skia/modules/canvaskit/htmlcanvas/htmlcanvas.js為例,看看這些插入的文件都干了啥:

CanvasKit.MakeCanvas = function(width, height) {
var surf = CanvasKit.MakeSurface(width, height);
if (surf) {
return new HTMLCanvas(surf);
}
return null;
}

function HTMLCanvas(skSurface) {
this._surface = skSurface;
this._context = new CanvasRenderingContext2D(skSurface.getCanvas());
this._toCleanup = [];
this._fontmgr = CanvasKit.SkFontMgr.RefDefault();

// Data is either an ArrayBuffer, a TypedArray, or a Node Buffer
this.decodeImage = function(data) {
// ...
}

this.loadFont = function(buffer, descriptors) {
//...
}

this.makePath2D = function(path) {
//...
}

// A normal <canvas> requires that clients call getContext
this.getContext = function(type) {
//...
}

this.toDataURL = function(codec, quality) {
//...
}

this.dispose = function() {
//...
}
}

其實就是對齊了一下瀏覽器實現,同時對齊了一下Skia內部的接口而已。最后我們還剩下一段沒有分析:

script

/Users/JianGuo/VSCodeProject/emsdk/emscripten/1.38.28/em++ \\
...
--bind \\
...
/Users/JianGuo/Desktop/skia/skia/modules/canvaskit/fonts/NotoMono-Regular.ttf.cpp \\
/Users/JianGuo/Desktop/skia/skia/modules/canvaskit/canvaskit_bindings.cpp \\
/Users/JianGuo/Desktop/skia/skia/modules/canvaskit/particles_bindings.cpp \\
/Users/JianGuo/Desktop/skia/skia/modules/canvaskit/skottie_bindings.cpp \\
modules/skottie/utils/SkottieUtils.cpp \\
...

根據文檔,這段命令要求em++以Embind(https://emscripten.org/docs/porting/connecting_cpp_and_javascript/embind.html#embind)連接C++代碼和JS代碼%E8%BF%9E%E6%8E%A5C++%E4%BB%A3%E7%A0%81%E5%92%8CJS%E4%BB%A3%E7%A0%81), embind簡單來說就是emscriptenSDK提供的將C/C++代碼暴露給JavaScript的便捷能力。這里不做重點介紹,我們直接看canvaskit用到的一個代碼:

particles_bindings.cpp:

// ...
#include <emscripten.h>
#include <emscripten/bind.h>

using namespace emscripten;

EMSCRIPTEN_BINDINGS(Particles) {
class_<SkParticleEffect>("SkParticleEffect")
.smart_ptr<sk_sp<SkParticleEffect>>("sk_sp<SkParticleEffect>")
.function("draw", &SkParticleEffect::draw, allow_raw_pointers())
.function("start", select_overload<void (double, bool)>(&SkParticleEffect::start))
.function("update", select_overload<void (double)>(&SkParticleEffect::update));

function("MakeParticles", optional_override([](std::string json)->sk_sp<SkParticleEffect> {
static bool didInit = false;
if (!didInit) {
REGISTER_REFLECTED(SkReflected);
SkParticleAffector::RegisterAffectorTypes();
SkParticleDrawable::RegisterDrawableTypes();
didInit = true;
}
SkRandom r;
sk_sp<SkParticleEffectParams> params(new SkParticleEffectParams());
skjson::DOM dom(json.c_str(), json.length());
SkFromJsonVisitor fromJson(dom.root());
params->visitFields(&fromJson);
return sk_sp<SkParticleEffect>(new SkParticleEffect(std::move(params), r));
}));
constant("particles", true);

}

上面代碼經過em++編譯后會直接將其功能內嵌進wasm文件中。至此,整個編譯流程就分析完了

小結
這里用一張圖來總結一下整個canvaskit的編譯流程, 圖中省去了編譯器優化和js優化的流程:

 

 

可應用場景
根據官方文檔(https://skia.org/user/modules/canvaskit)), canvaskit基於skia的API設計向web平台提供了更加方便的圖形接口,可以說起到了類似GLWrapper的作用。

得益於Skia本身的其他擴展功能,canvaskit相比於瀏覽器原生繪制能力,支持了許多更加上層的業務級別功能,例如skia的動畫模塊skottie(https://skia.org/user/modules/skottie)

Skia中的skottie本身就支持Lottie動畫解析和播放,由於Skia良好的跨平台能力,Android和iOS平台現在均可以使用Skia框架來播放Lottie動畫,canvaskit則運用WebAssembly的技術來將跨平台的范圍擴展到web上,使得web平台可以通過canvaskit的skottie相關接口直接播放lottie動畫

對於Web應用而言,canvaskit提供了開發者更加友好的圖形接口,並提供了常見的圖形概念(例如Bitmap,Path等),減少了上層應用開發者對於繪制接口的理解負擔,開發者只需要理解Skia的圖形概念即可開發圖形界面,有了skia他們也不需要理解復雜的webgl指令。

小結
得益於WASM的理念和EmscriptenSDK的能力,越來越多的native庫可以直接導出web上供開發者使用。CanvasKit可以說是C++ Library向Web平台遷移的又一最佳實踐。EmscriptenSDK已經做到將Skia這種規模的C++項目以WASM的方式遷移至Web平台,並保證其代碼功能的一致性。整個遷移的過程的代價也就是編譯工具鏈的替換和一部分膠水代碼。
————————————————
版權聲明:本文為CSDN博主「張馳Terry」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/terrychinaz/article/details/113940795

 

1

Install depot_tools and Git

Follow the instructions on Installing Chromium’s depot_tools to download depot_tools (which includes gclient, git-cl, and Ninja). Below is a summary of the necessary steps.

git clone 'https://chromium.googlesource.com/chromium/tools/depot_tools.git'
export PATH="${PWD}/depot_tools:${PATH}"

depot_tools will also install Git on your system, if it wasn’t installed already.

Clone the Skia repository

Skia can either be cloned using git or the fetch tool that is installed with depot_tools.

git clone https://skia.googlesource.com/skia.git
# or
# fetch skia
cd skia
python2 tools/git-sync-deps

How to build Skia

Make sure you have first followed the instructions to download Skia.

Skia uses GN to configure its builds.

is_official_build and Third-party Dependencies

Most users of Skia should set is_official_build=true, and most developers should leave it to its false default.

This mode configures Skia in a way that’s suitable to ship: an optimized build with no debug symbols, dynamically linked against its third-party dependencies using the ordinary library search path.

In contrast, the developer-oriented default is an unoptimized build with full debug symbols and all third-party dependencies built from source and embedded into libskia. This is how we do all our manual and automated testing.

Skia offers several features that make use of third-party libraries, like libpng, libwebp, or libjpeg-turbo to decode images, or ICU and sftnly to subset fonts. All these third-party dependencies are optional and can be controlled by a GN argument that looks something like skia_use_foo for appropriate foo.

If skia_use_foo is enabled, enabling skia_use_system_foo will build and link Skia against the headers and libraries found on the system paths. is_official_build=true enables all skia_use_system_foo by default. You can use extra_cflags and extra_ldflags to add include or library paths if needed.

Supported and Preferred Compilers

While Skia should compile with GCC, MSVC, and other compilers, a number of routines in Skia’s software backend have been written to run fastest when compiled with Clang. If you depend on software rasterization, image decoding, or color space conversion and compile Skia with a compiler other than Clang, you will see dramatically worse performance. This choice was only a matter of prioritization; there is nothing fundamentally wrong with non-Clang compilers. So if this is a serious issue for you, please let us know on the mailing list.

Skia makes use of C++17 language features (compiles with -std=c++17 flag) and thus requires a C++17 compatible compiler. Clang 5 and later implement all of the features of the c++17 standard. Older compilers that lack C++17 support may produce non-obvious compilation errors. You can configure your build to use specific executables for cc and cxx invocations using e.g. --args='cc="clang-6.0" cxx="clang++6.0"' GN build arguments, as illustrated in Quickstart. This can be useful for building Skia without needing to modify your machine’s default compiler toolchain.

Quickstart

Run gn gen to generate your build files. As arguments to gn gen, pass a name for your build directory, and optionally --args= to configure the build type.

To build Skia as a static library in a build directory named out/Static:

bin/gn gen out/Static --args='is_official_build=true'

To build Skia as a shared library (DLL) in a build directory named out/Shared:

bin/gn gen out/Shared --args='is_official_build=true is_component_build=true'

If you find that you don’t have bin/gn, make sure you’ve run:

python2 tools/git-sync-deps

For a list of available build arguments, take a look at gn/skia.gni, or run:

bin/gn args out/Debug --list

GN allows multiple build folders to coexist; each build can be configured separately as desired. For example:

bin/gn gen out/Debug
bin/gn gen out/Release  --args='is_debug=false'
bin/gn gen out/Clang    --args='cc="clang" cxx="clang++"'
bin/gn gen out/Cached   --args='cc_wrapper="ccache"'
bin/gn gen out/RTTI     --args='extra_cflags_cc=["-frtti"]'

Once you have generated your build files, run Ninja to compile and link Skia:

ninja -C out/Static

If some header files are missing, install the corresponding dependencies:

tools/install_dependencies.sh

To pull new changes and rebuild:

git pull
python tools/git-sync-deps
ninja -C out/Static

Android

To build Skia for Android you need an Android NDK.

If you do not have an NDK and have access to CIPD, you can use one of these commands to fetch the NDK our bots use:

python2 infra/bots/assets/android_ndk_linux/download.py -t /tmp/ndk
python2 infra/bots/assets/android_ndk_darwin/download.py -t /tmp/ndk
python2 infra/bots/assets/android_ndk_windows/download.py -t C:/ndk

When generating your GN build files, pass the path to your ndk and your desired target_cpu:

bin/gn gen out/arm   --args='ndk="/tmp/ndk" target_cpu="arm"'
bin/gn gen out/arm64 --args='ndk="/tmp/ndk" target_cpu="arm64"'
bin/gn gen out/x64   --args='ndk="/tmp/ndk" target_cpu="x64"'
bin/gn gen out/x86   --args='ndk="/tmp/ndk" target_cpu="x86"'

Other arguments like is_debug and is_component_build continue to work. Tweaking ndk_api gives you access to newer Android features like Vulkan.

To test on an Android device, push the binary and resources over, and run it as normal. You may find bin/droid convenient.

ninja -C out/arm64
adb push out/arm64/dm /data/local/tmp
adb push resources /data/local/tmp
adb shell "cd /data/local/tmp; ./dm --src gm --config gl"

ChromeOS

To cross-compile Skia for arm ChromeOS devices the following is needed:

  • Clang 4 or newer
  • An armhf sysroot
  • The (E)GL lib files on the arm chromebook to link against.

To compile Skia for an x86 ChromeOS device, one only needs Clang and the lib files.

If you have access to CIPD, you can fetch all of these as follows:

python2 infra/bots/assets/clang_linux/download.py  -t /opt/clang
python2 infra/bots/assets/armhf_sysroot/download.py -t /opt/armhf_sysroot
python2 infra/bots/assets/chromebook_arm_gles/download.py -t /opt/chromebook_arm_gles
python2 infra/bots/assets/chromebook_x86_64_gles/download.py -t /opt/chromebook_x86_64_gles

If you don’t have authorization to use those assets, then see the README.md files for armhf_sysrootchromebook_arm_gles, and chromebook_x86_64_gles for instructions on creating those assets.

Once those files are in place, generate the GN args that resemble the following:

#ARM
cc= "/opt/clang/bin/clang"
cxx = "/opt/clang/bin/clang++"

extra_asmflags = [
    "--target=armv7a-linux-gnueabihf",
    "--sysroot=/opt/armhf_sysroot/",
    "-march=armv7-a",
    "-mfpu=neon",
    "-mthumb",
]
extra_cflags=[
    "--target=armv7a-linux-gnueabihf",
    "--sysroot=/opt/armhf_sysroot",
    "-I/opt/chromebook_arm_gles/include",
    "-I/opt/armhf_sysroot/include/",
    "-I/opt/armhf_sysroot/include/c++/4.8.4/",
    "-I/opt/armhf_sysroot/include/c++/4.8.4/arm-linux-gnueabihf/",
    "-DMESA_EGL_NO_X11_HEADERS",
    "-funwind-tables",
]
extra_ldflags=[
    "--sysroot=/opt/armhf_sysroot",
    "-B/opt/armhf_sysroot/bin",
    "-B/opt/armhf_sysroot/gcc-cross",
    "-L/opt/armhf_sysroot/gcc-cross",
    "-L/opt/armhf_sysroot/lib",
    "-L/opt/chromebook_arm_gles/lib",
    "--target=armv7a-linux-gnueabihf",
]
target_cpu="arm"
skia_use_fontconfig = false
skia_use_system_freetype2 = false
skia_use_egl = true


# x86_64
cc= "/opt/clang/bin/clang"
cxx = "/opt/clang/bin/clang++"
extra_cflags=[
    "-I/opt/clang/include/c++/v1/",
    "-I/opt/chromebook_x86_64_gles/include",
    "-DMESA_EGL_NO_X11_HEADERS",
    "-DEGL_NO_IMAGE_EXTERNAL",
]
extra_ldflags=[
    "-stdlib=libc++",
    "-fuse-ld=lld",
    "-L/opt/chromebook_x86_64_gles/lib",
]
target_cpu="x64"
skia_use_fontconfig = false
skia_use_system_freetype2 = false
skia_use_egl = true

Compile dm (or another executable of your choice) with ninja, as per usual.

Push the binary to a chromebook via ssh and run dm as normal using the gles GPU config.

Most chromebooks by default have their home directory partition marked as noexec. To avoid “permission denied” errors, remember to run something like:

sudo mount -i -o remount,exec /home/chronos

Mac

Mac users may want to pass --ide=xcode to bin/gn gen to generate an Xcode project.

iOS

Run GN to generate your build files. Set target_os="ios" to build for iOS. This defaults to target_cpu="arm64". Choosing x64 targets the iOS simulator.

bin/gn gen out/ios64  --args='target_os="ios"'
bin/gn gen out/ios32  --args='target_os="ios" target_cpu="arm"'
bin/gn gen out/iossim --args='target_os="ios" target_cpu="x64"'

This will also package (and for devices, sign) iOS test binaries. This defaults to a Google signing identity and provisioning profile. To use a different one set the GN args skia_ios_identity to match your code signing identity and skia_ios_profile to the name of your provisioning profile, e.g.

skia_ios_identity=".*Jane Doe.*"
skia_ios_profile="iPad Profile"`

A list of identities can be found by typing security find-identity on the command line. The name of the provisioning profile should be available on the Apple Developer site. Alternatively, skia_ios_profile can be the absolute path to the mobileprovision file.

If you find yourself missing a Google signing identity or provisioning profile, you’ll want to have a read through go/appledev.

For signed packages ios-deploy makes installing and running them on a device easy:

ios-deploy -b out/Debug/dm.app -d --args "--match foo"

Alternatively you can generate an Xcode project by passing --ide=xcode to bin/gn gen. If you are using Xcode version 10 or later, you may need to go to Project Settings... and verify that Build System: is set to Legacy Build System.

Deploying to a device with an OS older than the current SDK can be done by setting the ios_min_target arg:

ios_min_target = "<major>.<minor>"

where <major>.<minor> is the iOS version on the device, e.g., 12.0 or 11.4.

Windows

Skia can build on Windows with Visual Studio 2017 or 2019. If GN is unable to locate either of those, it will print an error message. In that case, you can pass your VC path to GN via win_vc.

Skia can be compiled with the free Build Tools for Visual Studio 2017 or 2019.

The bots use a packaged 2019 toolchain, which Googlers can download like this:

python2 infra/bots/assets/win_toolchain/download.py -t C:/toolchain

You can then pass the VC and SDK paths to GN by setting your GN args:

win_vc = "C:\toolchain\VC"
win_sdk = "C:\toolchain\win_sdk"

This toolchain is the only way we support 32-bit builds, by also setting target_cpu="x86".

The Skia build assumes that the PATHEXT environment variable contains “.EXE”.

Skia uses generated code that is only optimized when Skia is built with clang. Other compilers get generic unoptimized code.

Setting the cc and cxx gn args is not sufficient to build with clang-cl. These variables are ignored on Windows. Instead set the variable clang_win to your LLVM installation directory. If you installed the prebuilt LLVM downloaded from here in the default location that would be:

clang_win = "C:\Program Files\LLVM"

Follow the standard Windows path specification and not MinGW convention (e.g. C:\Program Files\LLVM not /c/Program Files/LLVM).

Visual Studio Solutions

If you use Visual Studio, you may want to pass --ide=vs to bin/gn gen to generate all.sln. That solution will exist within the GN directory for the specific configuration, and will only build/run that configuration.

If you want a Visual Studio Solution that supports multiple GN configurations, there is a helper script. It requires that all of your GN directories be inside the out directory. First, create all of your GN configurations as usual. Pass --ide=vs when running bin/gn gen for each one. Then:

python2 gn/gn_meta_sln.py

This creates a new dedicated output directory and solution file out/sln/skia.sln. It has one solution configuration for each GN configuration, and supports building and running any of them. It also adjusts syntax highlighting of inactive code blocks based on preprocessor definitions from the selected solution configuration.

Windows ARM64

There is early, experimental support for Windows 10 on ARM. This currently requires (a recent version of) MSVC, and the Visual C++ compilers and libraries for ARM64 individual component in the Visual Studio Installer. For Googlers, the win_toolchain asset includes the ARM64 compiler.

To use that toolchain, set the target_cpu GN argument to "arm64". Note that OpenGL is not supported by Windows 10 on ARM, so Skia’s GL backends are stubbed out, and will not work. ANGLE is supported:

bin/gn gen out/win-arm64 --args='target_cpu="arm64" skia_use_angle=true'

This will produce a build of Skia that can use the software or ANGLE backends, in DM. Viewer only works when launched with --backend angle, because the software backend tries to use OpenGL to display the window contents.

CMake

We have added a GN-to-CMake translator mainly for use with IDEs that like CMake project descriptions. This is not meant for any purpose beyond development.

bin/gn gen out/config --ide=json --json-ide-script=../../gn/gn_to_cmake.py

 

 

Build canvaskit

https://github.com/google/skia/tree/f88eb656c123cd069f85f9ac1f11007777ce633a/modules/canvaskit

To compile CanvasKit, you will first need to install emscripten. This will set the environment EMSDK (among others) which is required for compilation. Which version should you use? /infra/wasm-common/docker/emsdk-base/Dockerfile shows the version we build and test with. We try to keep this up-to-date.

build通過dockers:

https://github.com/google/skia/tree/master/docker/skia-wasm-release 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM