SlideShare uma empresa Scribd logo
1 de 53
Emscripten -Transpiling C
/ C++ to JS / HTML5
DaveVoyles
Sr.Tech Evangelist, Philadelphia
DaveVoyles.com
JavaScript is standards-based and the only
language that runs in all web browsers
You can run only JavaScript in browsers, but you can
write in another language - if you compile it to
JavaScript
Everything compiles to LLVM bitcode
Which we can then turn into JavaScript
Native code has its perks (performance!)
But so does rapid testing/sharing.
Transpile to JS and just share a URL
This is nothing new (well, sort of…)
C#, Python, Java,Typescript
All transpile to JavaScript
• Pyjs – Python
• JSIL – C#
• Java – GoogleWebToolkit
Why now?
non-standardized approaches (ActiveX, Silverlight,
Flash/Alchemy, PNaCl/PPAPI) have had limited success in the
past
Why now?
Plugins outside of HTML5 standards have not received
widespread adoption for both technical and non-technical
reasons
Besides, they are on their way out
No plugins for iOS devices, Google nixes NPAPI, etc.
This is great for the web! Standards!
JavaScript is a standard, so why not compile to that?
Example: gaming on the web
Experience w/ typical games:
• Go to platform-specific store, log in, find game, purchase,
download, install, patch, play
Experience w/ web games:
• www.DaveVoyles.com (Launches the game!)
JS then vs JS now
Then: JS began as a slow interpreted language
JS then vs JS now
Implicit, statically typed code in JS, just like the competition
JS then vs JS now
Now: Asm.js – highly optimized, performant subset of JS
asm.js overview
Emscripten overview
•Open source (MIT/LLVM)
•Began in 2010
Emscripten is built on LLVM
• clang C++ frontend
• LLVM optimizer
• libc++ C++ standard library
• libc++abi low-level C++ support
Clang supports nearly all C++ features, so
Emscripten does as well
Exception handling takes some work,
though
Runtime functions
What about other libraries?
SDL & OpenGL are implemented viaWeb APIs,
same with musl (Linux)
• Bullet
• Box2D
• Python
• Lua
• Ruby
• zlib
Not without its limitations
•64-bit integer math will not work
•No multithreading with shared state
•No Direct3D support, only OpenGL
Debugging
This is a problem in general with compiling for
the web. Source maps can help, but browsers do
have more work to do to make debugging
compiled code a smoother experience.
Start with your compiled code.
How does it work?
Numerictypes
JS
• double
LLVM
•i8, i16, i32, float,
double
Performance
LLVM
• types & operations map
~1:1 to CPU
• RAII offers Predictability
JS
• virtual machine (VM)
• just in time (JIT) compilers
w/ type profiling
• garbage collection
• Etc.
Builds
C++
•Need to recompile for
each CPU / OS
JS
•One build to rule them all
Variables
LLVM
•Local vars have function
scope
JS
•Local vars have function
scope
Security concerns
JS
•Sandboxed
• Cannot see the machine it
is running on
C++
•Apps can use system libs
•Access local filesystem
Security concerns (cont’d)
The JS stack is managed and unobservable/unmodifiable by
executing code.
Compiled C++ is immune to some types of buffer overflow attacks
Can be beneficial, though….
More speed
Loads in LLVM IR become reads from typed array
(binary data in the browser) in JS, which become reads in
machine code.
Why do this?
• Download just parts of the app, stream the rest
• Ex: Star Citizen: 100GB+Vs.Age ofAscent: 50Mb
• Circumvent app stores
• Want to push updates? Just update your web app
• No more 1 week waiting period, iOS
• Distribution through sources other than curated
app stores
• Release apps on your website
Browser support
native executable
Compiling with Emscripten
Generating code
The target file name extension defines the output type to
be generated:
<name> .js : JavaScript.
<name> .html : HTML + separate JavaScript file
(<name>.js). (Having the separate JavaScript file improves
page load time.)
<name> .bc : LLVM bitcode (default).
Porting process
emcc is a drop-in replacement for gcc or clang
In many cases, you can use your normal build
system, plug in emcc
Porting process
emcc is a drop-in replacement for gcc or clang
In many cases, you can use your normal build
system, plug in emcc
Connecting C / C++ and JS
Call compiled C++ classes from JavaScript using bindings created with:
• Embind orWebIDL-Binder
Call compiled C functions from normal JavaScript:
• Using ccall or cwrap.
• Using direct function calls (faster but more complicated).
Call JavaScript functions from C/C++:
• Using emscripten_run_script().
• Using EM_ASM() (faster).
• Using a C API implemented in JavaScript.
• As function pointers from C.
• Using the Embind val class.
Why not just turn your JavaScript
code into asm.js?
Run-time type checking takes time.
Why not just turn your JavaScript
code into asm.js?
In statically typed languages, such as C, the
compiler knows the type of each object when it
is being compiled.
Offline experience
• IndexedDB
• Local database of records, holding simple values and
hierarchical objects
• AppCache
• Offline browsing, stores content on the disk instead of
network
• Service Workers
• Coming soon
Performance
UnityWebGL benchmark
(Higher is better)
Unity WebGL Benchmarks
Unity WebGL Benchmarks
• In benchmarks which stressWebGL rendering performance (Particles,
Asteroid Field), Edge performs best of all tested browsers.
• When you are mostly GPU-bound, you can expect WebGL to perform
very similar to native code.
• In some areas,WebGL will actually outperform native code
significantly. (Mandlebrot & Cryptohash)
• Native code can still be several times faster thanWebGL for areas
heavily optimized to use multi-threading and/or SIMD, such as the 3D
physics tests.
Case study: Owlchemy Labs
• 200+ levels
• 300 assets can be spawned a runtime
• 38 full length songs
• 1 million lines of JavaScript
• WebGL build (With Unity engine!) = 68.8Mb
• PC build = 192 Mb
Exporting with Unity
What goes in must come out
When you build a WebGL project, Unity will create a folder with
the following files:
• index.html file that embeds your content in a web page.
• JavaScript file containing the code for your player.
• .mem file containing a binary image to initialize the heap
memory for your player.
• .data file containing the asset data and scenes.
• some supporting JavaScript files to initialize and load the
player.
Some missing features
• Networking other thanWWW class (a WebSockets plug-in is
available)
• Support for WebCam and Microphone access
• Threads
• Any .NET features requiring dynamic code generation
• Runtime generation of Substance textures
Conclusion
The advantages of porting C/C++ to JavaScript are
clear:
• Often a smaller package size
• Easily demo or share projects on the web
• Reuse existing code
References
Thank you to Alon Zakai (@Kripken)and his
wonderful work on the project!
• http://twvideo01.ubm-
us.net/o1/vault/gdconline12/Presentations/Emscripten%20(pt%201).pdf
• https://www.reddit.com/r/programming/comments/2k3b4j/alon_zakai_emscripten_and_as
mjs_cs_role_in_the/http://llvm.org/devmtg/2013-11/slides/Zakai-Emscripten.pdf
• http://llvm.org/devmtg/2013-11/slides/Zakai-Emscripten.pdf

Mais conteúdo relacionado

Mais procurados

.NET Core in the Real World
.NET Core in the Real World.NET Core in the Real World
.NET Core in the Real WorldNate Barbettini
 
Raffaele Rialdi
Raffaele RialdiRaffaele Rialdi
Raffaele RialdiCodeFest
 
Chromium: NaCl and Pepper API
Chromium: NaCl and Pepper APIChromium: NaCl and Pepper API
Chromium: NaCl and Pepper APIChang W. Doh
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS Ganesh Kondal
 
Return on Ignite 2019: Azure, .NET, A.I. & Data
Return on Ignite 2019: Azure, .NET, A.I. & DataReturn on Ignite 2019: Azure, .NET, A.I. & Data
Return on Ignite 2019: Azure, .NET, A.I. & DataMSDEVMTL
 
Basics of Node.js
Basics of Node.jsBasics of Node.js
Basics of Node.jsAlper Unal
 
.NET Core: a new .NET Platform
.NET Core: a new .NET Platform.NET Core: a new .NET Platform
.NET Core: a new .NET PlatformAlex Thissen
 
The future of server side JavaScript
The future of server side JavaScriptThe future of server side JavaScript
The future of server side JavaScriptOleg Podsechin
 
Fix: static code analysis into our project
Fix: static code analysis into our project Fix: static code analysis into our project
Fix: static code analysis into our project noelchris3
 
Raffaele Rialdi
Raffaele RialdiRaffaele Rialdi
Raffaele RialdiCodeFest
 
Designing and coding for cloud-native applications using Python, Harjinder Mi...
Designing and coding for cloud-native applications using Python, Harjinder Mi...Designing and coding for cloud-native applications using Python, Harjinder Mi...
Designing and coding for cloud-native applications using Python, Harjinder Mi...Pôle Systematic Paris-Region
 
20151117 IoT를 위한 서비스 구성과 개발
20151117 IoT를 위한 서비스 구성과 개발20151117 IoT를 위한 서비스 구성과 개발
20151117 IoT를 위한 서비스 구성과 개발영욱 김
 
3 Things Everyone Knows About Node JS That You Don't
3 Things Everyone Knows About Node JS That You Don't3 Things Everyone Knows About Node JS That You Don't
3 Things Everyone Knows About Node JS That You Don'tF5 Buddy
 

Mais procurados (20)

Coroutines in Kotlin
Coroutines in KotlinCoroutines in Kotlin
Coroutines in Kotlin
 
Node js for beginners
Node js for beginnersNode js for beginners
Node js for beginners
 
.NET Core in the Real World
.NET Core in the Real World.NET Core in the Real World
.NET Core in the Real World
 
Node js
Node jsNode js
Node js
 
Raffaele Rialdi
Raffaele RialdiRaffaele Rialdi
Raffaele Rialdi
 
Chromium: NaCl and Pepper API
Chromium: NaCl and Pepper APIChromium: NaCl and Pepper API
Chromium: NaCl and Pepper API
 
Super combinators
Super combinatorsSuper combinators
Super combinators
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS
 
Return on Ignite 2019: Azure, .NET, A.I. & Data
Return on Ignite 2019: Azure, .NET, A.I. & DataReturn on Ignite 2019: Azure, .NET, A.I. & Data
Return on Ignite 2019: Azure, .NET, A.I. & Data
 
Basics of Node.js
Basics of Node.jsBasics of Node.js
Basics of Node.js
 
HaXe Demo
HaXe DemoHaXe Demo
HaXe Demo
 
Nodejs intro
Nodejs introNodejs intro
Nodejs intro
 
.NET Core: a new .NET Platform
.NET Core: a new .NET Platform.NET Core: a new .NET Platform
.NET Core: a new .NET Platform
 
The future of server side JavaScript
The future of server side JavaScriptThe future of server side JavaScript
The future of server side JavaScript
 
Fix: static code analysis into our project
Fix: static code analysis into our project Fix: static code analysis into our project
Fix: static code analysis into our project
 
Raffaele Rialdi
Raffaele RialdiRaffaele Rialdi
Raffaele Rialdi
 
Designing and coding for cloud-native applications using Python, Harjinder Mi...
Designing and coding for cloud-native applications using Python, Harjinder Mi...Designing and coding for cloud-native applications using Python, Harjinder Mi...
Designing and coding for cloud-native applications using Python, Harjinder Mi...
 
20151117 IoT를 위한 서비스 구성과 개발
20151117 IoT를 위한 서비스 구성과 개발20151117 IoT를 위한 서비스 구성과 개발
20151117 IoT를 위한 서비스 구성과 개발
 
.Net Core
.Net Core.Net Core
.Net Core
 
3 Things Everyone Knows About Node JS That You Don't
3 Things Everyone Knows About Node JS That You Don't3 Things Everyone Knows About Node JS That You Don't
3 Things Everyone Knows About Node JS That You Don't
 

Semelhante a Getting started with Emscripten – Transpiling C / C++ to JavaScript / HTML5

차세대컴파일러, VM의미래: 애플 오픈소스 LLVM
차세대컴파일러, VM의미래: 애플 오픈소스 LLVM차세대컴파일러, VM의미래: 애플 오픈소스 LLVM
차세대컴파일러, VM의미래: 애플 오픈소스 LLVMJung Kim
 
Nodejs Native Add-Ons from zero to hero
Nodejs Native Add-Ons from zero to heroNodejs Native Add-Ons from zero to hero
Nodejs Native Add-Ons from zero to heroNicola Del Gobbo
 
Node.js Native AddOns from zero to hero - Nicola Del Gobbo - Codemotion Rome ...
Node.js Native AddOns from zero to hero - Nicola Del Gobbo - Codemotion Rome ...Node.js Native AddOns from zero to hero - Nicola Del Gobbo - Codemotion Rome ...
Node.js Native AddOns from zero to hero - Nicola Del Gobbo - Codemotion Rome ...Codemotion
 
.Net overviewrajnish
.Net overviewrajnish.Net overviewrajnish
.Net overviewrajnishRajnish Kalla
 
Stealing Chromium: Embedding HTML5 with the Servo Browser Engine (LinuxCon NA...
Stealing Chromium: Embedding HTML5 with the Servo Browser Engine (LinuxCon NA...Stealing Chromium: Embedding HTML5 with the Servo Browser Engine (LinuxCon NA...
Stealing Chromium: Embedding HTML5 with the Servo Browser Engine (LinuxCon NA...Samsung Open Source Group
 
2.3 (Architecture) Moving to Managed Code
2.3   (Architecture) Moving to Managed Code2.3   (Architecture) Moving to Managed Code
2.3 (Architecture) Moving to Managed CodeMicro Focus
 
Devfest09 Cschalk Gwt
Devfest09 Cschalk GwtDevfest09 Cschalk Gwt
Devfest09 Cschalk GwtChris Schalk
 
Android : How Do I Code Thee?
Android : How Do I Code Thee?Android : How Do I Code Thee?
Android : How Do I Code Thee?Viswanath J
 
Introduction to Java Part-2
Introduction to Java Part-2Introduction to Java Part-2
Introduction to Java Part-2RatnaJava
 
Introduction to Java
Introduction to Java Introduction to Java
Introduction to Java Hitesh-Java
 
ASP.NET Session 1
ASP.NET Session 1ASP.NET Session 1
ASP.NET Session 1Sisir Ghosh
 
NA Developer Day - Taking your COBOL apps to Net & JVM
NA Developer Day - Taking your COBOL apps to Net & JVM NA Developer Day - Taking your COBOL apps to Net & JVM
NA Developer Day - Taking your COBOL apps to Net & JVM Micro Focus
 

Semelhante a Getting started with Emscripten – Transpiling C / C++ to JavaScript / HTML5 (20)

차세대컴파일러, VM의미래: 애플 오픈소스 LLVM
차세대컴파일러, VM의미래: 애플 오픈소스 LLVM차세대컴파일러, VM의미래: 애플 오픈소스 LLVM
차세대컴파일러, VM의미래: 애플 오픈소스 LLVM
 
Sadiq786
Sadiq786Sadiq786
Sadiq786
 
Nodejs Native Add-Ons from zero to hero
Nodejs Native Add-Ons from zero to heroNodejs Native Add-Ons from zero to hero
Nodejs Native Add-Ons from zero to hero
 
Node.js Native AddOns from zero to hero - Nicola Del Gobbo - Codemotion Rome ...
Node.js Native AddOns from zero to hero - Nicola Del Gobbo - Codemotion Rome ...Node.js Native AddOns from zero to hero - Nicola Del Gobbo - Codemotion Rome ...
Node.js Native AddOns from zero to hero - Nicola Del Gobbo - Codemotion Rome ...
 
Nodejs overview
Nodejs overviewNodejs overview
Nodejs overview
 
Php on Windows
Php on WindowsPhp on Windows
Php on Windows
 
20120306 dublin js
20120306 dublin js20120306 dublin js
20120306 dublin js
 
.Net overviewrajnish
.Net overviewrajnish.Net overviewrajnish
.Net overviewrajnish
 
Stealing Chromium: Embedding HTML5 with the Servo Browser Engine (LinuxCon NA...
Stealing Chromium: Embedding HTML5 with the Servo Browser Engine (LinuxCon NA...Stealing Chromium: Embedding HTML5 with the Servo Browser Engine (LinuxCon NA...
Stealing Chromium: Embedding HTML5 with the Servo Browser Engine (LinuxCon NA...
 
2.3 (Architecture) Moving to Managed Code
2.3   (Architecture) Moving to Managed Code2.3   (Architecture) Moving to Managed Code
2.3 (Architecture) Moving to Managed Code
 
01 java intro
01 java intro01 java intro
01 java intro
 
Devfest09 Cschalk Gwt
Devfest09 Cschalk GwtDevfest09 Cschalk Gwt
Devfest09 Cschalk Gwt
 
Android : How Do I Code Thee?
Android : How Do I Code Thee?Android : How Do I Code Thee?
Android : How Do I Code Thee?
 
Introduction to Java Part-2
Introduction to Java Part-2Introduction to Java Part-2
Introduction to Java Part-2
 
Introduction to Java
Introduction to Java Introduction to Java
Introduction to Java
 
Beginners Node.js
Beginners Node.jsBeginners Node.js
Beginners Node.js
 
ASP.NET Session 1
ASP.NET Session 1ASP.NET Session 1
ASP.NET Session 1
 
Where should I run my code? Serverless, Containers, Virtual Machines and more
Where should I run my code? Serverless, Containers, Virtual Machines and moreWhere should I run my code? Serverless, Containers, Virtual Machines and more
Where should I run my code? Serverless, Containers, Virtual Machines and more
 
NA Developer Day - Taking your COBOL apps to Net & JVM
NA Developer Day - Taking your COBOL apps to Net & JVM NA Developer Day - Taking your COBOL apps to Net & JVM
NA Developer Day - Taking your COBOL apps to Net & JVM
 
20120802 timisoara
20120802 timisoara20120802 timisoara
20120802 timisoara
 

Mais de David Voyles

Developing games for consoles as an indie in 2019
Developing games for consoles as an indie in 2019Developing games for consoles as an indie in 2019
Developing games for consoles as an indie in 2019David Voyles
 
Developing for consoles as an indie in 2019
Developing for consoles as an indie in 2019Developing for consoles as an indie in 2019
Developing for consoles as an indie in 2019David Voyles
 
Overview Microsoft's ML & AI tools
Overview Microsoft's ML & AI toolsOverview Microsoft's ML & AI tools
Overview Microsoft's ML & AI toolsDavid Voyles
 
Intro to deep learning
Intro to deep learning Intro to deep learning
Intro to deep learning David Voyles
 
What is a Tech Evangelist?
What is a Tech Evangelist?What is a Tech Evangelist?
What is a Tech Evangelist?David Voyles
 
Microsoft on open source and security
Microsoft on open source and securityMicrosoft on open source and security
Microsoft on open source and securityDavid Voyles
 
Students: How to get started in the tech world
Students: How to get started in the tech worldStudents: How to get started in the tech world
Students: How to get started in the tech worldDavid Voyles
 
Students -- How to get started in the tech world
Students -- How to get started in the tech worldStudents -- How to get started in the tech world
Students -- How to get started in the tech worldDavid Voyles
 
How to win a hackathon - Penn APps 2015
How to win a hackathon - Penn APps 2015How to win a hackathon - Penn APps 2015
How to win a hackathon - Penn APps 2015David Voyles
 
Running, improving & maintaining a site in the real world
Running, improving & maintaining a site in the real worldRunning, improving & maintaining a site in the real world
Running, improving & maintaining a site in the real worldDavid Voyles
 
Building web front ends using single page applications
Building web front ends using single page applicationsBuilding web front ends using single page applications
Building web front ends using single page applicationsDavid Voyles
 
Web standards and Visual Studio web tools
Web standards and Visual Studio web toolsWeb standards and Visual Studio web tools
Web standards and Visual Studio web toolsDavid Voyles
 
Build and deploy an ASP.NET applicaton
Build and deploy an ASP.NET applicatonBuild and deploy an ASP.NET applicaton
Build and deploy an ASP.NET applicatonDavid Voyles
 
Cluster puck99 postmortem
Cluster puck99 postmortemCluster puck99 postmortem
Cluster puck99 postmortemDavid Voyles
 
Joe Healy - How to set up your DreamSpark account
Joe Healy - How to set up your DreamSpark accountJoe Healy - How to set up your DreamSpark account
Joe Healy - How to set up your DreamSpark accountDavid Voyles
 
Joe Healy - Students as App Publishers
Joe Healy - Students as App PublishersJoe Healy - Students as App Publishers
Joe Healy - Students as App PublishersDavid Voyles
 
Using prime[31] to connect your unity game to azure mobile services
Using prime[31] to connect your unity game to azure mobile servicesUsing prime[31] to connect your unity game to azure mobile services
Using prime[31] to connect your unity game to azure mobile servicesDavid Voyles
 
An Introdouction to Venture Capital and Microsoft Ventures
An Introdouction to Venture Capital and Microsoft VenturesAn Introdouction to Venture Capital and Microsoft Ventures
An Introdouction to Venture Capital and Microsoft VenturesDavid Voyles
 
Intro to WebGL and BabylonJS
Intro to WebGL and BabylonJSIntro to WebGL and BabylonJS
Intro to WebGL and BabylonJSDavid Voyles
 

Mais de David Voyles (20)

Developing games for consoles as an indie in 2019
Developing games for consoles as an indie in 2019Developing games for consoles as an indie in 2019
Developing games for consoles as an indie in 2019
 
Developing for consoles as an indie in 2019
Developing for consoles as an indie in 2019Developing for consoles as an indie in 2019
Developing for consoles as an indie in 2019
 
Overview Microsoft's ML & AI tools
Overview Microsoft's ML & AI toolsOverview Microsoft's ML & AI tools
Overview Microsoft's ML & AI tools
 
Intro to deep learning
Intro to deep learning Intro to deep learning
Intro to deep learning
 
What is a Tech Evangelist?
What is a Tech Evangelist?What is a Tech Evangelist?
What is a Tech Evangelist?
 
Microsoft on open source and security
Microsoft on open source and securityMicrosoft on open source and security
Microsoft on open source and security
 
Students: How to get started in the tech world
Students: How to get started in the tech worldStudents: How to get started in the tech world
Students: How to get started in the tech world
 
Students -- How to get started in the tech world
Students -- How to get started in the tech worldStudents -- How to get started in the tech world
Students -- How to get started in the tech world
 
How to win a hackathon - Penn APps 2015
How to win a hackathon - Penn APps 2015How to win a hackathon - Penn APps 2015
How to win a hackathon - Penn APps 2015
 
ASP.NET 5
ASP.NET 5ASP.NET 5
ASP.NET 5
 
Running, improving & maintaining a site in the real world
Running, improving & maintaining a site in the real worldRunning, improving & maintaining a site in the real world
Running, improving & maintaining a site in the real world
 
Building web front ends using single page applications
Building web front ends using single page applicationsBuilding web front ends using single page applications
Building web front ends using single page applications
 
Web standards and Visual Studio web tools
Web standards and Visual Studio web toolsWeb standards and Visual Studio web tools
Web standards and Visual Studio web tools
 
Build and deploy an ASP.NET applicaton
Build and deploy an ASP.NET applicatonBuild and deploy an ASP.NET applicaton
Build and deploy an ASP.NET applicaton
 
Cluster puck99 postmortem
Cluster puck99 postmortemCluster puck99 postmortem
Cluster puck99 postmortem
 
Joe Healy - How to set up your DreamSpark account
Joe Healy - How to set up your DreamSpark accountJoe Healy - How to set up your DreamSpark account
Joe Healy - How to set up your DreamSpark account
 
Joe Healy - Students as App Publishers
Joe Healy - Students as App PublishersJoe Healy - Students as App Publishers
Joe Healy - Students as App Publishers
 
Using prime[31] to connect your unity game to azure mobile services
Using prime[31] to connect your unity game to azure mobile servicesUsing prime[31] to connect your unity game to azure mobile services
Using prime[31] to connect your unity game to azure mobile services
 
An Introdouction to Venture Capital and Microsoft Ventures
An Introdouction to Venture Capital and Microsoft VenturesAn Introdouction to Venture Capital and Microsoft Ventures
An Introdouction to Venture Capital and Microsoft Ventures
 
Intro to WebGL and BabylonJS
Intro to WebGL and BabylonJSIntro to WebGL and BabylonJS
Intro to WebGL and BabylonJS
 

Último

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 

Último (20)

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 

Getting started with Emscripten – Transpiling C / C++ to JavaScript / HTML5

  • 1. Emscripten -Transpiling C / C++ to JS / HTML5 DaveVoyles Sr.Tech Evangelist, Philadelphia DaveVoyles.com
  • 2. JavaScript is standards-based and the only language that runs in all web browsers You can run only JavaScript in browsers, but you can write in another language - if you compile it to JavaScript
  • 3. Everything compiles to LLVM bitcode Which we can then turn into JavaScript
  • 4. Native code has its perks (performance!) But so does rapid testing/sharing. Transpile to JS and just share a URL
  • 5. This is nothing new (well, sort of…) C#, Python, Java,Typescript All transpile to JavaScript • Pyjs – Python • JSIL – C# • Java – GoogleWebToolkit
  • 6. Why now? non-standardized approaches (ActiveX, Silverlight, Flash/Alchemy, PNaCl/PPAPI) have had limited success in the past
  • 7. Why now? Plugins outside of HTML5 standards have not received widespread adoption for both technical and non-technical reasons
  • 8. Besides, they are on their way out No plugins for iOS devices, Google nixes NPAPI, etc.
  • 9. This is great for the web! Standards! JavaScript is a standard, so why not compile to that?
  • 10. Example: gaming on the web Experience w/ typical games: • Go to platform-specific store, log in, find game, purchase, download, install, patch, play Experience w/ web games: • www.DaveVoyles.com (Launches the game!)
  • 11. JS then vs JS now Then: JS began as a slow interpreted language
  • 12. JS then vs JS now Implicit, statically typed code in JS, just like the competition
  • 13. JS then vs JS now Now: Asm.js – highly optimized, performant subset of JS
  • 15. Emscripten overview •Open source (MIT/LLVM) •Began in 2010
  • 16. Emscripten is built on LLVM • clang C++ frontend • LLVM optimizer • libc++ C++ standard library • libc++abi low-level C++ support
  • 17. Clang supports nearly all C++ features, so Emscripten does as well Exception handling takes some work, though
  • 18.
  • 20. What about other libraries? SDL & OpenGL are implemented viaWeb APIs, same with musl (Linux) • Bullet • Box2D • Python • Lua • Ruby • zlib
  • 21. Not without its limitations •64-bit integer math will not work •No multithreading with shared state •No Direct3D support, only OpenGL
  • 22. Debugging This is a problem in general with compiling for the web. Source maps can help, but browsers do have more work to do to make debugging compiled code a smoother experience. Start with your compiled code.
  • 23. How does it work?
  • 25. Performance LLVM • types & operations map ~1:1 to CPU • RAII offers Predictability JS • virtual machine (VM) • just in time (JIT) compilers w/ type profiling • garbage collection • Etc.
  • 26. Builds C++ •Need to recompile for each CPU / OS JS •One build to rule them all
  • 27. Variables LLVM •Local vars have function scope JS •Local vars have function scope
  • 28. Security concerns JS •Sandboxed • Cannot see the machine it is running on C++ •Apps can use system libs •Access local filesystem
  • 29. Security concerns (cont’d) The JS stack is managed and unobservable/unmodifiable by executing code. Compiled C++ is immune to some types of buffer overflow attacks Can be beneficial, though….
  • 30. More speed Loads in LLVM IR become reads from typed array (binary data in the browser) in JS, which become reads in machine code.
  • 31. Why do this? • Download just parts of the app, stream the rest • Ex: Star Citizen: 100GB+Vs.Age ofAscent: 50Mb • Circumvent app stores • Want to push updates? Just update your web app • No more 1 week waiting period, iOS • Distribution through sources other than curated app stores • Release apps on your website
  • 35. Generating code The target file name extension defines the output type to be generated: <name> .js : JavaScript. <name> .html : HTML + separate JavaScript file (<name>.js). (Having the separate JavaScript file improves page load time.) <name> .bc : LLVM bitcode (default).
  • 36. Porting process emcc is a drop-in replacement for gcc or clang In many cases, you can use your normal build system, plug in emcc
  • 37. Porting process emcc is a drop-in replacement for gcc or clang In many cases, you can use your normal build system, plug in emcc
  • 38. Connecting C / C++ and JS Call compiled C++ classes from JavaScript using bindings created with: • Embind orWebIDL-Binder Call compiled C functions from normal JavaScript: • Using ccall or cwrap. • Using direct function calls (faster but more complicated). Call JavaScript functions from C/C++: • Using emscripten_run_script(). • Using EM_ASM() (faster). • Using a C API implemented in JavaScript. • As function pointers from C. • Using the Embind val class.
  • 39. Why not just turn your JavaScript code into asm.js? Run-time type checking takes time.
  • 40. Why not just turn your JavaScript code into asm.js? In statically typed languages, such as C, the compiler knows the type of each object when it is being compiled.
  • 41. Offline experience • IndexedDB • Local database of records, holding simple values and hierarchical objects • AppCache • Offline browsing, stores content on the disk instead of network • Service Workers • Coming soon
  • 44. (Higher is better) Unity WebGL Benchmarks
  • 45. Unity WebGL Benchmarks • In benchmarks which stressWebGL rendering performance (Particles, Asteroid Field), Edge performs best of all tested browsers. • When you are mostly GPU-bound, you can expect WebGL to perform very similar to native code. • In some areas,WebGL will actually outperform native code significantly. (Mandlebrot & Cryptohash) • Native code can still be several times faster thanWebGL for areas heavily optimized to use multi-threading and/or SIMD, such as the 3D physics tests.
  • 46. Case study: Owlchemy Labs • 200+ levels • 300 assets can be spawned a runtime • 38 full length songs • 1 million lines of JavaScript • WebGL build (With Unity engine!) = 68.8Mb • PC build = 192 Mb
  • 47.
  • 49. What goes in must come out When you build a WebGL project, Unity will create a folder with the following files: • index.html file that embeds your content in a web page. • JavaScript file containing the code for your player. • .mem file containing a binary image to initialize the heap memory for your player. • .data file containing the asset data and scenes. • some supporting JavaScript files to initialize and load the player.
  • 50. Some missing features • Networking other thanWWW class (a WebSockets plug-in is available) • Support for WebCam and Microphone access • Threads • Any .NET features requiring dynamic code generation • Runtime generation of Substance textures
  • 51. Conclusion The advantages of porting C/C++ to JavaScript are clear: • Often a smaller package size • Easily demo or share projects on the web • Reuse existing code
  • 52.
  • 53. References Thank you to Alon Zakai (@Kripken)and his wonderful work on the project! • http://twvideo01.ubm- us.net/o1/vault/gdconline12/Presentations/Emscripten%20(pt%201).pdf • https://www.reddit.com/r/programming/comments/2k3b4j/alon_zakai_emscripten_and_as mjs_cs_role_in_the/http://llvm.org/devmtg/2013-11/slides/Zakai-Emscripten.pdf • http://llvm.org/devmtg/2013-11/slides/Zakai-Emscripten.pdf

Notas do Editor

  1. The Low Level Virtual Machine (LLVM) is a library that is used to construct, optimize and produce intermediate and/or binary machine code. It can be used as a compiler framework, where you provide the "front end" – Clang- (parser and lexer) and the "back end" (code that converts LLVM's representation to actual machine code). Starting in 2005, Apple has made extensive use of LLVM in a number of commercial systems,[6] including theiPhone development kit and Xcode 3.1GLSL, and others.
  2. Subset of JavaScript, largely led by Mozilla, and specifically Alon Zakai and Luke Wagner  The principal benefit of asm.js over whole new technologies like NaCl and PNaCl is that it works today: existing JavaScript engines already optimize this style of code quite well. Plan is to keep optimizing JIT compilers, but JIT compilers have less predictable performance based on complicated heuristics. The asm.js model provides a model closer to C/C++ by eliminating dynamic type guards, boxed values, and garbage collection. - Box Values:  data structures that are minimal wrappers around primitive types*. Boxed values are typically stored as pointers to objects on the heap.
  3. Emscripten is an LLVM based project that compiles C and C++ into highly performant JavaScript in the asm.js format. In short: near native speeds, using C and C++, inside of the browser.  Even better, emscripten converts OpenGL, a desktop graphics API, into WebGL, which is the web variant of that API.
  4. JavaScript typed arrays are array-like objects and provide a mechanism for accessing raw binary data. As you already know, Array objects grow and shrink dynamically and can have any JavaScript value. JavaScript engines perform optimizations so that these arrays are fast. 
  5. JavaScript typed arrays are array-like objects and provide a mechanism for accessing raw binary data. As you already know, Array objects grow and shrink dynamically and can have any JavaScript value. JavaScript engines perform optimizations so that these arrays are fast. 
  6. This operator allows inserting expressions that produce side effects into places where an expression that evaluates to undefined is desired. The void operator is often used merely to obtain the undefined primitive value, usually using "void(0)" (which is equivalent to "void 0"). In these cases, the global variable undefined can be used instead (assuming it has not been assigned to a non-default value).
  7. Emscripten mplements C++ exceptions using JS exceptions, JS VM provides stack unwinding Perf depends on the speed of JS exceptions
  8. We build for a 32-bit target, because 64-bit integers cannot all fit in doubles (but 32-bit ones can)
  9. Resource Acquisition Is Initialization (RAII) is a programming idiom used in several object-oriented languages, most prominently C++, where it originated, but also D, Ada, Vala, and Rust. n RAII, holding a resource is tied to object lifetime: resource allocation (acquisition) is done during object creation (specifically initialization), by the constructor, while resource deallocation (release) is done during object destruction, by thedestructor. If objects are destroyed properly, resource leaks do not occur.
  10. Having a single build does prevent some optimizations, though
  11. Applications must ship their own system libraries. Emscripten "fakes" a filesystem to make porting easy.
  12. Applications must ship their own system libraries. Emscripten "fakes" a filesystem to make porting easy.
  13. JavaScript typed arrays are array-like objects and provide a mechanism for accessing raw binary data. A Typed Array is a slab of memory with a typed view into it, much like how arrays work in C. Because a Typed Array is backed by raw memory, the JavaScript engine can pass the memory directly to native libraries without having to painstakingly convert the data to a native representation. As a result, typed arrays perform a lot better than JavaScript arrays for passing data to WebGL and other APIs dealing with binary data. Typed array views act like single-type arrays to a segment of an ArrayBuffer. There are views for all the usual numeric types, with self-descriptive names like Float32Array, Float64Array, Int32Array and Uint8Array.
  14. This is a pretty common question. The one I hear most though is “who would want to download a 60MB website? And you’re right — 60mb for a website is massive! But I suppose the same people who are downloading gigabytes worth of video content from YouTube and Netflix each day are those same people. Jonas Echterhoff pointed out that in Untiy, streaming assets is already possibly by using AssetBundles. Alternatively, you can try this Asset Store package, which repackages the WebGL build data, so that scenes in your build are split across multiple files, and your content can start once the first scene is loaded.
  15. CanIUse.com
  16. I know what you’re thinking. “This is great, but if there isn’t any sort of interoperability between my C++ and JavaScript, then this isn’t very useful.” Fortunately, there is!
  17. JavaScript can’t really be compiled to asm.js and offer much of a benefit, because of its dynamic nature. It’s the same problem as when trying to compile it to C or even to native code –  a VM with it  would be necessary to take care of those non-static aspects.  You could write asm.js by hand, however. To better understand this, it is important to comprehend why asm.js offers a performance benefit at all; or why statically-typed languages perform better than dynamically-typed ones. One reason is “run-time type checking takes time,” and a more thought out answer would include the enhanced feasibility of optimizing statically-typed code. A final perk of going from a statically typed language such as C is the fact that the compiler knows the type of each object when it is being compiled.
  18. JavaScript can’t really be compiled to asm.js and offer much of a benefit, because of its dynamic nature. It’s the same problem as when trying to compile it to C or even to native code –  a VM with it  would be necessary to take care of those non-static aspects.  You could write asm.js by hand, however. To better understand this, it is important to comprehend why asm.js offers a performance benefit at all; or why statically-typed languages perform better than dynamically-typed ones. One reason is “run-time type checking takes time,” and a more thought out answer would include the enhanced feasibility of optimizing statically-typed code. A final perk of going from a statically typed language such as C is the fact that the compiler knows the type of each object when it is being compiled.
  19. It would be wise to have a mix of local and remote content for your app. Technologies like IndexedDB, localStorage, and AppCache, which are supported by Microsoft Edge, allow for this. A number of browsers support all of these technologies as well, including Firefox and Chrome.  A local page can be kept in your app package that can still provide a basic offline experience. Finally, Service Workers are a useful option for offline caching, too. Matt Gaunt has a fantastic article on Service Workers.
  20. http://beta.unity3d.com/jonas/WebGLBenchmark/
  21. http://beta.unity3d.com/jonas/WebGLBenchmark/
  22. http://beta.unity3d.com/jonas/benchmark2015/ http://blogs.unity3d.com/2015/12/15/updated-webgl-benchmark-results/#comment-239858 Here are the overall scores of the different browsers running the benchmark suite on an Windows 10 machine with a 3.3.GHz i7 CPU and an Nvidia GTX 960 GPU some common performance-enhancing techniques, like multi-threading and SIMD, are not available yet; and we are relying on a completely new scripting runtime, IL2Cpp, to run user script code. So we need to find out: Will it be fast enough to play games?
  23. This is the case for tests which rely a lot on script performance (Mandelbrot and CryptoHash, both implement their algorithms in C#).
  24. The team at Owlchemy labs converted their game Aaaaa! In 2014 and put together a great postmortem about the process. Using the pre-alpha version of the WebGL exporter in June of last year, they were able to take all of their C# code and turn it into one JavaScript file which was more than 1 million lines of code long!
  25. Not just for games. Architecture too. Dozens of these online. Unreal Engine 4 -> HTML5
  26. Source: Brendan Eich
  27. Many of these slides were compiled from information I’ve gathered from Alon Zakai’s presentations online, but in powerpoint and video form.