907 points · by lainon · 8y ago · 143 comments
I think the thing I found most exciting is at the end: “WebAssembly is getting more flexible types very soon. Experimental support for the current proposal is already landed in Firefox Nightly.” Implication being that WASM will have native access to the DOM.
I think at that point WASM could be used to fully work with the DOM with no negative costs, right?
The DOM builtins should be helped by the Reference Types Proposal for WebAssembly. [1]
`The host bindings proposal` is going to help speed up new and getter/setter calls. [2]
1: `Currently the only built-ins that we support this for are mostly limited to the math built-ins. That’s because WebAssembly currently only has support for integers and floats as value types.
That works well for the math functions because they work with numbers, but it doesn’t work out so well for other things like the DOM built-ins. So currently when you want to call one of those functions, you have to go through JavaScript. That’s what wasm-bindgen does for you.
But WebAssembly is getting more flexible types very soon. Experimental support for the current proposal is already landed in Firefox Nightly behind the pref javascript.options.wasm_gc. Once these types are in place, you will be able to call these other built-ins directly from WebAssembly without having to go through JS.`
-- https://github.com/WebAssembly/reference-types
2: `there are still a couple of built-ins where you will need to go through JavaScript. For example, if those built-ins are called as if they were using new or if they’re using a getter or setter. These remaining built-ins will be addressed with the host-bindings proposal.`
-- https://github.com/WebAssembly/host-bindings
(BTW I could be mistaken, just quoting the article)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
It doesn't read like this is an explicit goal of the project, but are we going to get this by accident? Being able to use the same X code (where X is your favourite statically-compilable language) to generate both a WASM version that runs on the web and a statically-compiled version that links to the Y browser source (where Y can be whichever browser works for you because they all support the same native API) would be awesome.
WebAssembly is one of those technologies where we haven't seen the true extent of its capabilities yet. This is an exciting time to be working in browsers.
JS developers that don't have experience in lower level languages or some CS concepts. In other words, probably a good portion of the expected audience given it's about JS and possible improvements, and is likely to trickle into the news sources to cater to those people.
https://medium.com/@donhopkins/the-shape-of-psiber-space-oct...
The primary target audience is Web developers interested in new technologies. I'd wager most of them don't know what a stack frame is and would appreciate the explanation.
Probably a lot of JavaScript developers who started in web land and are only now starting to be exposed to the underlying architecture.
99% of all the JS developers I've ever met?
[1] On the right: https://2r4s9p1yi1fa2jd7j43zph8r-wpengine.netdna-ssl.com/fil...
Firefox WASM: 1809ms
Chrome WASM: 2855ms
Edge WASM: 12872ms
Firefox JS: 5413ms
Chrome JS: 4779ms
Edge JS: 8512ms
Firefox linux (v62.0.3)1904
From article: "This means that in the latest version of Firefox * Beta *, calls between JS and WebAssembly are faster than non-inlined JS to JS function calls."
Firefox linux 2132
E.g. if userscript replaces the built-in window.fetch() API to modify page behavior will wasm also be intercepted?
> We took the code that C++ was running — the entry stub — and made it directly callable from JIT code. When the engine goes from JavaScript to WebAssembly, the entry stub un-boxes the values and places them in the right place. With this, we got rid of the C++ trampolining.
So they replaced unboxing C++ trampoline with entry stub. But isn't that stub technically written in C++ too?
Specifically, see the GenerateJitEntry bits in https://bug1319203.bmoattachments.org/attachment.cgi?id=8949... -- the masm.whatever() calls are calls into an architecture-dependent assembler that will output the relevant machine instructions.
There is still an out-of-line codepath that does call into a C++-implemented entry stub in some cases when the argument conversions involved are too complicated to do them directly in the JIT-generated code.
I don't know what I want more, DOM calls from WASM, or C++ modules. A web without javascript would be welcome.
Yeah, Wasm => JS calls used to be reasonably fast because we had optimized that before. The work described here made that path much nicer, though (a more unified stack layout for JIT/Wasm frames) and also a bit faster still.
JS => Wasm calls being slow was one of the big performance cliffs in SpiderMonkey and I'm really glad that's fixed now.
A 3 GHz CPU would do 3 ticks per nanoseconds, doing such a bridging call in 23 or 15 CPU ticks is quite good IMHO (I just hope I didn't blunder the math, but function call overhead from WASM to JS isn't much of an issue, it was already fast after the previous round of optimizations).
Why? What is it that wasm or c++ provides you in making a DOM call that modern JS does not?
I have high hopes for Kotlin here. With Kotlin native they are targeting native IOS and native Android. Being able drive browsers from the same code-base via WASM seems like it will be a useful feature. Also, they seem to be really serious about tool support with Kotlin; providing dom/webgl and other bindings, and having decent end to end support with IDEs and other tools.
I imagine, Microsoft might have similar plans for C#. And it wouldn't surprise me if Apple was working on some Swift WASM support either.
Changing the game into "browsers run WASM" and JS is a built-in JIT compiler for it promises to make everyone's lives much easier.
The JavaScript object model is likely to remain fundamental for cross-language within-browser interop, just like C api's are fundamental for foreign function calls in other environments. (Or Java API's in a JVM.)
The ability to use existing non-JS code
The ability to write loops involving non-trivial computations without spamming a hundred million heap objects
etc.
How does being able to call the DOM from webasm give you that? That's what webasm is for in the first place.
And heck, even without that, there are languages that transpile directly to JavaScript.
Typescript, Coffeescript and a host of similar options have essentially the same data model. What makes other languages, like Java, Rust or Python actually useful is their way of handling data. Which is why you can't transcribe these languages to Javascript trivially.
Still, the ecosystem of javascript is a lot better than the languages which compile to WASM as of right now. I guess that will change...
Some devs are treating WASM as an entire runtime and outputing canvas/webGL code. I think that is mostly a mistake, and I'll be very disappointed if that becomes the defacto approach for new web devs.
However, the cool thing about WASM is that it's just the code part. So you can build an app that's still normal CSS/HTML, just like every web-app should be, and then you can replace all of your JS with WASM (with the current exception of a little bit of JS-to-DOM binding code which Mozilla has promised to eventually get rid of).
In the world of Flash/Java you're essentially working in a completely separate platform, it just happens to be launched from a web browser. So shortcuts don't work, accessibility is awful, users can't customize the page, extensions are broken, etc, etc...
With WASM, you don't have to be in that position. You can say, "I'm a web developer, I treat the web like a medium, I write responsive HTML/CSS. I just use C instead of Javascript."
I mean, yes, there are things like Blazor or similar things for Rust or Nim, but these aren't yet compelling to me.
(I don’t think this is where wasm will be used as much but I’m still interested!)
There is something like this for Rust, I think.
But Python for the Browser is not compelling unless we both have a faithful implementation of the language and data model and a productive and beautiful frontend framework. Call it a React for Python or a Django for the frontend.
Similar goals apply for other languages which have an edge on Javascript in some regard.
https://blog.benj.me/2018/07/04/mozilla-2018-faster-calls-an...
(Maybe it’s functionally easy but getting the heuristics right is hard? Curious what the primary obstacles are for Mozilla or others.)
The WASM spec already tries to avoid pretty much every other big problem that would've confounded attempts to cross-language inline. For example, WASM requires structured control flow (IOW, WASM doesn't have `goto`), avoids type punning in favor of a reinterpret primitive, uses function addresses that are orthogonal to memory addresses, and allows non-deterministic floating point bit representations, all to match up closer with the way existing JavaScript JITs already work. But they can't do anything about boxing without either breaking the web or making WebAssembly essentially a binary encoding of the JavaScript language.
The point of UnityJS is to tightly and efficiently integrate Unity3D and JavaScript, so it does a lot of JavaScript <=> C# calls, and I'm looking forward to it getting even faster!
https://github.com/SimHacker/UnityJS
You can pass delegates to C# functions that are directly callable into JavaScript using some magic PInvoke attributes and the Unity Runtime.dynCall function.
Declare a delegate that describes the signature of your C# function you want to call from JavaScript:
https://github.com/SimHacker/UnityJS/blob/master/UnityJS/Ass...
public delegate int AllocateTextureDelegate(int width, int height);
Then declare a C# static method with the MonoPInvokeCallback attribute, to implement you C# function:https://github.com/SimHacker/UnityJS/blob/master/UnityJS/Ass...
[MonoPInvokeCallback(typeof(AllocateTextureDelegate))]
public static int AllocateTexture(int width, int height) { ... }
Then pass those specially marked delegates to JavaScript and stash them in JS variables when you initialize (it doesn't work unless you use the magic MonoPInvokeCallback attribute):https://github.com/SimHacker/UnityJS/blob/master/UnityJS/Ass...
[DllImport(PLUGIN_DLL)]
public static extern void _UnityJS_HandleAwake(AllocateTextureDelegate allocateTextureCallback, FreeTextureDelegate freeTextureCallback, LockTextureDelegate lockTextureCallback, UnlockTextureDelegate unlockTextureCallback);
https://github.com/SimHacker/UnityJS/blob/master/UnityJS/Ass... public override void HandleAwake()
{
//Debug.Log("BridgeTransportWebGL: HandleAwake: this: " + this + " bridge: " + bridge);
_UnityJS_HandleAwake(
AllocateTexture,
FreeTexture,
LockTexture,
UnlockTexture);
}
In the awake function on the JavaScript side of your Unity WebGL extension (a .jslib file), wrap the C# delegate in a JavaScript thunk that calls into it via Runtime.dynCall:https://github.com/SimHacker/UnityJS/blob/master/UnityJS/Ass...
// Called by Unity when awakened.
_UnityJS_HandleAwake: function _UnityJS_HandleAwake(allocateTextureCallback, freeTextureCallback, lockTextureCallback, unlockTextureCallback)
{ [...]
function _UnityJS_AllocateTexture(width, height)
{
//console.log("UnityJS.jslib: _UnityJS_AllocateTexture: width: " + width + " height: " + height + " allocateTextureCallback: " + allocateTextureCallback);
var result = Runtime.dynCall('iii', allocateTextureCallback, [width, height]);
//console.log("UnityJS.jslib: _UnityJS_AllocateTexture: result: " + result);
return result;
};
window.bridge._UnityJS_AllocateTexture = _UnityJS_AllocateTexture;
Then you can call the C# method from JavaScript:https://github.com/SimHacker/UnityJS/blob/f0a4e1fb07fd9e8aab...
params.cache.backgroundSharedTextureID = id =
window.bridge._UnityJS_AllocateTexture(params.width, params.height);
This is zillions of time faster and more flexible than using Unity's terrible SendMessage technique to send messages from JS=>C#, whose only parameter is a single string, and which inefficiently dispatches messages by looking up Unity objects by name, and is asynchronous and can't return a result.I use this technique to efficiently copy binary textures and arrays of numbers between JavaScript and C#. MUCH better than serializing it as JSON, or base 64 encoded PNG files in a data: url (yuck!).
https://github.com/SimHacker/UnityJS/blob/674eda49be12a70812...
function DrawToCanvas(params, drawer, success, error)
{ [...]
var id = params.pie.backgroundSharedTextureID;
if (!id) {
params.pie.backgroundSharedTextureID = id =
window.bridge._UnityJS_AllocateTexture(params.width, params.height);
//console.log("game.js: DrawToCanvas: WebGL: AllocateTexture: width: " + params.width + " height: " + params.height + " id: " + id);
}
var imageData =
context.getImageData(0, 0, params.width, params.height);
window.bridge._UnityJS_UpdateTexture(id, imageData);
texture = {
type: 'sharedtexture',
id: id
};
success(texture, params);
canvasNode.parentNode.removeChild(canvasNode);
This lets me draw 2D user interface stuff, pie charts, diagrams, data visualizations, etc, in JavaScript with canvas, d3, or whatever library I like, and then efficiently use those images in Unity3D as user interface overlays, 3D textures, etc. It works great, and it's smooth and interactive, mixing up 2D canvas graphics with 3D Unity stuff!Unity is sorely lacking a decent 2D drawing library like canvas, not to mention fancy stuff built on top of it like d3.
I'm currently working on the plumbing to send binary arrays of floats from JavaScript to Unity, so I can pass them right into shaders!
Here's some discussion about the magic MonoPInvokeCallback attribute:
https://forum.unity.com/threads/monopinvokecallback-in-unity...
And about Unity.dyncall and the WebGL runtime:
https://forum.unity.com/threads/c-jslib-2-way-communication....
and:
https://forum.unity.com/threads/super-fast-javascript-intera...
Good note taken.