diff --git a/emcc.py b/emcc.py index 32e135984f94f..9c9524ee314df 100755 --- a/emcc.py +++ b/emcc.py @@ -1822,7 +1822,7 @@ def parse_args(newargs): should_exit = False for i in range(len(newargs)): - # On Windows Vista (and possibly others), excessive spaces in the command line + # On Windows Vista (and possibly others), excessive spaces in the command line # leak into the items in this array, so trim e.g. 'foo.cpp ' -> 'foo.cpp' newargs[i] = newargs[i].strip() if newargs[i].startswith('-O'): diff --git a/site/source/api_items.py b/site/source/api_items.py index ebd4cfb6a7060..a708f7bc8b612 100644 --- a/site/source/api_items.py +++ b/site/source/api_items.py @@ -268,4 +268,4 @@ def get_mapped_items(): mapped_wiki_inline_code['HEAPU32']=':js:data:`HEAPU32`' mapped_wiki_inline_code['EMSCRIPTEN_VISIBILITY_HIDDEN']=':c:macro:`EMSCRIPTEN_VISIBILITY_HIDDEN`' mapped_wiki_inline_code['addRunDependency']=':js:func:`addRunDependency`' - return mapped_wiki_inline_code \ No newline at end of file + return mapped_wiki_inline_code diff --git a/site/source/conf.py b/site/source/conf.py index 8fe15034c7667..890e635fafbd7 100644 --- a/site/source/conf.py +++ b/site/source/conf.py @@ -64,7 +64,7 @@ #Build "Todo" notes into the source -#todo_include_todos = 'True' +#todo_include_todos = 'True' # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] diff --git a/site/source/docs/api_reference/Filesystem-API.rst b/site/source/docs/api_reference/Filesystem-API.rst index fc1a9d113af38..496baf738c7bd 100644 --- a/site/source/docs/api_reference/Filesystem-API.rst +++ b/site/source/docs/api_reference/Filesystem-API.rst @@ -6,7 +6,7 @@ File System API File operations in Emscripten are provided by the `FS `_ library. It is used internally for all of Emscripten's **libc** and **libcxx** file I/O. -.. note:: The API is *inspired* by the Linux/POSIX `File System API `_, with each presenting a very similar interface. +.. note:: The API is *inspired* by the Linux/POSIX `File System API `_, with each presenting a very similar interface. The underlying behaviour is also similar, except where differences between the native and browser environments make this unreasonable. For example, user and group permissions are defined but ignored in :js:func:`FS.open`. @@ -16,7 +16,7 @@ File data in Emscripten is partitioned by mounted file systems. Several file sys The automatic tests in `tests/test_core.py `_ (search for ``test_files``) contain many examples of how to use this API. The :ref:`tutorial ` also shows how to pre-load a file so that it can be read from compiled C/C++. -A high level overview of the way File Systems work in Emscripten-ported code is provided in the :ref:`file-system-overview`. +A high level overview of the way File Systems work in Emscripten-ported code is provided in the :ref:`file-system-overview`. Including File System Support ============================= @@ -31,7 +31,7 @@ However, if your C/C++ code doesn't use files, but you want to use them from Jav Persistent data =============== -Applications compiled with Emscripten usually expect synchronous I/O, so Emscripten itself provides file systems with completely synchronous interfaces. +Applications compiled with Emscripten usually expect synchronous I/O, so Emscripten itself provides file systems with completely synchronous interfaces. However, due to JavaScript's event-driven nature, most *persistent* storage options offer only asynchronous interfaces. Emscripten offers :ref:`multiple file systems ` that can be mounted with :js:func:`FS.mount` to help deal with persistence depending on the execution context. @@ -52,7 +52,7 @@ This is the default file system mounted at ``/`` when the runtime is initialized NODEFS ------ -.. note:: This file system is only for use when running inside :term:`node.js`. +.. note:: This file system is only for use when running inside :term:`node.js`. This file system lets a program in *node* map directories (via a mount operation) on the host filesystem to directories in Emscripten's virtual filesystem. It uses node's synchronous `FS API `_ to immediately persist any data written to the Emscripten file system to your local disk. @@ -63,11 +63,11 @@ See `this test `_. @@ -108,7 +108,7 @@ The device node acts as an interface between the device and the file system. Any Setting up standard I/O devices =============================== -Emscripten standard I/O works by going though the virtual ``/dev/stdin``, ``/dev/stdout`` and ``/dev/stderr`` devices. You can set them up using your own I/O functions by calling :js:func:`FS.init`. +Emscripten standard I/O works by going though the virtual ``/dev/stdin``, ``/dev/stdout`` and ``/dev/stderr`` devices. You can set them up using your own I/O functions by calling :js:func:`FS.init`. By default: @@ -122,12 +122,12 @@ By default: .. js:function:: FS.init(input, output, error) Sets up standard I/O devices for ``stdin``, ``stdout``, and ``stderr``. - + The devices are set up using the following (optional) callbacks. If any of the callbacks throw an exception, it will be caught and handled as if the device malfunctioned. :param input: Input callback. This will be called with no parameters whenever the program attempts to read from ``stdin``. It should return an ASCII character code when data is available, or ``null`` when it isn't. :param output: Output callback. This will be called with an ASCII character code whenever the program writes to ``stdout``. It may also be called with ``null`` to flush the output. - :param error: Error callback. This is similar to ``output``, except it is called when data is written to ``stderr``. + :param error: Error callback. This is similar to ``output``, except it is called when data is written to ``stderr``. File system API @@ -139,12 +139,12 @@ File system API Mounts the FS object specified by ``type`` to the directory specified by ``mountpoint``. The ``opts`` object is specific to each file system type. :param type: The :ref:`file system type `: ``MEMFS``, ``NODEFS``, ``IDBFS`` or ``WORKERFS``. - :param object opts: A generic settings object used by the underlying file system. - - ``NODFES`` uses the `root` parameter to map the Emscripten directory to the physical directory. For example, to mount the current folder as a NODEFS instance: - + :param object opts: A generic settings object used by the underlying file system. + + ``NODFES`` uses the `root` parameter to map the Emscripten directory to the physical directory. For example, to mount the current folder as a NODEFS instance: + :: - + FS.mkdir('/working'); FS.mount(NODEFS, { root: '.' }, '/working'); @@ -173,22 +173,22 @@ File system API :param string mountpoint: A path to an existing local Emscripten directory where the file system is to be mounted. It can be either an absolute path, or something relative to the current directory. - + .. js:function:: FS.unmount(mountpoint) - Unmounts the specified ``mountpoint``. + Unmounts the specified ``mountpoint``. :param string mountpoint: The directory to unmount. - + .. js:function:: FS.syncfs(populate, callback) Responsible for iterating and synchronizing all mounted file systems in an asynchronous fashion. - + .. note:: Currently, only the :ref:`filesystem-api-idbfs` file system implements the interfaces needed for synchronization. All other file systems are completely synchronous and don't require synchronization. - The ``populate`` flag is used to control the intended direction of the underlying synchronization between Emscripten`s internal data, and the file system's persistent data. + The ``populate`` flag is used to control the intended direction of the underlying synchronization between Emscripten`s internal data, and the file system's persistent data. For example: @@ -222,9 +222,9 @@ File system API .. code:: javascript FS.mkdir('/data'); - + .. note:: The underlying implementation does not support user or group permissions. The caller is always treated as the owner of the folder, and only permissions relevant to the owner apply. - + :param string path: The path name for the new directory node. :param int mode: :ref:`File permissions ` for the new node. The default setting (`in octal numeric notation `_) is 0777. @@ -269,7 +269,7 @@ File system API :param string oldpath: The old path name. :param string newpath: The new path name - + .. js:function:: FS.rmdir(path) @@ -288,10 +288,10 @@ File system API .. js:function:: FS.unlink(path) Unlinks the node at ``path``. - - This removes a name from the file system. If that name was the last link to a file (and no processes have the file open) the file is deleted. - - For example: + + This removes a name from the file system. If that name was the last link to a file (and no processes have the file open) the file is deleted. + + For example: .. code:: javascript @@ -299,12 +299,12 @@ File system API FS.unlink('/foobar.txt'); :param string path: Path of the target node. - - + + .. js:function:: FS.readlink(path) - Gets the string value stored in the symbolic link at ``path``. For example: + Gets the string value stored in the symbolic link at ``path``. For example: .. code:: c @@ -325,10 +325,10 @@ File system API :: file - + :param string path: Path to the target file. :returns: The string value stored in the symbolic link at ``path``. - + .. js:function:: FS.stat(path) @@ -380,10 +380,10 @@ File system API .. js:function:: FS.chmod(path, mode) - Change the mode flags for ``path`` to ``mode``. - + Change the mode flags for ``path`` to ``mode``. + .. note:: The underlying implementation does not support user or group permissions. The caller is always treated as the owner of the folder, and only permissions relevant to the owner apply. - + For example: .. code:: javascript @@ -416,7 +416,7 @@ File system API .. js:function:: FS.chown(path, uid, gid) Change the ownership of the specified file to the given user or group id. - + .. note:: |note-completeness| :param string path: Path to the target file. @@ -428,7 +428,7 @@ File system API .. js:function:: FS.lchown(path, uid, gid) Identical to :js:func:`FS.chown`. However, if ``path`` is a symbolic link then the properties will be set on the link itself, not the file that it links to. - + .. note:: |note-completeness| :param string path: Path to the target file. @@ -440,14 +440,14 @@ File system API .. js:function:: FS.fchown(fd, uid, gid) Identical to :js:func:`FS.chown`. However, a raw file descriptor is supplied as ``fd``. - + .. note:: |note-completeness| :param int fd: Descriptor of target file. :param int uid: The id of the user to take ownership of the file. :param int gid: The id of the group to take ownership of the file. - + .. js:function:: FS.truncate(path, len) @@ -472,12 +472,12 @@ File system API :: foo - + :param string path: Path of the file to be truncated. :param int len: The truncation length for the file. - - - + + + .. js:function:: FS.ftruncate(fd, len) Truncates the file identified by the ``fd`` to the specified length (``len``). @@ -489,21 +489,21 @@ File system API .. js:function:: FS.utime(path, atime, mtime) Change the timestamps of the file located at ``path``. The times passed to the arguments are in *milliseconds* since January 1, 1970 (midnight UTC/GMT). - + Note that in the current implementation the stored timestamp is a single value, the maximum of ``atime`` and ``mtime``. - + :param string path: The path of the file to update. :param int atime: The file modify time (milliseconds). :param int mtime: The file access time (milliseconds). - + .. js:function:: FS.open(path, flags [, mode]) Opens a file with the specified flags. ``flags`` can be: .. _fs-read-and-write-flags: - + - ``r`` — Open file for reading. - ``r+`` — Open file for reading and writing. - ``w`` — Open file for writing. @@ -517,18 +517,18 @@ File system API .. note:: The underlying implementation does not support user or group permissions. The file permissions set in ``mode`` are only used if the file is created. The caller is always treated as the owner of the file, and only those permissions apply. - + :param string path: The path of the file to open. :param string flags: Read and write :ref:`flags `. - :param mode: File permission :ref:`flags ` for the file. The default setting (`in octal numeric notation `_) is 0666. - :returns: A stream object. + :param mode: File permission :ref:`flags ` for the file. The default setting (`in octal numeric notation `_) is 0666. + :returns: A stream object. + - .. js:function:: FS.close(stream) Closes the file stream. - + :param object stream: The stream to be closed. @@ -536,20 +536,20 @@ File system API .. js:function:: FS.llseek(stream, offset, whence) Repositions the offset of the stream ``offset`` bytes relative to the beginning, current position, or end of the file, depending on the ``whence`` parameter. - + The ``_llseek()`` function repositions the ``offset`` of the open file associated with the file descriptor ``fd`` to ``(offset_high<<32) | offset_low`` bytes relative to the beginning of the file, the current position in the file, or the end of the file, depending on whether whence is ``SEEK_SET``, ``SEEK_CUR``, or ``SEEK_END``, respectively. It returns the resulting file position in the argument result. - + .. todo:: **HamishW** Above sentence does not make sense. Have requested feedback. :param object stream: The stream for which the offset is to be repositioned. :param int offset: The offset (in bytes) relative to ``whence``. :param int whence: Point in file (beginning, current point, end) from which to calculate the offset: ``SEEK_SET`` (0), ``SEEK_CUR`` (1) or ``SEEK_END`` (2) - + .. js:function:: FS.read(stream, buffer, offset, length [, position]) - Read ``length`` bytes from the stream, storing them into ``buffer`` starting at ``offset``. - + Read ``length`` bytes from the stream, storing them into ``buffer`` starting at ``offset``. + By default, reading starts from the stream's current offset, however, a specific offset can be specified with the ``position`` argument. For example: .. code:: javascript @@ -564,13 +564,13 @@ File system API :param int offset: The offset within ``buffer`` to store the data. :param int length: The length of data to write in ``buffer``. :param int position: The offset within the stream to read. By default this is the stream's current offset. - - - + + + .. js:function:: FS.write(stream, buffer, offset, length[, position]) - Writes ``length`` bytes from ``buffer``, starting at ``offset``. - + Writes ``length`` bytes from ``buffer``, starting at ``offset``. + By default, writing starts from the stream's current offset, however, a specific offset can be specified with the ``position`` argument. For example: .. code:: javascript @@ -588,45 +588,45 @@ File system API - + .. js:function:: FS.readFile(path, opts) Reads the entire file at ``path`` and returns it as a ``string`` (encoding is ``utf8``), or as a new ``Uint8Array`` buffer (encoding is ``binary``). :param string path: The file to read. :param object opts: - + - **encoding** (*string*) - Defines the encoding used to return the file contents: ``binary`` | ``utf8`` . The default is ``binary`` + Defines the encoding used to return the file contents: ``binary`` | ``utf8`` . The default is ``binary`` - **flags** (*string*) Read flags, as defined in :js:func:`FS.open`. The default is 'r'. - + :returns: The file as a ``string`` or ``Uint8Array`` buffer, depending on the encoding. .. js:function:: FS.writeFile(path, data, opts) - Writes the entire contents of ``data`` to the file at ``path``. - + Writes the entire contents of ``data`` to the file at ``path``. + The value of ``opts`` determines whether ``data`` is treated either as a string (``encoding`` = ``utf8``), or as an ``ArrayBufferView`` (``encoding`` = ``binary``). For example: .. code:: javascript FS.writeFile('file', 'foobar'); var contents = FS.readFile('file', { encoding: ``utf8`` }); - + :param string path: The file to which to write ``data``. :param ArrayBufferView data: The data to write. :param object opts: - + - **encoding** (*string*) - ``binary`` | ``utf8``. The default is ``utf8`` + ``binary`` | ``utf8``. The default is ``utf8`` - **flags** (*string*) Write flags, as defined in :js:func:`FS.open`. The default is 'w'. - + .. js:function:: FS.createLazyFile(parent, name, url, canRead, canWrite) Creates a file that will be loaded lazily on first access from a given URL or local file system path, and returns a reference to it. @@ -639,8 +639,8 @@ File system API FS.createLazyFile('/', 'foo', 'other/page.htm', true, false); FS.createLazyFile('/', 'bar', '/get_file.php?name=baz', true, true); - - + + :param parent: The parent folder, either as a path (e.g. `'/usr/lib'`) or an object previously returned from a `FS.createFolder()` or `FS.createPath()` call. :type parent: string/object :param string name: The name of the new file. @@ -648,13 +648,13 @@ File system API :param bool canRead: Whether the file should have read permissions set from the program's point of view. :param bool canWrite: Whether the file should have write permissions set from the program's point of view. :returns: A reference to the new file. - + .. js:function:: FS.createPreloadedFile(parent, name, url, canRead, canWrite) Preloads a file asynchronously, and uses preload plugins to prepare its content. You should call this in ``preRun``, ``run()`` will be delayed until all preloaded files are ready. This is how the :ref:`preload-file ` option works in *emcc* when ``--use-preload-plugins`` has been specified (if you use this method by itself, you will need to build the program with that option). - + :param parent: The parent folder, either as a path (e.g. **'/usr/lib'**) or an object previously returned from a `FS.createFolder()` or `FS.createPath()` call. :type parent: string/object :param string name: The name of the new file. @@ -673,7 +673,7 @@ Emscripten's file system supports regular files, directories, symlinks, characte .. js:function:: FS.isFile(mode) Tests if the ``mode`` bitmask represents a file. - + :param mode: A bitmask of possible file properties. :returns: ``true`` if the ``mode`` bitmask represents a file. :rtype: bool @@ -701,7 +701,7 @@ Emscripten's file system supports regular files, directories, symlinks, characte Tests if the ``mode`` bitmask represents a character device. - :param mode: A bitmask of possible file properties. + :param mode: A bitmask of possible file properties. :returns: ``true`` if the ``mode`` bitmask represents a character device. :rtype: bool @@ -719,8 +719,8 @@ Emscripten's file system supports regular files, directories, symlinks, characte Tests if the ``mode`` bitmask represents a socket. - :param mode: A bitmask of possible file properties. - :returns: ``true`` if the ``mode`` bitmask represents a socket. + :param mode: A bitmask of possible file properties. + :returns: ``true`` if the ``mode`` bitmask represents a socket. :rtype: bool @@ -733,29 +733,29 @@ Paths Gets the current working directory. :returns: The current working directory. - - + + .. js:function:: FS.lookupPath(path, opts) - Looks up the incoming path and returns an object containing both the resolved path and node. - + Looks up the incoming path and returns an object containing both the resolved path and node. + The options (``opts``) allow you to specify whether the object, its parent component, a symlink, or the item the symlink points to are returned. For example: :: - + var lookup = FS.lookupPath(path, { parent: true }); - + :param string path: The incoming path. :param object opts: Options for the path: - - - **parent** (*bool*) - If true, stop resolving the path once the penultimate component is reached. + + - **parent** (*bool*) + If true, stop resolving the path once the penultimate component is reached. For example, the path ``/foo/bar`` with ``{ parent: true }`` would return an object representing ``/foo``. The default is ``false``. - **follow** (*bool*) - If true, follow the last component if it is a symlink. + If true, follow the last component if it is a symlink. For example, consider a symlink ``/foo/symlink`` that links to ``/foo/notes.txt``. If ``{ follow: true }``, an object representing ``/foo/notes.txt`` would be returned. If ``{ follow: false }``, an object representing the symlink file would be returned. The default is ``false``. :returns: an object with the format: - + .. code-block:: javascript { @@ -768,12 +768,12 @@ Paths .. js:function:: FS.getPath(node) Gets the absolute path to ``node``, accounting for mounts. - + :param node: The current node. :returns: The absolute path to ``node``. .. COMMENT (not rendered): Section below is automated copy and replace text. This is useful where we have boilerplate text. - + .. |note-completeness| replace:: This call exists to provide a more "complete" API mapping for ported code. Values set are effectively ignored. diff --git a/site/source/docs/api_reference/advanced-apis.rst b/site/source/docs/api_reference/advanced-apis.rst index 92e676b0c5406..30e1beca605a2 100644 --- a/site/source/docs/api_reference/advanced-apis.rst +++ b/site/source/docs/api_reference/advanced-apis.rst @@ -16,7 +16,7 @@ This section lists APIs that are not suitable for general use, but which may be settings.js ============ -`settings.js `_ contains default values and options used in various places by the compiler. +`settings.js `_ contains default values and options used in various places by the compiler. .. Warning :: Many **settings.js** options are highly brittle - certain combinations of options, and combinations of certain options used with some source code, can cause Emscripten to fail badly. This is intended for use by "advanced users", and possibly even only people developing Emscripten itself. @@ -32,7 +32,7 @@ The small number of options that developers may have cause to change should be m ./emcc tests/hello_function.cpp -o function.html -s EXPORTED_FUNCTIONS="['_int_sqrt']" - + preamble.js =========== @@ -41,13 +41,13 @@ The following advanced APIs are documented in `preamble.js `_. +This page documents the public C++ APIs provided by `emscripten.h `_. -Emscripten uses existing/familiar APIs where possible (for example: :term:`SDL`). This API provides C++ support for capabilities that are specific to JavaScript or the browser environment, or for which there is no existing API. +Emscripten uses existing/familiar APIs where possible (for example: :term:`SDL`). This API provides C++ support for capabilities that are specific to JavaScript or the browser environment, or for which there is no existing API. .. contents:: Table of Contents :local: @@ -25,34 +25,34 @@ Defines .. c:macro:: EM_ASM(...) Convenient syntax for inline assembly/JavaScript. - + This allows you to declare JavaScript in your C code "inline", which is then executed when your compiled code is run in the browser. For example, the following C code would display two alerts if it was compiled with Emscripten and run in the browser: :: - EM_ASM( alert(‘hai’)); + EM_ASM( alert(‘hai’)); alert(‘bai’)); ) - - .. note:: + + .. note:: - Double-quotes (") cannot be used in the inline assembly/JavaScript. Single-quotes (‘) can be used, as shown above. - Newlines (\\n, \\r etc.) are supported in the inline JavaScript. Note that any platform-specific issues with line endings in normal JavaScript also apply to inline JavaScript declared using ``EM_ASM``. - You can’t access C variables with :c:macro:`EM_ASM`, nor receive a value back. Instead use :c:macro:`EM_ASM_ARGS`, :c:macro:`EM_ASM_INT`, or :c:macro:`EM_ASM_DOUBLE`. - As of ``1.30.4``, ``EM_ASM`` contents appear as normal JS, outside of the compiled code. Previously we had them as a string that was ``eval``ed. The newer approach avoids the overhead of ``eval``, and also allows for better optimization of ``EM_ASM`` contents by things like closure compiler, as their contents are now visible. Note that this means that closure compiler will optimize them as if they were written together with the rest of the codebase, which is a change from before - you may need to use safety quotes in some places (``a['b']`` instead of ``a.b``). - - + + .. c:macro:: EM_ASM_(code, ...) - EM_ASM_ARGS(code, ...) + EM_ASM_ARGS(code, ...) EM_ASM_INT(code, ...) EM_ASM_DOUBLE(code, ...) - EM_ASM_INT_V(code) - EM_ASM_DOUBLE_V(code) - + EM_ASM_INT_V(code) + EM_ASM_DOUBLE_V(code) + Input-output versions of EM_ASM. - + :c:macro:`EM_ASM_` (an extra "_" is added) or :c:macro:`EM_ASM_ARGS` allow values (``int`` or ``double``) to be sent into the code. .. note:: The C preprocessor does not have a full understanding of JavaScript tokens, of course. An issue you might see is that it is not aware of nesting due to ``{`` or ``[``, it is only aware of ``,`` and ``(``. As a result, if you have a JavaScript array ``[1,2,3]`` then you might get an error, but can fix things with parentheses: ``([1,2,3])``. If you also want a return value, :c:macro:`EM_ASM_INT` receives arguments (of ``int`` or ``double`` type) and returns an ``int``; :c:macro:`EM_ASM_DOUBLE` does the same and returns a ``double``. - + Arguments arrive as ``$0``, ``$1`` etc. The output value should be returned: :: int x = EM_ASM_INT({ @@ -61,7 +61,7 @@ Defines }, calc(), otherCalc()); Note the ``{`` and ``}``. - + If you just want to receive an output value (``int`` or ``double``) but not pass any values, you can use :c:macro:`EM_ASM_INT_V` or :c:macro:`EM_ASM_DOUBLE_V`, respectively. @@ -74,38 +74,38 @@ Guide material for the following APIs can be found in :ref:`interacting-with-cod Function pointer types for callbacks ------------------------------------ -The following types are used to define function callback signatures used in a number of functions in this file. +The following types are used to define function callback signatures used in a number of functions in this file. .. c:type:: em_callback_func - General function pointer type for use in callbacks with no parameters. - + General function pointer type for use in callbacks with no parameters. + Defined as: :: - + typedef void (*em_callback_func)(void) - + .. c:type:: em_arg_callback_func - Generic function pointer type for use in callbacks with a single ``void*`` parameter. - - This type is used to define function callbacks that need to pass arbitrary data. For example, :c:func:`emscripten_set_main_loop_arg` sets user-defined data, and passes it to a callback of this type on completion. - - Defined as: :: + Generic function pointer type for use in callbacks with a single ``void*`` parameter. + + This type is used to define function callbacks that need to pass arbitrary data. For example, :c:func:`emscripten_set_main_loop_arg` sets user-defined data, and passes it to a callback of this type on completion. + + Defined as: :: typedef void (*em_arg_callback_func)(void*) - - + + .. c:type:: em_str_callback_func - General function pointer type for use in callbacks with a C string (``const char *``) parameter. - + General function pointer type for use in callbacks with a C string (``const char *``) parameter. + This type is used for function callbacks that need to be passed a C string. For example, it is used in :c:func:`emscripten_async_wget` to pass the name of a file that has been asynchronously loaded. - - Defined as: :: + + Defined as: :: typedef void (*em_str_callback_func)(const char *) - + Functions --------- @@ -115,36 +115,36 @@ Functions Interface to the underlying JavaScript engine. This function will ``eval()`` the given script. Note: If -s NO_DYNAMIC_EXECUTION=1 is set, this function will not be available. :param script: The script to evaluate. - :type script: const char* + :type script: const char* :rtype: void - + .. c:function:: int emscripten_run_script_int(const char *script) Interface to the underlying JavaScript engine. This function will ``eval()`` the given script. Note: If -s NO_DYNAMIC_EXECUTION=1 is set, this function will not be available. :param script: The script to evaluate. - :type script: const char* + :type script: const char* :return: The result of the evaluation, as an integer. :rtype: int - + .. c:function:: char *emscripten_run_script_string(const char *script) Interface to the underlying JavaScript engine. This function will ``eval()`` the given script. Note that this overload uses a single buffer shared between calls. Note: If -s NO_DYNAMIC_EXECUTION=1 is set, this function will not be available. :param script: The script to evaluate. - :type script: const char* + :type script: const char* :return: The result of the evaluation, as a string. :rtype: char* - -.. c:function:: void emscripten_async_run_script(const char *script, int millis) + +.. c:function:: void emscripten_async_run_script(const char *script, int millis) Asynchronously run a script, after a specified amount of time. :param script: The script to evaluate. - :type script: const char* + :type script: const char* :param int millis: The amount of time before the script is run, in milliseconds. :rtype: void @@ -152,77 +152,77 @@ Functions .. c:function:: void emscripten_async_load_script(const char *script, em_callback_func onload, em_callback_func onerror) Asynchronously loads a script from a URL. - + This integrates with the run dependencies system, so your script can call ``addRunDependency`` multiple times, prepare various asynchronous tasks, and call ``removeRunDependency`` on them; when all are complete (or if there were no run dependencies to begin with), ``onload`` is called. An example use for this is to load an asset module, that is, the output of the file packager. :param script: The script to evaluate. - :type script: const char* - :param em_callback_func onload: A callback function, with no parameters, that is executed when the script has fully loaded. + :type script: const char* + :param em_callback_func onload: A callback function, with no parameters, that is executed when the script has fully loaded. :param em_callback_func onerror: A callback function, with no parameters, that is executed if there is an error in loading. :rtype: void - + .. _emscripten-h-browser-execution-environment: - + Browser Execution Environment ============================= Guide material for the following APIs can be found in :ref:`emscripten-runtime-environment`. - + Functions --------- - + .. c:function:: void emscripten_set_main_loop(em_callback_func func, int fps, int simulate_infinite_loop) Set a C function as the main event loop. - + If the main loop function needs to receive user-defined data, use :c:func:`emscripten_set_main_loop_arg` instead. The JavaScript environment will call that function at a specified number of frames per second. Setting 0 or a negative value as the ``fps`` will instead use the browser’s ``requestAnimationFrame`` mechanism to call the main loop function. This is **HIGHLY** recommended if you are doing rendering, as the browser’s ``requestAnimationFrame`` will make sure you render at a proper smooth rate that lines up properly with the browser and monitor. If you do not render at all in your application, then you should pick a specific frame rate that makes sense for your code. - + If ``simulate_infinite_loop`` is true, the function will throw an exception in order to stop execution of the caller. This will lead to the main loop being entered instead of code after the call to :c:func:`emscripten_set_main_loop` being run, which is the closest we can get to simulating an infinite loop (we do something similar in `glutMainLoop `_ in `GLUT `_). If this parameter is ``false``, then the behavior is the same as it was before this parameter was added to the API, which is that execution continues normally. Note that in both cases we do not run global destructors, ``atexit``, etc., since we know the main loop will still be running, but if we do not simulate an infinite loop then the stack will be unwound. That means that if ``simulate_infinite_loop`` is ``false``, and you created an object on the stack, it will be cleaned up before the main loop is called for the first time. - + .. tip:: There can be only *one* main loop function at a time. To change the main loop function, first :c:func:`cancel ` the current loop, and then call this function to set another. - + .. note:: See :c:func:`emscripten_set_main_loop_expected_blockers`, :c:func:`emscripten_pause_main_loop`, :c:func:`emscripten_resume_main_loop` and :c:func:`emscripten_cancel_main_loop` for information about blocking, pausing, and resuming the main loop. .. note:: Calling this function overrides the effect of any previous calls to :c:func:`emscripten_set_main_loop_timing` by applying the timing mode specified by the parameter ``fps``. To specify a different timing mode, call the function :c:func:`emscripten_set_main_loop_timing` after setting up the main loop. - + :param em_callback_func func: C function to set as main event loop. - :param int fps: Number of frames per second that the JavaScript will call the function. Setting ``int <=0`` (recommended) uses the browser’s ``requestAnimationFrame`` mechanism to call the function. - :param int simulate_infinite_loop: If true, this function will throw an exception in order to stop execution of the caller. + :param int fps: Number of frames per second that the JavaScript will call the function. Setting ``int <=0`` (recommended) uses the browser’s ``requestAnimationFrame`` mechanism to call the function. + :param int simulate_infinite_loop: If true, this function will throw an exception in order to stop execution of the caller. .. c:function:: void emscripten_set_main_loop_arg(em_arg_callback_func func, void *arg, int fps, int simulate_infinite_loop) Set a C function as the main event loop, passing it user-defined data. - + .. seealso:: The information in :c:func:`emscripten_set_main_loop` also applies to this function. :param em_arg_callback_func func: C function to set as main event loop. The function signature must have a ``void*`` parameter for passing the ``arg`` value. :param void* arg: User-defined data passed to the main loop function, untouched by the API itself. - :param int fps: Number of frames per second at which the JavaScript will call the function. Setting ``int <=0`` (recommended) uses the browser’s ``requestAnimationFrame`` mechanism to call the function. - :param int simulate_infinite_loop: If true, this function will throw an exception in order to stop execution of the caller. + :param int fps: Number of frames per second at which the JavaScript will call the function. Setting ``int <=0`` (recommended) uses the browser’s ``requestAnimationFrame`` mechanism to call the function. + :param int simulate_infinite_loop: If true, this function will throw an exception in order to stop execution of the caller. + - .. c:function:: void emscripten_push_main_loop_blocker(em_arg_callback_func func, void *arg) void emscripten_push_uncounted_main_loop_blocker(em_arg_callback_func func, void *arg) - + Add a function that **blocks** the main loop. The function is added to the back of a queue of events to be blocked; the main loop will not run until all blockers in the queue complete. - + In the "counted" version, blockers are counted (internally) and ``Module.setStatus`` is called with some text to report progress (``setStatus`` is a general hook that a program can define in order to show processing updates). - + .. note:: - Main loop blockers block the main loop from running, and can be counted to show progress. In contrast, ``emscripten_async_calls`` are not counted, do not block the main loop, and can fire at specific time in the future. - + :param em_arg_callback_func func: The main loop blocker function. The function signature must have a ``void*`` parameter for passing the ``arg`` value. :param void* arg: User-defined arguments to pass to the blocker function. :rtype: void - + .. c:function:: void emscripten_pause_main_loop(void) void emscripten_resume_main_loop(void) @@ -230,16 +230,16 @@ Functions Pause and resume the main loop. Pausing and resuming the main loop is useful if your app needs to perform some synchronous operation, for example to load a file from the network. It might be wrong to run the main loop before that finishes (the original code assumes that), so you can break the code up into asynchronous callbacks, but you must pause the main loop until they complete. - + .. note:: These are fairly low-level functions. :c:func:`emscripten_push_main_loop_blocker` (and friends) provide more convenient alternatives. .. c:function:: void emscripten_cancel_main_loop(void) - Cancels the main event loop. - - See also :c:func:`emscripten_set_main_loop` and :c:func:`emscripten_set_main_loop_arg` for information about setting and using the main loop. + Cancels the main event loop. + + See also :c:func:`emscripten_set_main_loop` and :c:func:`emscripten_set_main_loop_arg` for information about setting and using the main loop. .. c:function:: int emscripten_set_main_loop_timing(int mode, int value) @@ -270,24 +270,24 @@ Functions :type mode: int* :param value: If not null, the used timing value is returned here. :type value: int* - + .. c:function:: void emscripten_set_main_loop_expected_blockers(int num) Sets the number of blockers that are about to be pushed. - + The number is used for reporting the *relative progress* through a set of blockers, after which the main loop will continue. - + For example, a game might have to run 10 blockers before starting a new level. The operation would first set this value as '10' and then push the 10 blockers. When the 3\ :sup:`rd` blocker (say) completes, progress is displayed as 3/10. - + :param int num: The number of blockers that are about to be pushed. - + .. c:function:: void emscripten_async_call(em_arg_callback_func func, void *arg, int millis) - + Call a C function asynchronously, that is, after returning control to the JavaScript event loop. - + This is done by a ``setTimeout``. - + When building natively this becomes a simple direct call, after ``SDL_Delay`` (you must include **SDL.h** for that). If ``millis`` is negative, the browser's ``requestAnimationFrame`` mechanism is used. @@ -301,11 +301,11 @@ Functions Exits the program immediately, but leaves the runtime alive so that you can continue to run code later (so global destructors etc., are not run). Note that the runtime is kept alive automatically when you do an asynchronous operation like :c:func:`emscripten_async_call`, so you don't need to call this function for those cases. - + .. c:function:: void emscripten_force_exit(int status) - Shuts down the runtime and exits (terminates) the program, as if you called ``exit()``. - + Shuts down the runtime and exits (terminates) the program, as if you called ``exit()``. + The difference is that ``emscripten_force_exit`` will shut down the runtime even if you previously called :c:func:`emscripten_exit_with_live_runtime` or otherwise kept the runtime alive. In other words, this method gives you the option to completely shut down the runtime after it was kept alive beyond the completion of ``main()``. :param int status: The same as for the *libc* function `exit() `_. @@ -327,7 +327,7 @@ Functions .. c:function:: void emscripten_set_canvas_size(int width, int height) Resizes the pixel width and height of the ```` element on the Emscripten web page. - + :param int width: New pixel width of canvas element. :param int height: New pixel height of canvas element. @@ -335,7 +335,7 @@ Functions .. c:function:: void emscripten_get_canvas_size(int * width, int * height, int * isFullscreen) Gets the current pixel width and height of the ```` element as well as whether the canvas is fullscreen or not. - + :param int* width: Pixel width of canvas element. :param int* height: New pixel height of canvas element. :param int* isFullscreen: If True (``*int > 0``), ```` is full screen. @@ -346,19 +346,19 @@ Functions Returns the highest-precision representation of the current time that the browser provides. This uses either ``Date.now`` or ``performance.now``. The result is not an absolute time, and is only meaningful in comparison to other calls to this function. - + :rtype: double :return: The current time, in milliseconds (ms). .. c:function:: float emscripten_random(void) Generates a random number in the range 0-1. This maps to ``Math.random()``. - + :rtype: float :return: A random number. - + .. _emscripten-h-asynchronous-file-system-api: Emscripten Asynchronous File System API @@ -371,41 +371,41 @@ Typedefs Function pointer type for the ``onload`` callback of :c:func:`emscripten_async_wget_data` (specific values of the parameters documented in that method). - Defined as: :: + Defined as: :: typedef void (*em_async_wget_onload_func)(void*, void*, int) - + .. c:type:: em_async_wget2_onload_func Function pointer type for the ``onload`` callback of :c:func:`emscripten_async_wget2` (specific values of the parameters documented in that method). - Defined as: :: + Defined as: :: typedef void (*em_async_wget2_onload_func)(void*, const char*) - - + + .. c:type:: em_async_wget2_onstatus_func Function pointer type for the ``onerror`` and ``onprogress`` callbacks of :c:func:`emscripten_async_wget2` (specific values of the parameters documented in that method). - Defined as: :: + Defined as: :: + + typedef void (*em_async_wget2_onstatus_func)(void*, int) + + - typedef void (*em_async_wget2_onstatus_func)(void*, int) - - - .. c:type:: em_async_wget2_data_onload_func Function pointer type for the ``onload`` callback of :c:func:`emscripten_async_wget2_data` (specific values of the parameters documented in that method). - Defined as: :: + Defined as: :: + + typedef void (*em_async_wget2_data_onload_func)(void*, void *, unsigned*) + - typedef void (*em_async_wget2_data_onload_func)(void*, void *, unsigned*) - - .. c:type:: em_async_wget2_data_onerror_func @@ -413,27 +413,27 @@ Typedefs Defined as: :: - typedef void (*em_async_wget2_data_onerror_func)(void*, int, const char*) - + typedef void (*em_async_wget2_data_onerror_func)(void*, int, const char*) + .. c:type:: em_async_wget2_data_onprogress_func Function pointer type for the ``onprogress`` callback of :c:func:`emscripten_async_wget2_data` (specific values of the parameters documented in that method). - Defined as: :: + Defined as: :: typedef void (*em_async_wget2_data_onprogress_func)(void*, int, int) - + .. c:type:: em_run_preload_plugins_data_onload_func Function pointer type for the ``onload`` callback of :c:func:`emscripten_run_preload_plugins_data` (specific values of the parameters documented in that method). - Defined as: :: + Defined as: :: + + typedef void (*em_run_preload_plugins_data_onload_func)(void*, const char*) - typedef void (*em_run_preload_plugins_data_onload_func)(void*, const char*) - Functions --------- @@ -443,7 +443,7 @@ Functions Load file from url in *synchronously*. For the asynchronous version, see the :c:func:`emscripten_async_wget`. In addition to fetching the URL from the network, preload plugins are executed so that the data is usable in ``IMG_Load`` and so forth (we synchronously do the work to make the browser decode the image or audio etc.). - + This function is blocking; it won't return until all operations are finished. You can then open and read the file if it succeeded. To use this function, you will need to compile your application with the linker flag ``-s ASYNCIFY=1`` @@ -451,154 +451,154 @@ Functions :param const char* url: The URL to load. :param const char* file: The name of the file created and loaded from the URL. If the file already exists it will be overwritten. If the destination directory for the file does not exist on the filesystem, it will be created. A relative pathname may be passed, which will be interpreted relative to the current working directory at the time of the call to this function. - + .. c:function:: void emscripten_async_wget(const char* url, const char* file, em_str_callback_func onload, em_str_callback_func onerror) - - Loads a file from a URL asynchronously. + + Loads a file from a URL asynchronously. In addition to fetching the URL from the network, preload plugins are executed so that the data is usable in ``IMG_Load`` and so forth (we asynchronously do the work to make the browser decode the image or audio etc.). When the file is ready the ``onload`` callback will be called. If any error occurs ``onerror`` will be called. The callbacks are called with the file as their argument. - + :param const char* url: The URL to load. :param const char* file: The name of the file created and loaded from the URL. If the file already exists it will be overwritten. If the destination directory for the file does not exist on the filesystem, it will be created. A relative pathname may be passed, which will be interpreted relative to the current working directory at the time of the call to this function. - :param em_str_callback_func onload: Callback on successful load of the file. The callback function parameter value is: - + :param em_str_callback_func onload: Callback on successful load of the file. The callback function parameter value is: + - *(const char*)* : The name of the ``file`` that was loaded from the URL. - - :param em_str_callback_func onerror: Callback in the event of failure. The callback function parameter value is: - + + :param em_str_callback_func onerror: Callback in the event of failure. The callback function parameter value is: + - *(const char*)* : The name of the ``file`` that failed to load from the URL. - - - + + + .. c:function:: void emscripten_async_wget_data(const char* url, void *arg, em_async_wget_onload_func onload, em_arg_callback_func onerror) - - Loads a buffer from a URL asynchronously. - - This is the "data" version of :c:func:`emscripten_async_wget`. + + Loads a buffer from a URL asynchronously. + + This is the "data" version of :c:func:`emscripten_async_wget`. Instead of writing to a file, this function writes to a buffer directly in memory. This avoids the overhead of using the emulated file system; note however that since files are not used, it cannot run preload plugins to set things up for ``IMG_Load`` and so forth (``IMG_Load`` etc. work on files). When the file is ready then the ``onload`` callback will be called. If any error occurred ``onerror`` will be called. - + :param url: The URL of the file to load. - :type url: const char* + :type url: const char* :param void* arg: User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call. - :param em_async_wget_onload_func onload: Callback on successful load of the URL into the buffer. The callback function parameter values are: - + :param em_async_wget_onload_func onload: Callback on successful load of the URL into the buffer. The callback function parameter values are: + - *(void*)* : Equal to ``arg`` (user defined data). - *(void*)* : A pointer to a buffer with the data. Note that, as with the worker API, the data buffer only lives during the callback; it must be used or copied during that time. - - *(int)* : The size of the buffer, in bytes. - - :param em_arg_callback_func onerror: Callback in the event of failure. The callback function parameter values are: - + - *(int)* : The size of the buffer, in bytes. + + :param em_arg_callback_func onerror: Callback in the event of failure. The callback function parameter values are: + - *(void*)* : Equal to ``arg`` (user defined data). .. c:function:: int emscripten_async_wget2(const char* url, const char* file, const char* requesttype, const char* param, void *arg, em_async_wget2_onload_func onload, em_async_wget2_onstatus_func onerror, em_async_wget2_onstatus_func onprogress) - - Loads a file from a URL asynchronously. - - This is an **experimental** "more feature-complete" version of :c:func:`emscripten_async_wget`. - + + Loads a file from a URL asynchronously. + + This is an **experimental** "more feature-complete" version of :c:func:`emscripten_async_wget`. + In addition to fetching the URL from the network, preload plugins are executed so that the data is usable in ``IMG_Load`` and so forth (we asynchronously do the work to make the browser decode the image, audio, etc.). When the file is ready the ``onload`` callback will be called with the object pointers given in ``arg`` and ``file``. During the download the ``onprogress`` callback is called. - + :param url: The URL of the file to load. - :type url: const char* + :type url: const char* :param file: The name of the file created and loaded from the URL. If the file already exists it will be overwritten. If the destination directory for the file does not exist on the filesystem, it will be created. A relative pathname may be passed, which will be interpreted relative to the current working directory at the time of the call to this function. - :type file: const char* + :type file: const char* :param requesttype: 'GET' or 'POST'. - :type requesttype: const char* + :type requesttype: const char* :param param: Request parameters for POST requests (see ``requesttype``). The parameters are specified in the same way as they would be in the URL for an equivalent GET request: e.g. ``key=value&key2=value2``. :type param: const char* :param void* arg: User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call. - :param em_async_wget2_onload_func onload: Callback on successful load of the file. The callback function parameter values are: - + :param em_async_wget2_onload_func onload: Callback on successful load of the file. The callback function parameter values are: + - *(void*)* : Equal to ``arg`` (user defined data). - *(const char*)* : The ``file`` passed to the original call. - - :param em_async_wget2_onstatus_func onerror: Callback in the event of failure. The callback function parameter values are: - + + :param em_async_wget2_onstatus_func onerror: Callback in the event of failure. The callback function parameter values are: + - *(void*)* : Equal to ``arg`` (user defined data). - *(int)* : The HTTP status code. - - :param em_async_wget2_onstatus_func onprogress: Callback during load of the file. The callback function parameter values are: - + + :param em_async_wget2_onstatus_func onprogress: Callback during load of the file. The callback function parameter values are: + - *(void*)* : Equal to ``arg`` (user defined data). - *(int)* : The progress (percentage completed). :returns: A handle to request (``int``) that can be used to :c:func:`abort ` the request. - - + + .. c:function:: int emscripten_async_wget2_data(const char* url, const char* requesttype, const char* param, void *arg, int free, em_async_wget2_data_onload_func onload, em_async_wget2_data_onerror_func onerror, em_async_wget2_data_onprogress_func onprogress) - - Loads a buffer from a URL asynchronously. - - This is the "data" version of :c:func:`emscripten_async_wget2`. It is an **experimental** "more feature complete" version of :c:func:`emscripten_async_wget_data`. + + Loads a buffer from a URL asynchronously. + + This is the "data" version of :c:func:`emscripten_async_wget2`. It is an **experimental** "more feature complete" version of :c:func:`emscripten_async_wget_data`. Instead of writing to a file, this function writes to a buffer directly in memory. This avoids the overhead of using the emulated file system; note however that since files are not used, it cannot run preload plugins to set things up for ``IMG_Load`` and so forth (``IMG_Load`` etc. work on files). - + When the file is ready the ``onload`` callback will be called with the object pointers given in ``arg``, a pointer to the buffer in memory, and an unsigned integer containing the size of the buffer. During the download the ``onprogress`` callback is called with progress information. If an error occurs, ``onerror`` will be called with the HTTP status code and a string containing the status description. - + :param url: The URL of the file to load. :type url: const char* - :param requesttype: 'GET' or 'POST'. - :type requesttype: const char* + :param requesttype: 'GET' or 'POST'. + :type requesttype: const char* :param param: Request parameters for POST requests (see ``requesttype``). The parameters are specified in the same way as they would be in the URL for an equivalent GET request: e.g. ``key=value&key2=value2``. :type param: const char* :param void* arg: User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call. :param int free: Tells the runtime whether to free the returned buffer after ``onload`` is complete. If ``false`` freeing the buffer is the receiver's responsibility. :type free: int :param em_async_wget2_data_onload_func onload: Callback on successful load of the file. The callback function parameter values are: - + - *(void*)* : Equal to ``arg`` (user defined data). - - *(void*)* : A pointer to the buffer in memory. + - *(void*)* : A pointer to the buffer in memory. - *(unsigned)* : The size of the buffer (in bytes). - - :param em_async_wget2_data_onerror_func onerror: Callback in the event of failure. The callback function parameter values are: - + + :param em_async_wget2_data_onerror_func onerror: Callback in the event of failure. The callback function parameter values are: + - *(void*)* : Equal to ``arg`` (user defined data). - - *(int)* : The HTTP error code. + - *(int)* : The HTTP error code. - *(const char*)* : A string with the status description. - - :param em_async_wget2_data_onprogress_func onprogress: Callback called (regularly) during load of the file to update progress. The callback function parameter values are: - + + :param em_async_wget2_data_onprogress_func onprogress: Callback called (regularly) during load of the file to update progress. The callback function parameter values are: + - *(void*)* : Equal to ``arg`` (user defined data). - - *(int)* : The number of bytes loaded. + - *(int)* : The number of bytes loaded. - *(int)* : The total size of the data in bytes, or zero if the size is unavailable. - :returns: A handle to request (``int``) that can be used to :c:func:`abort ` the request. + :returns: A handle to request (``int``) that can be used to :c:func:`abort ` the request. .. c:function:: void emscripten_async_wget2_abort(int handle) Abort an asynchronous request raised using :c:func:`emscripten_async_wget2` or :c:func:`emscripten_async_wget2_data`. - + :param int handle: A handle to request to be aborted. .. c:function:: void emscripten_run_preload_plugins_data(char* data, int size, const char *suffix, void *arg, em_run_preload_plugins_data_onload_func onload, em_arg_callback_func onerror) - - Runs preload plugins on a buffer of data asynchronously. This is a "data" version of :c:func:`emscripten_run_preload_plugins`, which receives raw data as input instead of a filename (this can prevent the need to write data to a file first). - + + Runs preload plugins on a buffer of data asynchronously. This is a "data" version of :c:func:`emscripten_run_preload_plugins`, which receives raw data as input instead of a filename (this can prevent the need to write data to a file first). + When file is loaded then the ``onload`` callback will be called. If any error occurs ``onerror`` will be called. - + ``onload`` also receives a second parameter, which is a 'fake' filename which you can pass into ``IMG_Load`` (it is not an actual file, but it identifies this image for ``IMG_Load`` to be able to process it). Note that the user of this API is responsible for ``free()`` ing the memory allocated for the fake filename. :param char* data: The buffer of data to process. :param suffix: The file suffix, e.g. 'png' or 'jpg'. - :type suffix: const char* + :type suffix: const char* :param void* arg: User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call. - :param em_run_preload_plugins_data_onload_func onload: Callback on successful processing of the data. The callback function parameter values are: - + :param em_run_preload_plugins_data_onload_func onload: Callback on successful processing of the data. The callback function parameter values are: + - *(void*)* : Equal to ``arg`` (user defined data). - *(const char*)* : A 'fake' filename which you can pass into ``IMG_Load``. See above for more information. - + :param em_arg_callback_func onerror: Callback in the event of failure. The callback function parameter value is: - + - *(void*)* : Equal to ``arg`` (user defined data). @@ -608,66 +608,66 @@ Emscripten Asynchronous IndexedDB API IndexedDB is a browser API that lets you store data persistently, that is, you can save data there and load it later when the user re-visits the web page. IDBFS provides one way to use IndexedDB, through the Emscripten filesystem layer. The ``emscripten_idb_*`` methods listed here provide an alternative API, directly to IndexedDB, thereby avoiding the overhead of the filesystem layer. .. c:function:: void emscripten_idb_async_load(const char *db_name, const char *file_id, void* arg, em_async_wget_onload_func onload, em_arg_callback_func onerror) - + Loads data from local IndexedDB storage asynchronously. This allows use of persistent data, without the overhead of the filesystem layer. - + When the data is ready then the ``onload`` callback will be called. If any error occurred ``onerror`` will be called. - + :param db_name: The IndexedDB database from which to load. :param file_id: The identifier of the data to load. :param void* arg: User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call. - :param em_async_wget_onload_func onload: Callback on successful load of the URL into the buffer. The callback function parameter values are: - + :param em_async_wget_onload_func onload: Callback on successful load of the URL into the buffer. The callback function parameter values are: + - *(void*)* : Equal to ``arg`` (user defined data). - *(void*)* : A pointer to a buffer with the data. Note that, as with the worker API, the data buffer only lives during the callback; it must be used or copied during that time. - - *(int)* : The size of the buffer, in bytes. - - :param em_arg_callback_func onerror: Callback in the event of failure. The callback function parameter values are: - + - *(int)* : The size of the buffer, in bytes. + + :param em_arg_callback_func onerror: Callback in the event of failure. The callback function parameter values are: + - *(void*)* : Equal to ``arg`` (user defined data). .. c:function:: void emscripten_idb_async_store(const char *db_name, const char *file_id, void* ptr, int num, void* arg, em_arg_callback_func onstore, em_arg_callback_func onerror); - + Stores data to local IndexedDB storage asynchronously. This allows use of persistent data, without the overhead of the filesystem layer. - + When the data has been stored then the ``onstore`` callback will be called. If any error occurred ``onerror`` will be called. - + :param db_name: The IndexedDB database from which to load. :param file_id: The identifier of the data to load. :param ptr: A pointer to the data to store. :param num: How many bytes to store. :param void* arg: User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call. :param em_arg_callback_func onstore: Callback on successful store of the data buffer to the URL. The callback function parameter values are: - + - *(void*)* : Equal to ``arg`` (user defined data). - - :param em_arg_callback_func onerror: Callback in the event of failure. The callback function parameter values are: - + + :param em_arg_callback_func onerror: Callback in the event of failure. The callback function parameter values are: + - *(void*)* : Equal to ``arg`` (user defined data). - + .. c:function:: void emscripten_idb_async_delete(const char *db_name, const char *file_id, void* arg, em_arg_callback_func ondelete, em_arg_callback_func onerror) - + Deletes data from local IndexedDB storage asynchronously. - + When the data has been deleted then the ``ondelete`` callback will be called. If any error occurred ``onerror`` will be called. - + :param db_name: The IndexedDB database. :param file_id: The identifier of the data. :param void* arg: User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call. :param em_arg_callback_func ondelete: Callback on successful delete - *(void*)* : Equal to ``arg`` (user defined data). - - :param em_arg_callback_func onerror: Callback in the event of failure. The callback function parameter values are: - + + :param em_arg_callback_func onerror: Callback in the event of failure. The callback function parameter values are: + - *(void*)* : Equal to ``arg`` (user defined data). .. c:function:: void emscripten_idb_async_exists(const char *db_name, const char *file_id, void* arg, em_idb_exists_func oncheck, em_arg_callback_func onerror) - + Checks if data with a certain ID exists in the local IndexedDB storage asynchronously. - + When the data has been checked then the ``oncheck`` callback will be called. If any error occurred ``onerror`` will be called. - + :param db_name: The IndexedDB database. :param file_id: The identifier of the data. :param void* arg: User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call. @@ -675,29 +675,29 @@ Emscripten Asynchronous IndexedDB API - *(void*)* : Equal to ``arg`` (user defined data). - *int* : Whether the file exists or not. - - :param em_arg_callback_func onerror: Callback in the event of failure. The callback function parameter values are: - + + :param em_arg_callback_func onerror: Callback in the event of failure. The callback function parameter values are: + - *(void*)* : Equal to ``arg`` (user defined data). .. c:function:: int emscripten_run_preload_plugins(const char* file, em_str_callback_func onload, em_str_callback_func onerror) - - Runs preload plugins on a file asynchronously. It works on file data already present and performs any required asynchronous operations available as preload plugins, such as decoding images for use in ``IMG_Load``, or decoding audio for use in ``Mix_LoadWAV``. - + + Runs preload plugins on a file asynchronously. It works on file data already present and performs any required asynchronous operations available as preload plugins, such as decoding images for use in ``IMG_Load``, or decoding audio for use in ``Mix_LoadWAV``. + Once the operations are complete, the ``onload`` callback will be called. If any error occurs ``onerror`` will be called. The callbacks are called with the file as their argument. :param file: The name of the file to process. - :type file: const char* + :type file: const char* :param em_str_callback_func onload: Callback on successful processing of the file. The callback function parameter value is: - + - *(const char*)* : The name of the ``file`` that was processed. - - :param em_str_callback_func onerror: Callback in the event of failure. The callback function parameter value is: - + + :param em_str_callback_func onerror: Callback in the event of failure. The callback function parameter value is: + - *(const char*)* : The name of the ``file`` for which the operation failed. - + :return: 0 if successful, -1 if the file does not exist :rtype: int @@ -707,18 +707,18 @@ Compiling ================ .. c:macro:: EMSCRIPTEN_KEEPALIVE - + Forces LLVM to not dead-code-eliminate a function. - - This also exports the function, as if you added it to :ref:`EXPORTED_FUNCTIONS `. - + + This also exports the function, as if you added it to :ref:`EXPORTED_FUNCTIONS `. + For example: :: void EMSCRIPTEN_KEEPALIVE my_function() { printf("I am being kept alive\n"); } - + Worker API ========== @@ -728,7 +728,7 @@ Typedefs .. c:var:: int worker_handle A wrapper around web workers that lets you create workers and communicate with them. - + Note that the current API is mainly focused on a main thread that sends jobs to workers and waits for responses, i.e., in an asymmetrical manner, there is no current API to send a message without being asked for it from a worker to the main thread. @@ -737,53 +737,53 @@ Typedefs Function pointer type for the callback from :c:func:`emscripten_call_worker` (specific values of the parameters documented in that method). - Defined as: :: + Defined as: :: + + typedef void (*em_worker_callback_func)(char*, int, void*) - typedef void (*em_worker_callback_func)(char*, int, void*) - Functions --------- .. c:function:: worker_handle emscripten_create_worker(const char * url) - + Creates a worker. - + A worker must be compiled separately from the main program, and with the ``BUILD_AS_WORKER`` flag set to 1. :param url: The URL of the worker script. - :type url: const char* + :type url: const char* :return: A handle to the newly created worker. :rtype: worker_handle - - + + .. c:function:: void emscripten_destroy_worker(worker_handle worker) Destroys a worker. See :c:func:`emscripten_create_worker` - + :param worker_handle worker: A handle to the worker to be destroyed. - + .. c:function:: void emscripten_call_worker(worker_handle worker, const char *funcname, char *data, int size, em_worker_callback_func callback, void *arg) Asynchronously calls a worker. - + The worker function will be called with two parameters: a data pointer, and a size. The data block defined by the pointer and size exists only during the callback: **it cannot be relied upon afterwards**. If you need to keep some of that information outside the callback, then it needs to be copied to a safe location. - + The called worker function can return data, by calling :c:func:`emscripten_worker_respond`. When the worker is called, if a callback was given it will be called with three arguments: a data pointer, a size, and an argument that was provided when calling :c:func:`emscripten_call_worker` (to more easily associate callbacks to calls). The data block defined by the data pointer and size behave like the data block in the worker function — it exists only during the callback. - + :param worker_handle worker: A handle to the worker to be called. - :param funcname: The name of the function in the worker. The function must be a C function (so no C++ name mangling), and must be exported (:ref:`EXPORTED_FUNCTIONS `). + :param funcname: The name of the function in the worker. The function must be a C function (so no C++ name mangling), and must be exported (:ref:`EXPORTED_FUNCTIONS `). :type funcname: const char* :param char* data: The address of a block of memory to copy over. :param int size: The size of the block of memory. - :param em_worker_callback_func callback: Worker callback with the response. This can be ``null``. The callback function parameter values are: - + :param em_worker_callback_func callback: Worker callback with the response. This can be ``null``. The callback function parameter values are: + - *(char*)* : The ``data`` pointer provided in :c:func:`emscripten_call_worker`. - - *(int)* : The ``size`` of the block of data. + - *(int)* : The ``size`` of the block of data. - *(void*)* : Equal to ``arg`` (user defined data). :param void* arg: An argument (user data) to be passed to the callback @@ -792,7 +792,7 @@ Functions void emscripten_worker_respond_provisionally(char *data, int size) Sends a response when in a worker call (that is, when called by the main thread using :c:func:`emscripten_call_worker`). - + Both functions post a message back to the thread which called the worker. The :c:func:`emscripten_worker_respond_provisionally` variant can be invoked multiple times, which will queue up messages to be posted to the worker’s creator. Eventually, the _respond variant must be invoked, which will disallow further messages and free framework resources previously allocated for this worker call. .. note:: Calling the provisional version is optional, but you must call the non-provisional version to avoid leaks. @@ -800,18 +800,18 @@ Functions :param char* data: The message to be posted. :param int size: The size of the message, in bytes. - + .. c:function:: int emscripten_get_worker_queue_size(worker_handle worker) - Checks how many responses are being waited for from a worker. - + Checks how many responses are being waited for from a worker. + This only counts calls to :c:func:`emscripten_call_worker` that had a callback (calls with null callbacks are ignored), and where the response has not yet been received. It is a simple way to check on the status of the worker to see how busy it is, and do basic decisions about throttling. - + :param worker_handle worker: The handle to the relevant worker. :return: The number of responses waited on from a worker. :rtype: int - + Logging utilities ================= @@ -828,7 +828,7 @@ Defines .. c:macro:: EM_LOG_ERROR - If specified, prints an error message. If neither :c:data:`EM_LOG_WARN` or :c:data:`EM_LOG_ERROR` is specified, an info message is printed. :c:data:`EM_LOG_WARN` and :c:data:`EM_LOG_ERROR` are mutually exclusive. + If specified, prints an error message. If neither :c:data:`EM_LOG_WARN` or :c:data:`EM_LOG_ERROR` is specified, an info message is printed. :c:data:`EM_LOG_WARN` and :c:data:`EM_LOG_ERROR` are mutually exclusive. .. c:macro:: EM_LOG_C_STACK @@ -836,11 +836,11 @@ Defines .. c:macro:: EM_LOG_JS_STACK - If specified, prints a call stack that contains file names referring to lines in the built .js/.html file along with the message. The flags :c:data:`EM_LOG_C_STACK` and :c:data:`EM_LOG_JS_STACK` can be combined to output both untranslated and translated file and line information. - + If specified, prints a call stack that contains file names referring to lines in the built .js/.html file along with the message. The flags :c:data:`EM_LOG_C_STACK` and :c:data:`EM_LOG_JS_STACK` can be combined to output both untranslated and translated file and line information. + .. c:macro:: EM_LOG_DEMANGLE - If specified, C/C++ function names are de-mangled before printing. Otherwise, the mangled post-compilation JavaScript function names are displayed. + If specified, C/C++ function names are de-mangled before printing. Otherwise, the mangled post-compilation JavaScript function names are displayed. .. c:macro:: EM_LOG_NO_PATHS @@ -849,17 +849,17 @@ Defines .. c:macro:: EM_LOG_FUNC_PARAMS If specified, prints out the actual values of the parameters the functions were invoked with. - + Functions --------- .. c:function:: int emscripten_get_compiler_setting(const char *name) - Returns the value of a compiler setting. - + Returns the value of a compiler setting. + For example, to return the integer representing the value of ``PRECISE_F32`` during compilation: :: - + emscripten_get_compiler_setting("PRECISE_F32") For values containing anything other than an integer, a string is returned (you will need to cast the ``int`` return value to a ``char*``). @@ -867,15 +867,15 @@ Functions Some useful things this can do is provide the version of Emscripten (“EMSCRIPTEN_VERSION”), the optimization level (“OPT_LEVEL”), debug level (“DEBUG_LEVEL”), etc. For this command to work, you must build with the following compiler option (as we do not want to increase the build size with this metadata): :: - + -s RETAIN_COMPILER_SETTINGS=1 :param name: The compiler setting to return. :type name: const char* :returns: The value of the specified setting. Note that for values other than an integer, a string is returned (cast the ``int`` return value to a ``char*``). - :rtype: int + :rtype: int + - .. c:function:: void emscripten_debugger() Emits ``debugger``. @@ -894,7 +894,7 @@ Functions .. c:function:: int emscripten_get_callstack(int flags, char *out, int maxbytes) Programmatically obtains the current callstack. - + To query the amount of bytes needed for a callstack without writing it, pass 0 to ``out`` and ``maxbytes``, in which case the function will return the number of bytes (including the terminating zero) that will be needed to hold the full callstack. Note that this might be fully accurate since subsequent calls will carry different line numbers, so it is best to allocate a few bytes extra to be safe. :param int flags: A binary OR of items from the list of :c:data:`EM_LOG_xxx ` flags that specify printing options. The flags :c:data:`EM_LOG_CONSOLE`, :c:data:`EM_LOG_WARN` and :c:data:`EM_LOG_ERROR` do not apply in this function and are ignored. @@ -907,8 +907,8 @@ Functions .. c:function:: char *emscripten_get_preloaded_image_data(const char *path, int *w, int *h) Gets preloaded image data and the size of the image. - - The function returns pointer to loaded image or NULL — the pointer should be ``free()``'d. The width/height of the image are written to the ``w`` and ``h`` parameters if the data is valid. + + The function returns pointer to loaded image or NULL — the pointer should be ``free()``'d. The width/height of the image are written to the ``w`` and ``h`` parameters if the data is valid. :param path: Full path/filename to the file containing the preloaded image. :type: const char* @@ -937,7 +937,7 @@ Functions :param char* to: A pre-allocated buffer of sufficient size, or NULL if no output is requested (useful to get the necessary size). :param signed max: The maximum number of bytes that can be written to the output pointer 'to' (including the null terminator). :rtype: The number of necessary bytes, not including the null terminator (actually written, if ``to`` is not NULL). - + .. _emscripten-api-reference-sockets: Socket event registration @@ -949,7 +949,7 @@ Only a single callback function may be registered to handle any given event, so The ``userData`` pointer allows arbitrary data specified during event registration to be passed to the callback, this is particularly useful for passing ``this`` pointers around in Object Oriented code. -In addition to being able to register network callbacks from C it is also possible for native JavaScript code to directly use the underlying mechanism used to implement the callback registration. For example, the following code shows simple logging callbacks that are registered by default when ``SOCKET_DEBUG`` is enabled: +In addition to being able to register network callbacks from C it is also possible for native JavaScript code to directly use the underlying mechanism used to implement the callback registration. For example, the following code shows simple logging callbacks that are registered by default when ``SOCKET_DEBUG`` is enabled: .. code-block:: javascript @@ -975,10 +975,10 @@ Callback functions .. code-block:: cpp typedef void (*em_socket_callback)(int fd, void *userData); - + :param int fd: The file descriptor of the socket that triggered the callback. :param void* userData: The ``userData`` originally passed to the event registration function. - + .. c:type:: em_socket_error_callback @@ -987,7 +987,7 @@ Callback functions .. code-block:: cpp typedef void (*em_socket_error_callback)(int fd, int err, const char* msg, void *userData); - + :param int fd: The file descriptor of the socket that triggered the callback. :param int err: The code for the error that occurred. :param int msg: The message for the error that occurred. @@ -1000,10 +1000,10 @@ Functions .. c:function:: void emscripten_set_socket_error_callback(void *userData, em_socket_error_callback callback) - Triggered by a ``WebSocket`` error. - + Triggered by a ``WebSocket`` error. + See :ref:`emscripten-api-reference-sockets` for more information. - + :param void* userData: Arbitrary user data to be passed to the callback. :param em_socket_error_callback callback: Pointer to a callback function. The callback returns a file descriptor, error code and message, and the arbitrary ``userData`` passed to this function. @@ -1013,53 +1013,53 @@ Functions Triggered when the ``WebSocket`` has opened. See :ref:`emscripten-api-reference-sockets` for more information. - + :param void* userData: Arbitrary user data to be passed to the callback. :param em_socket_callback callback: Pointer to a callback function. The callback returns a file descriptor and the arbitrary ``userData`` passed to this function. - + .. c:function:: void emscripten_set_socket_listen_callback(void *userData, em_socket_callback callback) Triggered when ``listen`` has been called (synthetic event). See :ref:`emscripten-api-reference-sockets` for more information. - + :param void* userData: Arbitrary user data to be passed to the callback. :param em_socket_callback callback: Pointer to a callback function. The callback returns a file descriptor and the arbitrary ``userData`` passed to this function. - + .. c:function:: void emscripten_set_socket_connection_callback(void *userData, em_socket_callback callback) Triggered when the connection has been established. See :ref:`emscripten-api-reference-sockets` for more information. - + :param void* userData: Arbitrary user data to be passed to the callback. :param em_socket_callback callback: Pointer to a callback function. The callback returns a file descriptor and the arbitrary ``userData`` passed to this function. - + .. c:function:: void emscripten_set_socket_message_callback(void *userData, em_socket_callback callback) Triggered when data is available to be read from the socket. See :ref:`emscripten-api-reference-sockets` for more information. - + :param void* userData: Arbitrary user data to be passed to the callback. :param em_socket_callback callback: Pointer to a callback function. The callback returns a file descriptor and the arbitrary ``userData`` passed to this function. - - + + .. c:function:: void emscripten_set_socket_close_callback(void *userData, em_socket_callback callback) Triggered when the ``WebSocket`` has closed. See :ref:`emscripten-api-reference-sockets` for more information. - + :param void* userData: Arbitrary user data to be passed to the callback. :param em_socket_callback callback: Pointer to a callback function. The callback returns a file descriptor and the arbitrary ``userData`` passed to this function. - + Unaligned types =============== @@ -1075,10 +1075,10 @@ Typedefs emscripten_align2_double emscripten_align1_double - Unaligned types. These may be used to force LLVM to emit unaligned loads/stores in places in your code where :ref:`SAFE_HEAP ` found an unaligned operation. - + Unaligned types. These may be used to force LLVM to emit unaligned loads/stores in places in your code where :ref:`SAFE_HEAP ` found an unaligned operation. + For usage examples see `tests/core/test_set_align.c `_. - + .. note:: It is better to avoid unaligned operations, but if you are reading from a packed stream of bytes or such, these types may be useful! @@ -1154,7 +1154,7 @@ IndexedDB :param pexists: An out parameter that will be filled with a non-zero value if the file exists in that database. :param perror: An out parameter that will be filled with a non-zero value if an error occurred. - + Asyncify functions ================== @@ -1187,5 +1187,5 @@ Functions .. c:function:: void emscripten_yield(void) This function should only be called in a coroutine created by `emscripten_coroutine_create`, when it called, the coroutine is paused and the caller will continue. - + diff --git a/site/source/docs/api_reference/fetch.rst b/site/source/docs/api_reference/fetch.rst index 645f67beb4454..0bc267b81b50e 100644 --- a/site/source/docs/api_reference/fetch.rst +++ b/site/source/docs/api_reference/fetch.rst @@ -142,14 +142,14 @@ All types of Emscripten Fetch API operations (XHRs, IndexedDB accesses) can be p printf("Finished downloading %llu bytes from URL %s.\n", fetch->numBytes, fetch->url); // The data is now available at fetch->data[0] through fetch->data[fetch->numBytes-1]; } else { - printf("Downloading %s failed, HTTP failure status code: %d.\n", fetch->url, fetch->status); + printf("Downloading %s failed, HTTP failure status code: %d.\n", fetch->url, fetch->status); } emscripten_fetch_close(fetch); } In the above code sample, the success and failure callback functions are not used. However, if specified, they will be synchronously called before emscripten_fetch() returns. -.. note:: +.. note:: Synchronous Emscripten Fetch operations are subject to a number of restrictions, depending on which Emscripten build mode (linker flags) is used: @@ -183,14 +183,14 @@ Emscripten Fetch operations can also run in a third mode, called a *waitable* fe printf("Finished downloading %llu bytes from URL %s.\n", fetch->numBytes, fetch->url); // The data is now available at fetch->data[0] through fetch->data[fetch->numBytes-1]; } else { - printf("Downloading %s failed, HTTP failure status code: %d.\n", fetch->url, fetch->status); + printf("Downloading %s failed, HTTP failure status code: %d.\n", fetch->url, fetch->status); } emscripten_fetch_close(fetch); } Waitable fetches allow interleaving multiple tasks in one thread so that the issuing thread can perform some other work until the fetch completes. -.. note:: +.. note:: Waitable fetches are available only in certain build modes: @@ -249,7 +249,7 @@ If the application does not need random seek access to the file, but is able to void downloadProgress(emscripten_fetch_t *fetch) { printf("Downloading %s.. %.2f%%s complete. HTTP readyState: %d. HTTP status: %d.\n" - "HTTP statusText: %s. Received chunk [%llu, %llu[\n", + "HTTP statusText: %s. Received chunk [%llu, %llu[\n", fetch->url, fetch->totalBytes > 0 ? (fetch->dataOffset + fetch->numBytes) * 100.0 / fetch->totalBytes : (fetch->dataOffset + fetch->numBytes), fetch->totalBytes > 0 ? "%" : " bytes", fetch->readyState, fetch->status, fetch->statusText, diff --git a/site/source/docs/api_reference/html5.h.rst b/site/source/docs/api_reference/html5.h.rst index 4a308ef6384f9..bf1d90409f8fd 100644 --- a/site/source/docs/api_reference/html5.h.rst +++ b/site/source/docs/api_reference/html5.h.rst @@ -4,13 +4,13 @@ html5.h ======== -The C++ APIs in `html5.h `_ define the Emscripten low-level glue bindings to interact with HTML5 events from native code. +The C++ APIs in `html5.h `_ define the Emscripten low-level glue bindings to interact with HTML5 events from native code. .. tip:: The C++ APIs map closely to their :ref:`equivalent HTML5 JavaScript APIs `. The HTML5 specifications listed below provide additional detailed reference "over and above" the information provided in this document. In addition, the :ref:`test-example-code-html5-api` can be reviewed to see how the code is used. -.. _specifications-html5-api: +.. _specifications-html5-api: The HTML5 specifications for APIs that are mapped by **html5.h** include: @@ -32,11 +32,11 @@ The HTML5 specifications for APIs that are mapped by **html5.h** include: .. contents:: Table of Contents :local: :depth: 1 - + How to use this API =================== - -Most of these APIs use an event-based architecture; functionality is accessed by registering a callback function that will be called when the event occurs. + +Most of these APIs use an event-based architecture; functionality is accessed by registering a callback function that will be called when the event occurs. .. note:: The Gamepad API is currently an exception, as only a polling API is available. For some APIs, both an event-based and a polling-based model are exposed. @@ -45,7 +45,7 @@ Most of these APIs use an event-based architecture; functionality is accessed by Registration functions ---------------------- -The typical format of registration functions is as follows (some methods may omit various parameters): +The typical format of registration functions is as follows (some methods may omit various parameters): .. code-block:: cpp @@ -57,8 +57,8 @@ The typical format of registration functions is as follows (some methods may omi ); -.. _target-parameter-html5-api: - +.. _target-parameter-html5-api: + The ``target`` parameter is the ID of the HTML element to which the callback registration is to be applied. This field has the following special meanings: - ``0`` or ``NULL``: A default element is chosen automatically based on the event type, which should be reasonable most of the time. @@ -68,17 +68,17 @@ The ``target`` parameter is the ID of the HTML element to which the callback reg - ``#canvas``: The event listener is applied to the Emscripten default WebGL canvas element. - Any other string without a leading hash "#" sign: The event listener is applied to the element on the page with the given ID. -.. _userdata-parameter-html5-api: - +.. _userdata-parameter-html5-api: + The ``userData`` parameter is a user-defined value that is passed (unchanged) to the registered event callback. This can be used to, for example, pass a pointer to a C++ class or similarly to enclose the C API in a clean object-oriented manner. -.. _usecapture-parameter-html5-api: +.. _usecapture-parameter-html5-api: The ``useCapture`` parameter maps to ``useCapture`` in `EventTarget.addEventListener `_. It indicates whether or not to initiate *capture*: if ``true`` the callback will be invoked only for the DOM capture and target phases; if ``false`` the callback will be triggered during the target and bubbling phases. See `DOM Level 3 Events `_ for a more detailed explanation. Most functions return the result using the type :c:data:`EMSCRIPTEN_RESULT`. Zero and positive values denote success. Negative values signal failure. None of the functions fail or abort by throwing a JavaScript or C++ exception. If a particular browser does not support the given feature, the value :c:data:`EMSCRIPTEN_RESULT_NOT_SUPPORTED` will be returned at the time the callback is registered. - + Callback functions ------------------ @@ -92,20 +92,20 @@ When the event occurs the callback is invoked with the relevant event "type" (fo ); -.. _callback-handler-return-em_bool-html5-api: +.. _callback-handler-return-em_bool-html5-api: Callback handlers that return an :c:data:`EM_BOOL` may specify ``true`` to signal that the handler *consumed* the event (this suppresses the default action for that event by calling its ``.preventDefault();`` member). Returning ``false`` indicates that the event was not consumed — the default browser event action is carried out and the event is allowed to pass on/bubble up as normal. Calling a registration function with a ``null`` pointer for the callback causes a de-registration of that callback from the given ``target`` element. All event handlers are also automatically unregistered when the C ``exit()`` function is invoked during the ``atexit`` handler pass. Either use the function :c:func:`emscripten_set_main_loop` or set ``Module.noExitRuntime = true;`` to make sure that leaving ``main()`` will not immediately cause an ``exit()`` and clean up the event handlers. -.. _web-security-functions-html5-api: +.. _web-security-functions-html5-api: Functions affected by web security ---------------------------------- Some functions, including :c:func:`emscripten_request_pointerlock` and :c:func:`emscripten_request_fullscreen`, are affected by web security. -While the functions can be called anywhere, the actual "requests" can only be raised inside the handler for a user-generated event (for example a key, mouse or touch press/release). +While the functions can be called anywhere, the actual "requests" can only be raised inside the handler for a user-generated event (for example a key, mouse or touch press/release). When porting code, it may be difficult to ensure that the functions are called inside appropriate event handlers (so that the requests are raised immediately). As a convenience, developers can set ``deferUntilInEventHandler=true`` to automatically defer insecure requests until the user next presses a keyboard or mouse button. This simplifies porting, but often results in a poorer user experience. For example, the user must click once on the canvas to hide the pointer or transition to full screen. @@ -122,7 +122,7 @@ The HTML5 test code demonstrates how to use this API: - `test_html5.c `_ - `test_html5_fullscreen.c `_ - `test_html5_mouse.c `_ - + General types ============= @@ -130,35 +130,35 @@ General types .. c:macro:: EM_BOOL - This is the Emscripten type for a ``bool``. + This is the Emscripten type for a ``bool``. Possible values: - + .. c:macro:: EM_TRUE - This is the Emscripten value for ``true``. + This is the Emscripten value for ``true``. .. c:macro:: EM_FALSE - This is the Emscripten value for ``false``. + This is the Emscripten value for ``false``. + - .. c:macro:: EM_UTF8 This is the Emscripten type for a UTF8 string (maps to a ``char``). This is used for node names, element ids, etc. - + Function result values ====================== Most functions in this API return a result of type :c:data:`EMSCRIPTEN_RESULT`. None of the functions fail or abort by throwing a JavaScript or C++ exception. If a particular browser does not support the given feature, the value :c:data:`EMSCRIPTEN_RESULT_NOT_SUPPORTED` will be returned at the time the callback is registered. - + .. c:macro:: EMSCRIPTEN_RESULT This type is used to return the result of most functions in this API. Zero and positive values denote success, while negative values signal failure. Possible values are listed below. - - + + .. c:macro:: EMSCRIPTEN_RESULT_SUCCESS The operation succeeded. @@ -166,63 +166,63 @@ Most functions in this API return a result of type :c:data:`EMSCRIPTEN_RESULT`. .. c:macro:: EMSCRIPTEN_RESULT_DEFERRED The requested operation cannot be completed now for :ref:`web security reasons`, and has been deferred for completion in the next event handler. - + .. c:macro:: EMSCRIPTEN_RESULT_NOT_SUPPORTED The given operation is not supported by this browser or the target element. This value will be returned at the time the callback is registered if the operation is not supported. - + .. c:macro:: EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED - The requested operation could not be completed now for :ref:`web security reasons`. It failed because the user requested the operation not be deferred. + The requested operation could not be completed now for :ref:`web security reasons`. It failed because the user requested the operation not be deferred. .. c:macro:: EMSCRIPTEN_RESULT_INVALID_TARGET - The operation failed because the specified target element is invalid. + The operation failed because the specified target element is invalid. .. c:macro:: EMSCRIPTEN_RESULT_UNKNOWN_TARGET - The operation failed because the specified target element was not found. + The operation failed because the specified target element was not found. .. c:macro:: EMSCRIPTEN_RESULT_INVALID_PARAM - The operation failed because an invalid parameter was passed to the function. + The operation failed because an invalid parameter was passed to the function. .. c:macro:: EMSCRIPTEN_RESULT_FAILED - Generic failure result message, returned if no specific result is available. + Generic failure result message, returned if no specific result is available. .. c:macro:: EMSCRIPTEN_RESULT_NO_DATA - The operation failed because no data is currently available. - + The operation failed because no data is currently available. + Keys ==== Defines -------- +------- .. c:macro:: EMSCRIPTEN_EVENT_KEYPRESS EMSCRIPTEN_EVENT_KEYDOWN EMSCRIPTEN_EVENT_KEYUP - + Emscripten key events. - + .. c:macro:: DOM_KEY_LOCATION - The location of the key on the keyboard; one of the values below. + The location of the key on the keyboard; one of the values below. .. c:macro:: DOM_KEY_LOCATION_STANDARD DOM_KEY_LOCATION_LEFT - DOM_KEY_LOCATION_RIGHT - DOM_KEY_LOCATION_NUMPAD + DOM_KEY_LOCATION_RIGHT + DOM_KEY_LOCATION_NUMPAD Locations of the key on the keyboard. Struct ------- +------ .. c:type:: EmscriptenKeyboardEvent @@ -232,66 +232,66 @@ Struct .. c:member:: EM_UTF8 key - - The printed representation of the pressed key. - + + The printed representation of the pressed key. + Maximum size 32 ``char`` (i.e. ``EM_UTF8 key[32]``). .. c:member:: EM_UTF8 code - - A string that identifies the physical key being pressed. The value is not affected by the current keyboard layout or modifier state, so a particular key will always return the same value. - - Maximum size 32 ``char`` (i.e. ``EM_UTF8 code[32]``). - + + A string that identifies the physical key being pressed. The value is not affected by the current keyboard layout or modifier state, so a particular key will always return the same value. + + Maximum size 32 ``char`` (i.e. ``EM_UTF8 code[32]``). + .. c:member:: unsigned long location - + Indicates the location of the key on the keyboard. One of the :c:data:`DOM_KEY_LOCATION ` values. .. c:member:: EM_BOOL ctrlKey EM_BOOL shiftKey EM_BOOL altKey EM_BOOL metaKey - - Specifies which modifiers were active during the key event. + + Specifies which modifiers were active during the key event. .. c:member:: EM_BOOL repeat - + Specifies if this keyboard event represents a repeated press. .. c:member:: EM_UTF8 locale - - A locale string indicating the configured keyboard locale. This may be an empty string if the browser or device doesn't know the keyboard's locale. - + + A locale string indicating the configured keyboard locale. This may be an empty string if the browser or device doesn't know the keyboard's locale. + Maximum size 32 char (i.e. ``EM_UTF8 locale[32]``). - + .. c:member:: EM_UTF8 charValue - - The following fields are values from previous versions of the DOM key events specifications. See `the character representation of the key `_. This is the field ``char`` from the docs, but renamed to ``charValue`` to avoid a C reserved word. - + + The following fields are values from previous versions of the DOM key events specifications. See `the character representation of the key `_. This is the field ``char`` from the docs, but renamed to ``charValue`` to avoid a C reserved word. + Maximum size 32 ``char`` (i.e. ``EM_UTF8 charValue[32]``). - + .. warning:: This attribute has been dropped from DOM Level 3 events. .. c:member:: unsigned long charCode - + The Unicode reference number of the key; this attribute is used only by the keypress event. For keys whose ``char`` attribute contains multiple characters, this is the Unicode value of the first character in that attribute. - + .. warning:: This attribute is deprecated, you should use the field ``key`` instead, if available. - + .. c:member:: unsigned long keyCode - + A system and implementation dependent numerical code identifying the unmodified value of the pressed key. - + .. warning:: This attribute is deprecated, you should use the field ``key`` instead, if available. - - + + .. c:member:: unsigned long which - + A system and implementation dependent numeric code identifying the unmodified value of the pressed key; this is usually the same as ``keyCode``. - + .. warning:: This attribute is deprecated, you should use the field ``key`` instead, if available. Note thought that while this field is deprecated, the cross-browser support for ``which`` may be better than for the other fields, so experimentation is recommended. Read issue https://github.com/kripken/emscripten/issues/2817 for more information. - + Callback functions ------------------ @@ -302,34 +302,34 @@ Callback functions .. code-block:: cpp typedef EM_BOOL (*em_key_callback_func)(int eventType, const EmscriptenKeyboardEvent *keyEvent, void *userData); - + :param int eventType: The type of :c:data:`key event `. :param keyEvent: Information about the key event that occurred. :type keyEvent: const EmscriptenKeyboardEvent* :param void* userData: The ``userData`` originally passed to the registration function. :returns: |callback-handler-return-value-doc| :rtype: |EM_BOOL| - - + + Functions ---------- +--------- .. c:function:: EMSCRIPTEN_RESULT emscripten_set_keypress_callback(const char *target, void *userData, EM_BOOL useCapture, em_key_callback_func callback) EMSCRIPTEN_RESULT emscripten_set_keydown_callback(const char *target, void *userData, EM_BOOL useCapture, em_key_callback_func callback) EMSCRIPTEN_RESULT emscripten_set_keyup_callback(const char *target, void *userData, EM_BOOL useCapture, em_key_callback_func callback) - - Registers a callback function for receiving browser-generated keyboard input events. - + + Registers a callback function for receiving browser-generated keyboard input events. + :param target: |target-parameter-doc| :type target: const char* :param void* userData: |userData-parameter-doc| :param EM_BOOL useCapture: |useCapture-parameter-doc| - :param em_key_callback_func callback: |callback-function-parameter-doc| + :param em_key_callback_func callback: |callback-function-parameter-doc| :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. :rtype: |EMSCRIPTEN_RESULT| - :see also: - - https://developer.mozilla.org/en/DOM/Event/UIEvent/KeyEvent + :see also: + - https://developer.mozilla.org/en/DOM/Event/UIEvent/KeyEvent - http://www.javascriptkit.com/jsref/eventkeyboardmouse.shtml Mouse @@ -345,76 +345,76 @@ Defines EMSCRIPTEN_EVENT_MOUSEMOVE EMSCRIPTEN_EVENT_MOUSEENTER EMSCRIPTEN_EVENT_MOUSELEAVE - + Emscripten mouse events. Struct ------- +------ .. c:type:: EmscriptenMouseEvent The event structure passed in `mouse events `_: `click `_, `mousedown `_, `mouseup `_, `dblclick `_, `mousemove `_, `mouseenter `_ and `mouseleave `_. - + .. c:member:: double timestamp; - + A timestamp of when this data was generated by the browser. This is an absolute wallclock time in milliseconds. .. c:member:: long screenX long screenY - + The coordinates relative to the browser screen coordinate system. - + .. c:member:: long clientX long clientY - + The coordinates relative to the viewport associated with the event. - - + + .. c:member:: EM_BOOL ctrlKey EM_BOOL shiftKey EM_BOOL altKey EM_BOOL metaKey - + Specifies which modifiers were active during the mouse event. - - + + .. c:member:: unsigned short button - + Identifies which pointer device button changed state (see `MouseEvent.button `_): - 0 : Left button - 1 : Middle button (if present) - 2 : Right button - + .. c:member:: unsigned short buttons - + A bitmask that indicates which combinations of mouse buttons were being held down at the time of the event. - + .. c:member:: long movementX long movementY; - + If pointer lock is active, these two extra fields give relative mouse movement since the last event. - + .. c:member:: long targetX long targetY - + These fields give the mouse coordinates mapped relative to the coordinate space of the target DOM element receiving the input events (Emscripten-specific extension). - + .. c:member:: long canvasX long canvasY - + These fields give the mouse coordinates mapped to the Emscripten canvas client area (Emscripten-specific extension). .. c:member:: long padding - + Internal, and can be ignored. - .. note:: Implementers only: pad this struct to multiple of 8 bytes to make ``WheelEvent`` unambiguously align to 8 bytes. + .. note:: Implementers only: pad this struct to multiple of 8 bytes to make ``WheelEvent`` unambiguously align to 8 bytes. Callback functions @@ -427,7 +427,7 @@ Callback functions .. code-block:: cpp typedef EM_BOOL (*em_mouse_callback_func)(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData); - + :param int eventType: The type of :c:data:`mouse event `. :param mouseEvent: Information about the mouse event that occurred. :type mouseEvent: const EmscriptenMouseEvent* @@ -436,9 +436,9 @@ Callback functions :rtype: |EM_BOOL| - + Functions ---------- +--------- .. c:function:: EMSCRIPTEN_RESULT emscripten_set_click_callback(const char *target, void *userData, EM_BOOL useCapture, em_mouse_callback_func callback) EMSCRIPTEN_RESULT emscripten_set_mousedown_callback(const char *target, void *userData, EM_BOOL useCapture, em_mouse_callback_func callback) @@ -457,19 +457,19 @@ Functions :param em_mouse_callback_func callback: |callback-function-parameter-doc| :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. :rtype: |EMSCRIPTEN_RESULT| - - + + .. c:function:: EMSCRIPTEN_RESULT emscripten_get_mouse_status(EmscriptenMouseEvent *mouseState) - Returns the most recently received mouse event state. - + Returns the most recently received mouse event state. + Note that for this function call to succeed, :c:func:`emscripten_set_xxx_callback ` must have first been called with one of the mouse event types and a non-zero callback function pointer to enable the Mouse state capture. :param EmscriptenMouseEvent* mouseState: The most recently received mouse event state. :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. :rtype: |EMSCRIPTEN_RESULT| - + Wheel @@ -479,43 +479,43 @@ Defines ------- .. c:macro:: EMSCRIPTEN_EVENT_WHEEL - + Emscripten wheel event. - + .. c:macro:: DOM_DELTA_PIXEL The units of measurement for the delta must be pixels (from `spec `_). - + .. c:macro:: DOM_DELTA_LINE The units of measurement for the delta must be individual lines of text (from `spec `_). - + .. c:macro:: DOM_DELTA_PAGE The units of measurement for the delta must be pages, either defined as a single screen or as a demarcated page (from `spec `_). - + Struct ------- +------ .. c:type:: EmscriptenWheelEvent The event structure passed in `mousewheel events `_. - + .. c:member:: EmscriptenMouseEvent mouse - + Specifies general mouse information related to this event. - + .. c:member:: double deltaX double deltaY double deltaZ - + Movement of the wheel on each of the axis. Note that these values may be fractional, so you should avoid simply casting them to integer, or it might result in scroll values of 0. The positive Y scroll direction is when scrolling the page downwards (page CSS pixel +Y direction), which corresponds to scrolling the mouse wheel downwards (away from the screen) on Windows, Linux, and also on OSX when the 'natural scroll' option is disabled. - + .. c:member:: unsigned long deltaMode - + One of the :c:data:`DOM_DELTA_` values that indicates the units of measurement for the delta values. @@ -529,7 +529,7 @@ Callback functions .. code-block:: cpp typedef EM_BOOL (*em_wheel_callback_func)(int eventType, const EmscriptenWheelEvent *wheelEvent, void *userData); - + :param int eventType: The type of wheel event (:c:data:`EMSCRIPTEN_EVENT_WHEEL`). :param wheelEvent: Information about the wheel event that occurred. :type wheelEvent: const EmscriptenWheelEvent* @@ -537,13 +537,13 @@ Callback functions :returns: |callback-handler-return-value-doc| :rtype: |EM_BOOL| - - + + Functions ---------- - +--------- + .. c:function:: EMSCRIPTEN_RESULT emscripten_set_wheel_callback(const char *target, void *userData, EM_BOOL useCapture, em_wheel_callback_func callback) - + Registers a callback function for receiving browser-generated `mousewheel events `_. :param target: |target-parameter-doc| @@ -564,40 +564,40 @@ Defines .. c:macro:: EMSCRIPTEN_EVENT_RESIZE EMSCRIPTEN_EVENT_SCROLL - + Emscripten UI events. - + Struct ------- +------ .. c:type:: EmscriptenUiEvent The event structure passed in DOM element `UIEvent `_ events: `resize `_ and `scroll `_. - + .. c:member:: long detail - + Specifies additional detail/information about this event. .. c:member:: int documentBodyClientWidth int documentBodyClientHeight - + The clientWidth/clientHeight of the ``document.body`` element. - + .. c:member:: int windowInnerWidth int windowInnerHeight - + The innerWidth/innerHeight of the browser window. .. c:member:: int windowOuterWidth int windowOuterHeight; - + The outerWidth/outerHeight of the browser window. - + .. c:member:: int scrollTop int scrollLeft - + The page scroll position. @@ -611,26 +611,26 @@ Callback functions .. code-block:: cpp typedef EM_BOOL (*em_ui_callback_func)(int eventType, const EmscriptenUiEvent *uiEvent, void *userData); - + :param int eventType: The type of UI event (:c:data:`EMSCRIPTEN_EVENT_RESIZE`). :param uiEvent: Information about the UI event that occurred. :type uiEvent: const EmscriptenUiEvent* :param void* userData: The ``userData`` originally passed to the registration function. :returns: |callback-handler-return-value-doc| :rtype: |EM_BOOL| - - + + Functions ---------- +--------- .. c:function:: EMSCRIPTEN_RESULT emscripten_set_resize_callback(const char *target, void *userData, EM_BOOL useCapture, em_ui_callback_func callback) EMSCRIPTEN_RESULT emscripten_set_scroll_callback(const char *target, void *userData, EM_BOOL useCapture, em_ui_callback_func callback) - + Registers a callback function for receiving DOM element `resize `_ and `scroll `_ events. - - .. note:: - - - For the ``resize`` callback, pass in target = 0 to get ``resize`` events from the ``Window`` object. + + .. note:: + + - For the ``resize`` callback, pass in target = 0 to get ``resize`` events from the ``Window`` object. - The DOM3 Events specification only requires that the ``Window`` object sends resize events. It is valid to register a ``resize`` callback on other DOM elements, but the browser is not required to fire ``resize`` events for these. :param target: |target-parameter-doc| @@ -642,7 +642,7 @@ Functions :rtype: |EMSCRIPTEN_RESULT| - + Focus ===== @@ -654,31 +654,31 @@ Defines EMSCRIPTEN_EVENT_FOCUS EMSCRIPTEN_EVENT_FOCUSIN EMSCRIPTEN_EVENT_FOCUSOUT - + Emscripten focus events. - + Struct ------- +------ .. c:type:: EmscriptenFocusEvent The event structure passed in DOM element `blur `_, `focus `_, `focusin `_ and `focusout `_ events. - + .. c:member:: EM_UTF8 nodeName - - The `nodeName `_ of the target HTML Element. - + + The `nodeName `_ of the target HTML Element. + Maximum size 128 ``char`` (i.e. ``EM_UTF8 nodeName[128]``). .. c:member:: EM_UTF8 id - - The ID of the target element. - + + The ID of the target element. + Maximum size 128 ``char`` (i.e. ``EM_UTF8 id[128]``). - - + + Callback functions ------------------ @@ -689,7 +689,7 @@ Callback functions .. code-block:: cpp typedef EM_BOOL (*em_focus_callback_func)(int eventType, const EmscriptenFocusEvent *focusEvent, void *userData); - + :param int eventType: The type of focus event (:c:data:`EMSCRIPTEN_EVENT_BLUR`). :param focusEvent: Information about the focus event that occurred. :type focusEvent: const EmscriptenFocusEvent* @@ -697,16 +697,16 @@ Callback functions :returns: |callback-handler-return-value-doc| :rtype: |EM_BOOL| - - + + Functions ---------- +--------- .. c:function:: EMSCRIPTEN_RESULT emscripten_set_blur_callback(const char *target, void *userData, EM_BOOL useCapture, em_focus_callback_func callback) EMSCRIPTEN_RESULT emscripten_set_focus_callback(const char *target, void *userData, EM_BOOL useCapture, em_focus_callback_func callback) EMSCRIPTEN_RESULT emscripten_set_focusin_callback(const char *target, void *userData, EM_BOOL useCapture, em_focus_callback_func callback) EMSCRIPTEN_RESULT emscripten_set_focusout_callback(const char *target, void *userData, EM_BOOL useCapture, em_focus_callback_func callback) - + Registers a callback function for receiving DOM element `blur `_, `focus `_, `focusin `_ and `focusout `_ events. :param target: |target-parameter-doc| @@ -718,7 +718,7 @@ Functions :rtype: |EMSCRIPTEN_RESULT| - + Device orientation ================== @@ -726,40 +726,40 @@ Defines ------- .. c:macro:: EMSCRIPTEN_EVENT_DEVICEORIENTATION - + Emscripten ``deviceorientation`` events. Struct ------- +------ .. c:type:: EmscriptenDeviceOrientationEvent The event structure passed in the `deviceorientation `_ event. - - + + .. c:member:: double timestamp - + Absolute wallclock time when the event occurred (in milliseconds). .. c:member:: double alpha double beta double gamma - - The `orientation `_ of the device in terms of the transformation from a coordinate frame fixed on the Earth to a coordinate frame fixed in the device. - + + The `orientation `_ of the device in terms of the transformation from a coordinate frame fixed on the Earth to a coordinate frame fixed in the device. + The image (source: `dev.opera.com `_) and definitions below illustrate the co-ordinate frame: - + - :c:type:`~EmscriptenDeviceOrientationEvent.alpha`: the rotation of the device around the Z axis. - :c:type:`~EmscriptenDeviceOrientationEvent.beta`: the rotation of the device around the X axis. - :c:type:`~EmscriptenDeviceOrientationEvent.gamma`: the rotation of the device around the Y axis. - + .. image:: device-orientation-axes.png :target: https://developer.mozilla.org/en-US/Apps/Build/gather_and_modify_data/responding_to_device_orientation_changes#Device_Orientation_API :alt: Image of device showing X, Y, Z axes - + .. c:member:: EM_BOOL absolute - + If ``false``, the orientation is only relative to some other base orientation, not to the fixed coordinate frame. @@ -773,7 +773,7 @@ Callback functions .. code-block:: cpp typedef EM_BOOL (*em_deviceorientation_callback_func)(int eventType, const EmscriptenDeviceOrientationEvent *deviceOrientationEvent, void *userData); - + :param int eventType: The type of orientation event (:c:data:`EMSCRIPTEN_EVENT_DEVICEORIENTATION`). :param deviceOrientationEvent: Information about the orientation event that occurred. :type deviceOrientationEvent: const EmscriptenDeviceOrientationEvent* @@ -781,13 +781,13 @@ Callback functions :returns: |callback-handler-return-value-doc| :rtype: |EM_BOOL| - - + + Functions ---------- +--------- .. c:function:: EMSCRIPTEN_RESULT emscripten_set_deviceorientation_callback(void *userData, EM_BOOL useCapture, em_deviceorientation_callback_func callback) - + Registers a callback function for receiving the `deviceorientation `_ event. :param void* userData: |userData-parameter-doc| @@ -799,16 +799,16 @@ Functions .. c:function:: EMSCRIPTEN_RESULT emscripten_get_deviceorientation_status(EmscriptenDeviceOrientationEvent *orientationState) - Returns the most recently received ``deviceorientation`` event state. - + Returns the most recently received ``deviceorientation`` event state. + Note that for this function call to succeed, :c:func:`emscripten_set_deviceorientation_callback` must have first been called with one of the mouse event types and a non-zero callback function pointer to enable the ``deviceorientation`` state capture. :param orientationState: The most recently received ``deviceorientation`` event state. - :type orientationState: EmscriptenDeviceOrientationEvent* + :type orientationState: EmscriptenDeviceOrientationEvent* :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. :rtype: |EMSCRIPTEN_RESULT| - + Device motion ============= @@ -817,7 +817,7 @@ Defines ------- .. c:macro:: EMSCRIPTEN_EVENT_DEVICEMOTION - + Emscripten `devicemotion `_ event. @@ -827,22 +827,22 @@ Struct .. c:type:: EmscriptenDeviceMotionEvent The event structure passed in the `devicemotion `_ event. - + .. c:member:: double timestamp - + Absolute wallclock time when the event occurred (milliseconds). .. c:member:: double accelerationX double accelerationY double accelerationZ - + Acceleration of the device excluding gravity. - + .. c:member:: double accelerationIncludingGravityX double accelerationIncludingGravityY - double accelerationIncludingGravityZ + double accelerationIncludingGravityZ Acceleration of the device including gravity. @@ -850,9 +850,9 @@ Struct .. c:member:: double rotationRateAlpha double rotationRateBeta double rotationRateGamma - + The rotational delta of the device. - + Callback functions ------------------ @@ -864,7 +864,7 @@ Callback functions .. code-block:: cpp typedef EM_BOOL (*em_devicemotion_callback_func)(int eventType, const EmscriptenDeviceMotionEvent *deviceMotionEvent, void *userData); - + :param int eventType: The type of devicemotion event (:c:data:`EMSCRIPTEN_EVENT_DEVICEMOTION`). :param deviceMotionEvent: Information about the devicemotion event that occurred. :type deviceMotionEvent: const EmscriptenDeviceMotionEvent* @@ -873,13 +873,13 @@ Callback functions :rtype: |EM_BOOL| - - + + Functions ---------- - +--------- + .. c:function:: EMSCRIPTEN_RESULT emscripten_set_devicemotion_callback(void *userData, EM_BOOL useCapture, em_devicemotion_callback_func callback) - + Registers a callback function for receiving the `devicemotion `_ event. :param void* userData: |userData-parameter-doc| @@ -891,8 +891,8 @@ Functions .. c:function:: EMSCRIPTEN_RESULT emscripten_get_devicemotion_status(EmscriptenDeviceMotionEvent *motionState) - Returns the most recently received `devicemotion `_ event state. - + Returns the most recently received `devicemotion `_ event state. + Note that for this function call to succeed, :c:func:`emscripten_set_devicemotion_callback` must have first been called with one of the mouse event types and a non-zero callback function pointer to enable the ``devicemotion`` state capture. :param motionState: The most recently received ``devicemotion`` event state. @@ -900,7 +900,7 @@ Functions :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. :rtype: |EMSCRIPTEN_RESULT| - + Orientation =========== @@ -909,10 +909,10 @@ Defines ------- .. c:macro:: EMSCRIPTEN_EVENT_ORIENTATIONCHANGE - + Emscripten `orientationchange `_ event. - - + + .. c:macro:: EMSCRIPTEN_ORIENTATION_PORTRAIT_PRIMARY Primary portrait mode orientation. @@ -920,34 +920,34 @@ Defines .. c:macro:: EMSCRIPTEN_ORIENTATION_PORTRAIT_SECONDARY Secondary portrait mode orientation. - + .. c:macro:: EMSCRIPTEN_ORIENTATION_LANDSCAPE_PRIMARY Primary landscape mode orientation. - + .. c:macro:: EMSCRIPTEN_ORIENTATION_LANDSCAPE_SECONDARY Secondary landscape mode orientation. - + Struct ------ .. c:type:: EmscriptenOrientationChangeEvent - The event structure passed in the `orientationchange `_ event. - - + The event structure passed in the `orientationchange `_ event. + + .. c:member:: int orientationIndex - + One of the :c:type:`EM_ORIENTATION_PORTRAIT_xxx ` fields, or -1 if unknown. .. c:member:: int orientationAngle - + Emscripten-specific extension: Some browsers refer to ``window.orientation``, so report that as well. - + Orientation angle in degrees. 0: "default orientation", i.e. default upright orientation to hold the mobile device in. Could be either landscape or portrait. - + Callback functions ------------------ @@ -959,7 +959,7 @@ Callback functions .. code-block:: cpp typedef EM_BOOL (*em_orientationchange_callback_func)(int eventType, const EmscriptenOrientationChangeEvent *orientationChangeEvent, void *userData); - + :param int eventType: The type of orientationchange event (:c:data:`EMSCRIPTEN_EVENT_ORIENTATIONCHANGE`). :param orientationChangeEvent: Information about the orientationchange event that occurred. :type orientationChangeEvent: const EmscriptenOrientationChangeEvent* @@ -967,12 +967,12 @@ Callback functions :returns: |callback-handler-return-value-doc| :rtype: |EM_BOOL| - + Functions ---------- +--------- .. c:function:: EMSCRIPTEN_RESULT emscripten_set_orientationchange_callback(void *userData, EM_BOOL useCapture, em_orientationchange_callback_func callback) - + Registers a callback function for receiving the `orientationchange `_ event. :param void* userData: |userData-parameter-doc| @@ -991,7 +991,7 @@ Functions :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. :rtype: |EMSCRIPTEN_RESULT| - + .. c:function:: EMSCRIPTEN_RESULT emscripten_lock_orientation(int allowedOrientations) Locks the screen orientation to the given set of :c:data:`allowed orientations `. @@ -1017,7 +1017,7 @@ Defines ------- .. c:macro:: EMSCRIPTEN_EVENT_FULLSCREENCHANGE - + Emscripten `fullscreenchange `_ event. .. c:macro:: EMSCRIPTEN_FULLSCREEN_SCALE @@ -1027,7 +1027,7 @@ Defines .. c:macro:: EMSCRIPTEN_FULLSCREEN_SCALE_DEFAULT - Specifies that the DOM element should not be resized by Emscripten runtime when transitioning between fullscreen and windowed modes. The browser will be responsible for + Specifies that the DOM element should not be resized by Emscripten runtime when transitioning between fullscreen and windowed modes. The browser will be responsible for scaling the DOM element to the fullscreen size. The proper browser behavior in this mode is to stretch the element to fit the full display ignoring aspect ratio, but at the time of writing, browsers implement different behavior here. See the discussion at https://github.com/kripken/emscripten/issues/2556 for more information. @@ -1039,12 +1039,12 @@ Defines .. c:macro:: EMSCRIPTEN_FULLSCREEN_SCALE_ASPECT Specifies that the Emscripten runtime should explicitly scale the CSS size of the target element to cover the whole screen, while adding either vertical or horizontal - black letterbox padding to preserve the aspect ratio of the content. The aspect ratio that is used here is the render target size of the canvas element. To change the + black letterbox padding to preserve the aspect ratio of the content. The aspect ratio that is used here is the render target size of the canvas element. To change the desired aspect ratio, call :c:func:`emscripten_set_canvas_size` before entering fullscreen mode. .. c:macro:: EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE - An enum-like type which specifies how the Emscripten runtime should treat the pixel size (render target resolution) of the target canvas element when displaying it in + An enum-like type which specifies how the Emscripten runtime should treat the pixel size (render target resolution) of the target canvas element when displaying it in fullscreen mode via calls to functions :c:func:`emscripten_request_fullscreen_strategy` and :c:func:`emscripten_enter_soft_fullscreen`. To better understand the underlying distinction between the CSS size of a canvas element versus the render target size of a canvas element, see https://www.khronos.org/webgl/wiki/HandlingHighDPI. @@ -1086,41 +1086,41 @@ Struct .. c:type:: EmscriptenFullscreenChangeEvent The event structure passed in the `fullscreenchange `_ event. - + .. c:member:: EM_BOOL isFullscreen - + Specifies whether an element on the browser page is currently fullscreen. .. c:member:: EM_BOOL fullscreenEnabled - + Specifies if the current page has the ability to display elements fullscreen. - + .. c:member:: EM_UTF8 nodeName - - The `nodeName `_ of the target HTML Element that is in full screen mode. - + + The `nodeName `_ of the target HTML Element that is in full screen mode. + Maximum size 128 ``char`` (i.e. ``EM_UTF8 nodeName[128]``). - + If ``isFullscreen`` is ``false``, then ``nodeName``, ``id`` and ``elementWidth`` and ``ElementHeight`` specify information about the element that just exited fullscreen mode. - + .. c:member:: EM_UTF8 id - - The ID of the target HTML element that is in full screen mode. - + + The ID of the target HTML element that is in full screen mode. + Maximum size 128 ``char`` (i.e. ``EM_UTF8 id[128]``). - + .. c:member:: int elementWidth int elementHeight - + The new pixel size of the element that changed fullscreen status. - + .. c:member:: int screenWidth int screenHeight - + The size of the whole screen, in pixels. .. c:type:: EmscriptenFullscreenStrategy @@ -1148,7 +1148,7 @@ Struct .. c:member:: void *canvasResizedCallbackUserData Stores a custom data field which will be passed to all calls to the user-provided callback function. - + Callback functions ------------------ @@ -1159,7 +1159,7 @@ Callback functions .. code-block:: cpp typedef EM_BOOL (*em_fullscreenchange_callback_func)(int eventType, const EmscriptenFullscreenChangeEvent *fullscreenChangeEvent, void *userData); - + :param int eventType: The type of fullscreen event (:c:data:`EMSCRIPTEN_EVENT_FULLSCREENCHANGE`). :param fullscreenChangeEvent: Information about the fullscreen event that occurred. :type fullscreenChangeEvent: const EmscriptenFullscreenChangeEvent* @@ -1168,19 +1168,19 @@ Callback functions :rtype: |EM_BOOL| - + Functions ---------- +--------- .. c:function:: EMSCRIPTEN_RESULT emscripten_set_fullscreenchange_callback(const char *target, void *userData, EM_BOOL useCapture, em_fullscreenchange_callback_func callback) - + Registers a callback function for receiving the `fullscreenchange `_ event. - + :param target: |target-parameter-doc| :type target: const char* :param void* userData: |userData-parameter-doc| :param EM_BOOL useCapture: |useCapture-parameter-doc| - :param em_fullscreenchange_callback_func callback: |callback-function-parameter-doc| + :param em_fullscreenchange_callback_func callback: |callback-function-parameter-doc| :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. :rtype: |EMSCRIPTEN_RESULT| @@ -1198,7 +1198,7 @@ Functions .. c:function:: EMSCRIPTEN_RESULT emscripten_request_fullscreen(const char *target, EM_BOOL deferUntilInEventHandler) Requests the given target element to transition to full screen mode. - + .. note:: This function can be called anywhere, but for web security reasons its associated *request* can only be raised inside the event handler for a user-generated event (for example a key, mouse or touch press/release). This has implications for porting and the value of ``deferUntilInEventHandler`` — see :ref:`web-security-functions-html5-api` for more information. .. note:: This function only performs a fullscreen request without changing any parameters of the DOM element that is to be displayed in fullscreen mode. At the time of writing, there are differences in how browsers present elements in fullscreen mode. For more information, read the discussion at https://github.com/kripken/emscripten/issues/2556. To display an element in fullscreen mode in a way that is consistent across browsers, prefer calling the function :c:func:`emscripten_request_fullscreen_strategy` instead. This function is best called only in scenarios where the preconfigured presets defined by :c:func:`emscripten_request_fullscreen_strategy` conflict with the developer's use case in some way. @@ -1206,10 +1206,10 @@ Functions :param target: |target-parameter-doc| :type target: const char* :param EM_BOOL deferUntilInEventHandler: If ``true`` requests made outside of a user-generated event handler are automatically deferred until the user next presses a keyboard or mouse button. If ``false`` the request will fail if called outside of a user-generated event handler. - + :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. :rtype: **EMSCRIPTEN_RESULT** - + .. c:function:: EMSCRIPTEN_RESULT emscripten_request_fullscreen_strategy(const char *target, EM_BOOL deferUntilInEventHandler, const EmscriptenFullscreenStrategy *fullscreenStrategy) Requests the given target element to transition to full screen mode, using a custom presentation mode for the element. This function is otherwise the same as :c:func:`emscripten_request_fullscreen`, but this function adds options to control how resizing and aspect ratio, and ensures that the behavior is consistent across browsers. @@ -1238,14 +1238,14 @@ Functions Returns back to windowed browsing mode from a soft fullscreen mode. Do not call this function to attempt to return to windowed browsing mode from a real fullscreen mode, or vice versa. -Pointerlock +Pointerlock =========== Defines ------- .. c:macro:: EMSCRIPTEN_EVENT_POINTERLOCKCHANGE - + Emscripten `pointerlockchange `_ event. .. c:macro:: EMSCRIPTEN_EVENT_POINTERLOCKERROR @@ -1259,21 +1259,21 @@ Struct The event structure passed in the `pointerlockchange `_ event. - + .. c:member:: EM_BOOL isActive - + Specifies whether an element on the browser page currently has pointer lock enabled. .. c:member:: EM_UTF8 nodeName - - The `nodeName `_ of the target HTML Element that has the pointer lock active. - + + The `nodeName `_ of the target HTML Element that has the pointer lock active. + Maximum size 128 ``char`` (i.e. ``EM_UTF8 nodeName[128]``). - + .. c:member:: EM_UTF8 id - - The ID of the target HTML element that has the pointer lock active. - + + The ID of the target HTML element that has the pointer lock active. + Maximum size 128 ``char`` (i.e. ``EM_UTF8 id[128]``). @@ -1287,7 +1287,7 @@ Callback functions .. code-block:: cpp typedef EM_BOOL (*em_pointerlockchange_callback_func)(int eventType, const EmscriptenPointerlockChangeEvent *pointerlockChangeEvent, void *userData); - + :param int eventType: The type of pointerlockchange event (:c:data:`EMSCRIPTEN_EVENT_POINTERLOCKCHANGE`). :param pointerlockChangeEvent: Information about the pointerlockchange event that occurred. :type pointerlockChangeEvent: const EmscriptenPointerlockChangeEvent* @@ -1308,16 +1308,16 @@ Callback functions :param void* userData: The ``userData`` originally passed to the registration function. :returns: |callback-handler-return-value-doc| :rtype: |EM_BOOL| - - + + Functions ---------- +--------- .. c:function:: EMSCRIPTEN_RESULT emscripten_set_pointerlockchange_callback(const char *target, void *userData, EM_BOOL useCapture, em_pointerlockchange_callback_func callback) - + Registers a callback function for receiving the `pointerlockchange `_ event. - + Pointer lock hides the mouse cursor and exclusively gives the target element relative mouse movement events via the `mousemove `_ event. :param target: |target-parameter-doc| @@ -1352,14 +1352,14 @@ Functions :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. :rtype: |EMSCRIPTEN_RESULT| - + .. c:function:: EMSCRIPTEN_RESULT emscripten_request_pointerlock(const char *target, EM_BOOL deferUntilInEventHandler) Requests the given target element to grab pointerlock. - + .. note:: This function can be called anywhere, but for web security reasons its associated *request* can only be raised inside the event handler for a user-generated event (for example a key, mouse or touch press/release). This has implications for porting and the value of ``deferUntilInEventHandler`` — see :ref:`web-security-functions-html5-api` for more information. - + :param target: |target-parameter-doc| :type target: const char* :param EM_BOOL deferUntilInEventHandler: If ``true`` requests made outside of a user-generated event handler are automatically deferred until the user next presses a keyboard or mouse button. If ``false`` the request will fail if called outside of a user-generated event handler. @@ -1374,7 +1374,7 @@ Functions :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. :rtype: |EMSCRIPTEN_RESULT| - + Visibility @@ -1384,14 +1384,14 @@ Defines ------- .. c:macro:: EMSCRIPTEN_EVENT_VISIBILITYCHANGE - + Emscripten `visibilitychange `_ event. .. c:macro:: EMSCRIPTEN_VISIBILITY_HIDDEN The document is `hidden `_ (not visible). - + .. c:macro:: EMSCRIPTEN_VISIBILITY_VISIBLE The document is at least partially `visible `_. @@ -1410,18 +1410,18 @@ Struct .. c:type:: EmscriptenVisibilityChangeEvent - The event structure passed in the `visibilitychange `_ event. - - + The event structure passed in the `visibilitychange `_ event. + + .. c:member:: EM_BOOL hidden - + If true, the current browser page is now hidden. - + .. c:member:: int visibilityState - + Specifies a more fine-grained state of the current page visibility status. One of the :c:type:`EMSCRIPTEN_VISIBILITY_ ` values. - + Callback functions ------------------ @@ -1433,7 +1433,7 @@ Callback functions .. code-block:: cpp typedef EM_BOOL (*em_visibilitychange_callback_func)(int eventType, const EmscriptenVisibilityChangeEvent *visibilityChangeEvent, void *userData); - + :param int eventType: The type of ``visibilitychange`` event (:c:data:`EMSCRIPTEN_VISIBILITY_HIDDEN`). :param visibilityChangeEvent: Information about the ``visibilitychange`` event that occurred. :type visibilityChangeEvent: const EmscriptenVisibilityChangeEvent* @@ -1441,12 +1441,12 @@ Callback functions :returns: |callback-handler-return-value-doc| :rtype: |EM_BOOL| - + Functions ---------- +--------- .. c:function:: EMSCRIPTEN_RESULT emscripten_set_visibilitychange_callback(void *userData, EM_BOOL useCapture, em_visibilitychange_callback_func callback) - + Registers a callback function for receiving the `visibilitychange `_ event. :param void* userData: |userData-parameter-doc| @@ -1476,78 +1476,78 @@ Defines EMSCRIPTEN_EVENT_TOUCHEND EMSCRIPTEN_EVENT_TOUCHMOVE EMSCRIPTEN_EVENT_TOUCHCANCEL - + Emscripten touch events. - + Struct ------ .. c:type:: EmscriptenTouchPoint Specifies the status of a single `touch point `_ on the page. - + .. c:member:: long identifier - + An identification number for each touch point. .. c:member:: long screenX long screenY - + The touch coordinate relative to the whole screen origin, in pixels. - + .. c:member:: long clientX long clientY - + The touch coordinate relative to the viewport, in pixels. .. c:member:: long pageX long pageY - + The touch coordinate relative to the viewport, in pixels, and including any scroll offset. .. c:member:: EM_BOOL isChanged - + Specifies whether the touch point changed during this event. - + .. c:member:: EM_BOOL onTarget - - Specifies whether this touch point is still above the original target on which it was initially pressed. - + + Specifies whether this touch point is still above the original target on which it was initially pressed. + .. c:member:: long targetX long targetY - + These fields give the touch coordinates mapped relative to the coordinate space of the target DOM element receiving the input events (Emscripten-specific extension). .. c:member:: long canvasX long canvasY - + The touch coordinates mapped to the Emscripten canvas client area, in pixels (Emscripten-specific extension). - + .. c:type:: EmscriptenTouchEvent Specifies the data of a single `touchevent `_. - + .. c:member:: int numTouches - + The number of valid elements in the touches array. - + .. c:member:: EM_BOOL ctrlKey EM_BOOL shiftKey EM_BOOL altKey EM_BOOL metaKey - + Specifies which modifiers were active during the touch event. - + .. c:member:: EmscriptenTouchPoint touches[32] - + An array of currently active touches, one for each finger. - - + + Callback functions ------------------ @@ -1559,7 +1559,7 @@ Callback functions .. code-block:: cpp typedef EM_BOOL (*em_touch_callback_func)(int eventType, const EmscriptenTouchEvent *touchEvent, void *userData); - + :param int eventType: The type of touch event (:c:data:`EMSCRIPTEN_EVENT_TOUCHSTART`). :param touchEvent: Information about the touch event that occurred. :type touchEvent: const EmscriptenTouchEvent* @@ -1567,10 +1567,10 @@ Callback functions :returns: |callback-handler-return-value-doc| :rtype: |EM_BOOL| - - + + Functions ---------- +--------- .. c:function:: EMSCRIPTEN_RESULT emscripten_set_touchstart_callback(const char *target, void *userData, EM_BOOL useCapture, em_touch_callback_func callback) EMSCRIPTEN_RESULT emscripten_set_touchend_callback(const char *target, void *userData, EM_BOOL useCapture, em_touch_callback_func callback) @@ -1597,7 +1597,7 @@ Defines .. c:macro:: EMSCRIPTEN_EVENT_GAMEPADCONNECTED EMSCRIPTEN_EVENT_GAMEPADDISCONNECTED - + Emscripten `gamepad `_ events. @@ -1607,56 +1607,56 @@ Struct .. c:type:: EmscriptenGamepadEvent Represents the current snapshot state of a `gamepad `_. - - + + .. c:member:: double timestamp - + Absolute wallclock time when the data was recorded (milliseconds). .. c:member:: int numAxes - + The number of valid axis entries in the ``axis`` array. - + .. c:member:: int numButtons - + The number of valid button entries in the analogButton and digitalButton arrays. .. c:member:: double axis[64] - + The analog state of the gamepad axes, in the range [-1, 1]. .. c:member:: double analogButton[64] - + The analog state of the gamepad buttons, in the range [0, 1]. - + .. c:member:: EM_BOOL digitalButton[64] - - The digital state of the gamepad buttons, either 0 or 1. + + The digital state of the gamepad buttons, either 0 or 1. .. c:member:: EM_BOOL connected - - Specifies whether this gamepad is connected to the browser page. + + Specifies whether this gamepad is connected to the browser page. .. c:member:: long index - - An ordinal associated with this gamepad, zero-based. + + An ordinal associated with this gamepad, zero-based. .. c:member:: EM_UTF8 id - - An ID for the brand or style of the connected gamepad device. Typically, this will include the USB vendor and a product ID. - + + An ID for the brand or style of the connected gamepad device. Typically, this will include the USB vendor and a product ID. + Maximum size 64 ``char`` (i.e. ``EM_UTF8 id[128]``). - + .. c:member:: EM_UTF8 mapping - - A string that identifies the layout or control mapping of this device. - + + A string that identifies the layout or control mapping of this device. + Maximum size 128 ``char`` (i.e. ``EM_UTF8 mapping[128]``). - + Callback functions ------------------ @@ -1667,35 +1667,35 @@ Callback functions .. code-block:: cpp typedef EM_BOOL (*em_gamepad_callback_func)(int eventType, const EmscriptenGamepadEvent *gamepadEvent, void *userData) - + :param int eventType: The type of gamepad event (:c:data:`EMSCRIPTEN_EVENT_GAMEPADCONNECTED`). :param gamepadEvent: Information about the gamepad event that occurred. :type gamepadEvent: const EmscriptenGamepadEvent* :param void* userData: The ``userData`` originally passed to the registration function. :returns: |callback-handler-return-value-doc| - :rtype: |EM_BOOL| - - - + :rtype: |EM_BOOL| + + + Functions ---------- +--------- .. c:function:: EMSCRIPTEN_RESULT emscripten_set_gamepadconnected_callback(void *userData, EM_BOOL useCapture, em_gamepad_callback_func callback) EMSCRIPTEN_RESULT emscripten_set_gamepaddisconnected_callback(void *userData, EM_BOOL useCapture, em_gamepad_callback_func callback) - + Registers a callback function for receiving the `gamepad `_ events: `gamepadconnected `_ and `gamepaddisconnected `_. :param void* userData: |userData-parameter-doc| :param EM_BOOL useCapture: |useCapture-parameter-doc| :param em_gamepad_callback_func callback: |callback-function-parameter-doc| :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| + :rtype: |EMSCRIPTEN_RESULT| .. c:function:: int emscripten_get_num_gamepads(void) Returns the number of gamepads connected to the system or :c:type:`EMSCRIPTEN_RESULT_NOT_SUPPORTED` if the current browser does not support gamepads. - + .. note:: A gamepad does not show up as connected until a button on it is pressed. .. note:: Gamepad API uses an array of gamepad state objects to return the state of each device. The devices are identified via the index they are present in in @@ -1727,10 +1727,10 @@ Defines .. c:macro:: EMSCRIPTEN_EVENT_BATTERYCHARGINGCHANGE EMSCRIPTEN_EVENT_BATTERYLEVELCHANGE - + Emscripten `batterymanager `_ events. - + Struct ------ @@ -1738,24 +1738,24 @@ Struct The event structure passed in the `batterymanager `_ events: ``chargingchange`` and ``levelchange``. - + .. c:member:: double chargingTime - + Time remaining until the battery is fully charged (seconds). .. c:member:: double dischargingTime - + Time remaining until the battery is empty and the system will be suspended (seconds). - + .. c:member:: double level - + Current battery level, on a scale of 0 to 1.0. .. c:member:: EM_BOOL charging; - + ``true`` if the battery is charging, ``false`` otherwise. - + Callback functions ------------------ @@ -1766,7 +1766,7 @@ Callback functions .. code-block:: cpp typedef EM_BOOL (*em_battery_callback_func)(int eventType, const EmscriptenBatteryEvent *batteryEvent, void *userData); - + :param int eventType: The type of ``batterymanager`` event (:c:data:`EMSCRIPTEN_EVENT_BATTERYCHARGINGCHANGE`). :param batteryEvent: Information about the ``batterymanager`` event that occurred. :type batteryEvent: const EmscriptenBatteryEvent* @@ -1774,20 +1774,20 @@ Callback functions :returns: |callback-handler-return-value-doc| :rtype: |EM_BOOL| - - + + Functions ---------- +--------- .. c:function:: EMSCRIPTEN_RESULT emscripten_set_batterychargingchange_callback(void *userData, em_battery_callback_func callback) EMSCRIPTEN_RESULT emscripten_set_batterylevelchange_callback(void *userData, em_battery_callback_func callback) - + Registers a callback function for receiving the `batterymanager `_ events: ``chargingchange`` and ``levelchange``. :param void* userData: |userData-parameter-doc| :param em_battery_callback_func callback: |callback-function-parameter-doc| :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. - :rtype: |EMSCRIPTEN_RESULT| + :rtype: |EMSCRIPTEN_RESULT| .. c:function:: EMSCRIPTEN_RESULT emscripten_get_battery_status(EmscriptenBatteryEvent *batteryState) @@ -1805,7 +1805,7 @@ Vibration ========= Functions ---------- +--------- .. c:function:: EMSCRIPTEN_RESULT emscripten_vibrate(int msecs) @@ -1834,9 +1834,9 @@ Defines ------- .. c:macro:: EMSCRIPTEN_EVENT_BEFOREUNLOAD - + Emscripten `beforeunload `_ event. - + Callback functions ------------------ @@ -1848,31 +1848,31 @@ Callback functions .. code-block:: cpp typedef const char *(*em_beforeunload_callback)(int eventType, const void *reserved, void *userData); - + :param int eventType: The type of ``beforeunload`` event (:c:data:`EMSCRIPTEN_EVENT_BEFOREUNLOAD`). :param reserved: Reserved for future use; pass in 0. :type reserved: const void* :param void* userData: The ``userData`` originally passed to the registration function. :returns: Return a string to be displayed to the user. :rtype: char* - - - + + + Functions --------- .. c:function:: EMSCRIPTEN_RESULT emscripten_set_beforeunload_callback(void *userData, em_beforeunload_callback callback) - + Registers a callback function for receiving the page `beforeunload `_ event. - - Hook into this event to perform actions immediately prior to page close (for example, to display a notification to ask if the user really wants to leave the page). + + Hook into this event to perform actions immediately prior to page close (for example, to display a notification to ask if the user really wants to leave the page). :param void* userData: |userData-parameter-doc| :param em_beforeunload_callback callback: |callback-function-parameter-doc| :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. :rtype: |EMSCRIPTEN_RESULT| - + WebGL context @@ -1883,27 +1883,27 @@ Defines .. c:macro:: EMSCRIPTEN_EVENT_WEBGLCONTEXTLOST EMSCRIPTEN_EVENT_WEBGLCONTEXTRESTORED - + Emscripten `WebGL context `_ events. .. c:type:: EMSCRIPTEN_WEBGL_CONTEXT_HANDLE Represents a handle to an Emscripten WebGL context object. The value 0 denotes an invalid/no context (this is a typedef to an ``int``). - - + + Struct ------ .. c:type:: EmscriptenWebGLContextAttributes - Specifies `WebGL context creation parameters `_. - + Specifies `WebGL context creation parameters `_. + .. c:member:: EM_BOOL alpha - + If ``true``, request an alpha channel for the context. If you create an alpha channel, you can blend the canvas rendering with the underlying web page contents. Default value: ``true``. - + .. c:member:: EM_BOOL depth - + If ``true``, request a depth buffer of at least 16 bits. If ``false``, no depth buffer will be initialized. Default value: ``true``. .. c:member:: EM_BOOL stencil @@ -1919,37 +1919,37 @@ Struct If ``true``, the alpha channel of the rendering context will be treated as representing premultiplied alpha values. If ``false``, the alpha channel represents non-premultiplied alpha. Default value: ``true``. - + .. c:member:: EM_BOOL preserveDrawingBuffer If ``true``, the contents of the drawing buffer are preserved between consecutive ``requestAnimationFrame()`` calls. If ``false``, color, depth and stencil are cleared at the beginning of each ``requestAnimationFrame()``. Generally setting this to ``false`` gives better performance. Default value: ``false``. - - + + .. c:member:: EM_BOOL preferLowPowerToHighPerformance If ``true``, hints the browser to initialize a low-power GPU rendering context. If ``false``, prefers to initialize a high-performance rendering context. Default value: ``false``. - .. c:member:: EM_BOOL failIfMajorPerformanceCaveat - + .. c:member:: EM_BOOL failIfMajorPerformanceCaveat + If ``true``, requests context creation to abort if the browser is only able to create a context that does not give good hardware-accelerated performance. Default value: ``false``. .. c:member:: int majorVersion int minorVersion - + Emscripten-specific extensions which specify the WebGL context version to initialize. For example, pass in ``majorVersion=1``, ``minorVersion=0`` to request a WebGL 1.0 context, and ``majorVersion=2``, ``minorVersion=0`` to request a WebGL 2.0 context. Default value: ``majorVersion=1``, ``minorVersion=0`` - - .. c:member:: EM_BOOL enableExtensionsByDefault + + .. c:member:: EM_BOOL enableExtensionsByDefault If ``true``, all GLES2-compatible non-performance-impacting WebGL extensions will automatically be enabled for you after the context has been created. If ``false``, no extensions are enabled by default, and you need to manually call :c:func:`emscripten_webgl_enable_extension` to enable each extension that you want to use. Default value: ``true``. - + Callback functions ------------------ @@ -1961,15 +1961,15 @@ Callback functions .. code-block:: cpp typedef EM_BOOL (*em_webgl_context_callback)(int eventType, const void *reserved, void *userData); - + :param int eventType: The type of :c:data:`WebGL context event `. :param reserved: Reserved for future use; pass in 0. :type reserved: const void* :param void* userData: The ``userData`` originally passed to the registration function. :returns: |callback-handler-return-value-doc| :rtype: |EM_BOOL| - - + + Functions --------- @@ -1998,13 +1998,13 @@ Functions :returns: ``true`` if the WebGL context is in a lost state. :rtype: |EM_BOOL| - + .. c:function:: void emscripten_webgl_init_context_attributes(EmscriptenWebGLContextAttributes *attributes) Populates all fields of the given :c:type:`EmscriptenWebGLContextAttributes` structure to their default values for use with WebGL 1.0. - + Call this function as a forward-compatible way to ensure that if there are new fields added to the ``EmscriptenWebGLContextAttributes`` structure in the future, that they also will get default-initialized without having to change any code. - + :param attributes: The structure to be populated. :type attributes: EmscriptenWebGLContextAttributes* @@ -2013,11 +2013,11 @@ Functions .. c:function:: EMSCRIPTEN_WEBGL_CONTEXT_HANDLE emscripten_webgl_create_context(const char *target, const EmscriptenWebGLContextAttributes *attributes) Creates and returns a new `WebGL context `_. - - .. note:: - + + .. note:: + - A successful call to this function will not immediately make that rendering context active. Call :c:func:`emscripten_webgl_make_context_current` after creating a context to activate it. - - This function will try to initialize the context version that was *exactly* requested. It will not e.g. initialize a newer backwards-compatible version or similar. + - This function will try to initialize the context version that was *exactly* requested. It will not e.g. initialize a newer backwards-compatible version or similar. :param target: The DOM canvas element in which to initialize the WebGL context. If 0 is passed, the element specified by ``Module.canvas`` will be used. :type target: const char* @@ -2026,7 +2026,7 @@ Functions :returns: On success, a strictly positive value that represents a handle to the created context. On failure, a negative number that can be cast to an |EMSCRIPTEN_RESULT| field to get the reason why the context creation failed. :rtype: |EMSCRIPTEN_WEBGL_CONTEXT_HANDLE| - + .. c:function:: EMSCRIPTEN_RESULT emscripten_webgl_make_context_current(EMSCRIPTEN_WEBGL_CONTEXT_HANDLE context) Activates the given WebGL context for rendering. After calling this function, all OpenGL functions (``glBindBuffer()``, ``glDrawArrays()``, etc.) can be applied to the given GL context. @@ -2035,16 +2035,16 @@ Functions :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. :rtype: |EMSCRIPTEN_RESULT| - + .. c:function:: EMSCRIPTEN_WEBGL_CONTEXT_HANDLE emscripten_webgl_get_current_context() Returns the currently active WebGL rendering context, or 0 if no context is active. Calling any WebGL functions when there is no active rendering context is undefined and may throw a JavaScript exception. :returns: The currently active WebGL rendering context, or 0 if no context is active. :rtype: |EMSCRIPTEN_WEBGL_CONTEXT_HANDLE| - - - + + + .. c:function:: EMSCRIPTEN_RESULT emscripten_webgl_get_drawing_buffer_size(EMSCRIPTEN_WEBGL_CONTEXT_HANDLE context, int *width, int *height) Gets the ``drawingBufferWidth`` and ``drawingBufferHeight`` of the specified WebGL context. @@ -2054,7 +2054,7 @@ Functions :param int *height: The context's ``drawingBufferHeight``. :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. :rtype: |EMSCRIPTEN_RESULT| - + .. c:function:: EMSCRIPTEN_RESULT emscripten_webgl_destroy_context(EMSCRIPTEN_WEBGL_CONTEXT_HANDLE context) @@ -2072,9 +2072,9 @@ Functions :param EMSCRIPTEN_WEBGL_CONTEXT_HANDLE context: The WebGL context on which the extension is to be enabled. :param extension: A string identifying the `WebGL extension `_. For example "OES_texture_float". :type extension: const char* - :returns: EM_TRUE if the given extension is supported by the context, and EM_FALSE if the extension was not available. + :returns: EM_TRUE if the given extension is supported by the context, and EM_FALSE if the extension was not available. :rtype: |EM_BOOL| - + .. comment : **HamishW** Are EM_TRUE, EM_FALSE defined? @@ -2108,12 +2108,12 @@ Functions :returns: :c:data:`EMSCRIPTEN_RESULT_SUCCESS`, or one of the other result values. :rtype: |EMSCRIPTEN_RESULT| - - + + .. COMMENT (not rendered): Section below is automated copy and replace text. .. COMMENT (not rendered): The replace function return values with links (not created automatically) - + .. |EMSCRIPTEN_RESULT| replace:: :c:type:`EMSCRIPTEN_RESULT` .. |EM_BOOL| replace:: :c:type:`EM_BOOL` .. |EMSCRIPTEN_WEBGL_CONTEXT_HANDLE| replace:: :c:type:`EMSCRIPTEN_WEBGL_CONTEXT_HANDLE` @@ -2126,7 +2126,7 @@ Functions .. |userData-parameter-doc| replace:: :ref:`User-defined data ` to be passed to the callback (opaque to the API). .. |useCapture-parameter-doc| replace:: Set ``true`` to :ref:`use capture `. .. |callback-handler-return-value-doc| replace:: ``true`` (non zero) to indicate that the event was consumed by the :ref:`callback handler `. -.. |callback-function-parameter-doc| replace:: A callback function. The function is called with the type of event, information about the event, and user data passed from this registration function. The callback should return ``true`` if the event is consumed. +.. |callback-function-parameter-doc| replace:: A callback function. The function is called with the type of event, information about the event, and user data passed from this registration function. The callback should return ``true`` if the event is consumed. diff --git a/site/source/docs/api_reference/index.rst b/site/source/docs/api_reference/index.rst index 833040ef77129..c5034e12b053a 100644 --- a/site/source/docs/api_reference/index.rst +++ b/site/source/docs/api_reference/index.rst @@ -6,40 +6,40 @@ API Reference This section lists Emscripten's public API, organised by header file. At a very high level it consists of: -- :ref:`emscripten-h`: +- :ref:`emscripten-h`: APIs for integrating with the browser environment. - -- :ref:`html5-h`: + +- :ref:`html5-h`: Low level glue bindings for interfacing with HTML5 APIs from native code. - -- :ref:`preamble-js`: + +- :ref:`preamble-js`: APIs for working with compiled code from JavaScript. -- :ref:`Filesystem-API` (**library_fs.js**): +- :ref:`Filesystem-API` (**library_fs.js**): APIs for managing file systems and synchronous file operations. - :ref:`Fetch API`: API for managing accesses to network XHR and IndexedDB. -- :ref:`Module`: +- :ref:`Module`: Global JavaScript object that can be used to control code execution and access exported methods. -- :ref:`val-h`: +- :ref:`val-h`: Embind API to support transliteration of JavaScript code to C++. -- :ref:`bind-h`: +- :ref:`bind-h`: Embind API for binding C++ functions and classes so that they can be called from JavaScript in a natural way. - :ref:`trace-h`: A tracing API for doing memory usage analysis. -- :ref:`api-reference-advanced-apis`: +- :ref:`api-reference-advanced-apis`: APIs for advanced users/core developers. -.. toctree:: +.. toctree:: :hidden: - + emscripten.h html5.h preamble.js diff --git a/site/source/docs/api_reference/module.rst b/site/source/docs/api_reference/module.rst index 19a2e0e0dd0dd..ee79119f04e4a 100644 --- a/site/source/docs/api_reference/module.rst +++ b/site/source/docs/api_reference/module.rst @@ -4,7 +4,7 @@ Module object ============= -``Module`` is a global JavaScript object with attributes that Emscripten-generated code calls at various points in its execution. +``Module`` is a global JavaScript object with attributes that Emscripten-generated code calls at various points in its execution. Developers can provide an implementation of ``Module`` to control the execution of code. For example, to define how notification messages from Emscripten are displayed, developers implement the :js:attr:`Module.print` attribute. @@ -20,7 +20,7 @@ Developers can provide an implementation of ``Module`` to control the execution Creating the Module object ========================== -Use emcc's :ref:`pre-js option` to add JavaScript code that defines (or extends) the ``Module`` object with the behaviour you need. +Use emcc's :ref:`pre-js option` to add JavaScript code that defines (or extends) the ``Module`` object with the behaviour you need. When generating only JavaScript (as opposed to HTML), no ``Module`` object is created by default, and the behaviour is entirely defined by the developer. For example, creating a ``Module`` object with the following code will cause all notifications from the program to be calls to ``alert()``. @@ -43,13 +43,13 @@ When generating HTML, Emscripten creates a ``Module`` object with default method Affecting execution =================== -The following ``Module`` attributes affect code execution. +The following ``Module`` attributes affect code execution. .. js:attribute:: Module.print Called when something is printed to standard output (stdout) - + .. js:attribute:: Module.printErr Called when something is printed to standard error (stderr) @@ -63,8 +63,8 @@ The following ``Module`` attributes affect code execution. .. js:attribute:: Module.preInit A function (or array of functions) that must be called before global initializers run, but after basic initialization of the JavaScript runtime. This is typically used for :ref:`File System operations `. - - + + .. js:attribute:: Module.preRun An array of functions to call right before calling ``run()``, but after defining and setting up the environment, including global initializers. This is useful, for example, to set up directories and files using the :ref:`Filesystem-API` — as this needs to happen after the FileSystem API has been loaded, but before the program starts to run. @@ -92,7 +92,7 @@ The following ``Module`` attributes affect code execution. .. js:attribute:: Module.filePackagePrefixURL This is the "prefix" URL for a preloaded data file that is hosted separately from its JavaScript and HTML files (it includes the full path up to, but not including, the data file). See :ref:`packaging-files-data-file-location` for more information. - + .. js:attribute:: Module.locateFile If set, this method will be called when the runtime needs to load either a file generated by the file packager (this is a generalization of ``Module.filePackagePrefixURL``), or the ``.mem`` memory init file. In both cases the function receives the URL, and should return the actual URL. This lets you host file packages or the ``.mem`` file on a different location than the current directory (which is the default expectation), for example if you want to host them on a CDN. @@ -137,7 +137,7 @@ The generated program is able to detect its execution environment by checking th However, sometimes it may be needed to override the detected environment: a typical use case would be module bundlers (like webpack): they are executed by nodejs but the final output is for browser. -In order to do that, you can dictate your preferred execution environment by setting the ``Module.ENVIRONMENT`` variable to one of those allowed values: +In order to do that, you can dictate your preferred execution environment by setting the ``Module.ENVIRONMENT`` variable to one of those allowed values: ``WEB`` diff --git a/site/source/docs/api_reference/preamble.js.rst b/site/source/docs/api_reference/preamble.js.rst index 1a44e41d434d5..7b9c9ba43aa19 100644 --- a/site/source/docs/api_reference/preamble.js.rst +++ b/site/source/docs/api_reference/preamble.js.rst @@ -35,26 +35,26 @@ Calling compiled C functions from JavaScript 'number', // return type ['number', 'number'], // argument types [10, 20]); // arguments - + // result is 30 - + .. COMMENT (not rendered): There is more complete documentation in the guide: **HamishW** — add link to guide when it exists (currently in wiki at "Interacting with code"). - - .. note:: - - ``ccall`` uses the C stack for temporary values. If you pass a string then it is only "alive" until the call is complete. If the code being called saves the pointer to be used later, it may point to invalid data. + + .. note:: + - ``ccall`` uses the C stack for temporary values. If you pass a string then it is only "alive" until the call is complete. If the code being called saves the pointer to be used later, it may point to invalid data. - If you need a string to live forever, you can create it, for example, using ``_malloc`` and :js:func:`stringToUTF8`. However, you must later delete it manually! - - LLVM optimizations can inline and remove functions, after which you will not be able to call them. Similarly, function names minified by the *Closure Compiler* are inaccessible. In either case, the solution is to add the functions to the ``EXPORTED_FUNCTIONS`` list when you invoke *emcc* : - + - LLVM optimizations can inline and remove functions, after which you will not be able to call them. Similarly, function names minified by the *Closure Compiler* are inaccessible. In either case, the solution is to add the functions to the ``EXPORTED_FUNCTIONS`` list when you invoke *emcc* : + :: -s EXPORTED_FUNCTIONS="['_main', '_myfunc']" - + Exported functions can be called as normal: :: - + a_result = Module.ccall('myfunc', 'number', ['number'], [10]) - - :param ident: The name of the C function to be called. + + :param ident: The name of the C function to be called. :param returnType: The return type of the function. Note that ``array`` is not supported as there is no way for us to know the length of the array. For a void function this can be ``null`` (note: the JavaScript ``null`` value, not a string containing the word "null"). .. note:: 64-bit integers become two 32-bit parameters, for the low and high bits (since 64-bit integers cannot be represented in JavaScript numbers). @@ -68,16 +68,16 @@ Calling compiled C functions from JavaScript .. COMMENT (not rendered): The ccall/cwrap functions only work for C++ functions that use "extern C". In theory ordinary C++ names can be unmangled, but it would require tool to ship a fairly large amount of code just for this purpose. - + .. js:function:: cwrap(ident, returnType, argTypes) - Returns a native JavaScript wrapper for a C function. - + Returns a native JavaScript wrapper for a C function. + This is similar to :js:func:`ccall`, but returns a JavaScript function that can be reused as many time as needed. The C function can be defined in a C file, or be a C-compatible C++ function defined using ``extern "C"`` (to prevent name mangling). - + .. code-block:: javascript - + // Call C from JavaScript var c_javascript_add = Module.cwrap('c_add', // name of C function 'number', // return type @@ -85,62 +85,62 @@ Calling compiled C functions from JavaScript // Call c_javascript_add normally console.log(c_javascript_add(10, 20)); // 30 - console.log(c_javascript_add(20, 30)); // 50 + console.log(c_javascript_add(20, 30)); // 50 .. COMMENT (not rendered): There is more complete documentation in the guide: **HamishW** — add link to guide when it exists (currently in wiki at "Interacting with code"). - - .. note:: + + .. note:: - ``cwrap`` uses the C stack for temporary values. If you pass a string then it is only "alive" until the call is complete. If the code being called saves the pointer to be used later, it may point to invalid data. If you need a string to live forever, you can create it, for example, using ``_malloc`` and :js:func:`stringToUTF8`. However, you must later delete it manually! - - LLVM optimizations can inline and remove functions, after which you will not be able to "wrap" them. Similarly, function names minified by the *Closure Compiler* are inaccessible. In either case, the solution is to add the functions to the ``EXPORTED_FUNCTIONS`` list when you invoke *emcc* : + - LLVM optimizations can inline and remove functions, after which you will not be able to "wrap" them. Similarly, function names minified by the *Closure Compiler* are inaccessible. In either case, the solution is to add the functions to the ``EXPORTED_FUNCTIONS`` list when you invoke *emcc* : - ``cwrap`` does not actually call compiled code (only calling the wrapper it returns does that). That means that it is safe to call ``cwrap`` early, before the runtime is fully initialized (but calling the returned wrapped function must wait for the runtime, of course, like calling compiled code in general). - + :: -s EXPORTED_FUNCTIONS="['_main', '_myfunc']" - + Exported functions can be called as normal: :: - + my_func = Module.cwrap('myfunc', 'number', ['number']) my_func(12) - :param ident: The name of the C function to be called. + :param ident: The name of the C function to be called. :param returnType: The return type of the function. This can be ``"number"``, ``"string"`` or ``"array"``, which correspond to the appropriate JavaScript types (use ``"number"`` for any C pointer, and ``"array"`` for JavaScript arrays and typed arrays; note that arrays are 8-bit), or for a void function it can be ``null`` (note: the JavaScript ``null`` value, not a string containing the word "null"). :param argTypes: An array of the types of arguments for the function (if there are no arguments, this can be omitted). Types are as in ``returnType``, except that ``array`` is not supported as there is no way for us to know the length of the array). - :returns: A JavaScript function that can be used for running the C function. + :returns: A JavaScript function that can be used for running the C function. + + + - - - Accessing memory ================ - + .. js:function:: setValue(ptr, value, type[, noSafe]) - Sets a value at a specific memory address at run-time. - + Sets a value at a specific memory address at run-time. + .. note:: - :js:func:`setValue` and :js:func:`getValue` only do *aligned* writes and reads. - - The ``type`` is an LLVM IR type (one of ``i8``, ``i16``, ``i32``, ``i64``, ``float``, ``double``, or a pointer type like ``i8*`` or just ``*``), not JavaScript types as used in :js:func:`ccall` or :js:func:`cwrap`. This is a lower-level operation, and we do need to care what specific type is being used. + - The ``type`` is an LLVM IR type (one of ``i8``, ``i16``, ``i32``, ``i64``, ``float``, ``double``, or a pointer type like ``i8*`` or just ``*``), not JavaScript types as used in :js:func:`ccall` or :js:func:`cwrap`. This is a lower-level operation, and we do need to care what specific type is being used. - :param ptr: A pointer (number) representing the memory address. - :param value: The value to be stored - :param type: An LLVM IR type as a string (see "note" above). - :param noSafe: Developers should ignore this variable. It is only used in ``SAFE_HEAP`` compilation mode, where it can help avoid infinite recursion in some specialist use cases. + :param ptr: A pointer (number) representing the memory address. + :param value: The value to be stored + :param type: An LLVM IR type as a string (see "note" above). + :param noSafe: Developers should ignore this variable. It is only used in ``SAFE_HEAP`` compilation mode, where it can help avoid infinite recursion in some specialist use cases. :type noSafe: bool - - + + .. js:function:: getValue(ptr, type[, noSafe]) - Gets a value at a specific memory address at run-time. + Gets a value at a specific memory address at run-time. .. note:: - :js:func:`setValue` and :js:func:`getValue` only do *aligned* writes and reads! - The ``type`` is an LLVM IR type (one of ``i8``, ``i16``, ``i32``, ``i64``, ``float``, ``double``, or a pointer type like ``i8*`` or just ``*``), not JavaScript types as used in :js:func:`ccall` or :js:func:`cwrap`. This is a lower-level operation, and we do need to care what specific type is being used. - :param ptr: A pointer (number) representing the memory address. - :param type: An LLVM IR type as a string (see "note" above). + :param ptr: A pointer (number) representing the memory address. + :param type: An LLVM IR type as a string (see "note" above). :param noSafe: Developers should ignore this variable. It is only used in ``SAFE_HEAP`` compilation mode, where it can help avoid infinite recursion in some specialist use cases. :type noSafe: bool :returns: The value stored at the specified memory address. @@ -152,9 +152,9 @@ Conversion functions — strings, pointers and arrays =================================================== .. js:function:: Pointer_stringify(ptr[, length]) - + Returns a JavaScript String from a pointer, for use in compiled code. - + :param ptr: The pointer to be converted to a ``String``. :param length: The length of the data in the pointer (optional). :returns: A JavaScript ``String`` containing the data from ``ptr``. @@ -167,7 +167,7 @@ Conversion functions — strings, pointers and arrays :param ptr: A pointer to a null-terminated UTF8-encoded string in the Emscripten HEAP. :returns: A JavaScript ``String`` object - + .. js:function:: stringToUTF8(str, outPtr, maxBytesToWrite) @@ -188,13 +188,13 @@ Conversion functions — strings, pointers and arrays :param ptr: A pointer to a null-terminated UTF16LE-encoded string in the Emscripten HEAP. :returns: A JavaScript ``String`` object - + .. js:function:: stringToUTF16(str, outPtr, maxBytesToWrite) - Copies the given JavaScript ``String`` object ``str`` to the Emscripten HEAP at address ``outPtr``, null-terminated and encoded in UTF16LE form. - + Copies the given JavaScript ``String`` object ``str`` to the Emscripten HEAP at address ``outPtr``, null-terminated and encoded in UTF16LE form. + The copy will require exactly ``(str.length+1)*2`` bytes of space in the HEAP. :param str: A JavaScript ``String`` object. @@ -210,14 +210,14 @@ Conversion functions — strings, pointers and arrays :param ptr: A pointer to a null-terminated UTF32LE-encoded string in the Emscripten HEAP. :returns: A JavaScript ``String`` object. - + .. js:function:: stringToUTF32(str, outPtr, maxBytesToWrite) - Copies the given JavaScript ``String`` object ``str`` to the Emscripten HEAP at address ``outPtr``, null-terminated and encoded in UTF32LE form. - + Copies the given JavaScript ``String`` object ``str`` to the Emscripten HEAP at address ``outPtr``, null-terminated and encoded in UTF32LE form. + The copy will require at most ``(str.length+1)*4`` bytes of space in the HEAP, but can use less, since ``str.length`` does not return the number of characters in the string, but the number of UTF-16 code units in the string. You can use the function ``lengthBytesUTF32()`` to compute the exact amount of bytes (excluding the null terminator) needed to encode the string. - + :param str: A JavaScript ``String`` object. :type str: String :param outPtr: Pointer to data copied from ``str``, encoded in encoded in UTF32LE format and null-terminated. @@ -234,32 +234,32 @@ Conversion functions — strings, pointers and arrays :param dontAddNull: If ``true``, the new array is not zero-terminated. :type dontAddNull: bool :param length: The length of the array (optional). - :returns: The array created from ``stringy``. - + :returns: The array created from ``stringy``. + .. js:function:: intArrayToString(array) - This creates a JavaScript string from a zero-terminated C-line array of numbers. + This creates a JavaScript string from a zero-terminated C-line array of numbers. :param array: The array to convert. :returns: A ``String``, containing the content of ``array``. - + .. js:function:: writeStringToMemory(string, buffer, dontAddNull) - Writes a JavaScript string to a specified address in the heap. + Writes a JavaScript string to a specified address in the heap. .. warning:: This function is deprecated, you should call the function ``stringToUTF8`` instead, which provides a secure bounded version of the same functionality instead. - + .. code-block:: javascript - + // Allocate space for string and extra '0' at the end var buffer = Module._malloc(myString.length+1); - + // Write the string to memory Module.writeStringToMemory(myString, buffer); - + // We can now send buffer into a C function, it is just a normal char* pointer :param string: The string to write into memory. @@ -267,8 +267,8 @@ Conversion functions — strings, pointers and arrays :param buffer: The address (number) where ``string`` is to be written. :type buffer: Number :param dontAddNull: If ``true``, the new array is not zero-terminated. - :type dontAddNull: bool - + :type dontAddNull: bool + .. js:function:: writeArrayToMemory(array, buffer) @@ -279,30 +279,30 @@ Conversion functions — strings, pointers and arrays :param buffer: The address (number) where ``array`` is to be written. :type buffer: Number - + .. js:function:: writeAsciiToMemory(str, buffer, dontAddNull) Writes an ASCII string to a specified address in the heap. Note that memory should to be allocated for the string before it is written. - + The string is assumed to only have characters in the ASCII character set. If ASSERTIONS are enabled and this is not the case, it will fail. - + .. code-block:: javascript - + // Allocate space for string var buffer = Module._malloc(myString.length); - + // Write the string to memory Module.writeStringToMemory(myString, buffer); :param string: The string to write into memory. :param buffer: The address where ``string`` is to be written. :param dontAddNull: If ``true``, the new string is not zero-terminated. - :type dontAddNull: bool + :type dontAddNull: bool -Run dependencies +Run dependencies ===================================== Note that generally run dependencies are managed by the file packager and other parts of the system. It is rare for developers to use this API directly. @@ -310,32 +310,32 @@ Note that generally run dependencies are managed by the file packager and other .. js:function:: addRunDependency(id) - Adds an ``id`` to the list of run dependencies. - - This adds a run dependency and increments the run dependency counter. - + Adds an ``id`` to the list of run dependencies. + + This adds a run dependency and increments the run dependency counter. + .. COMMENT (not rendered): **HamishW** Remember to link to Execution lifecycle in Browser environment or otherwise link to information on using this. Possibly its own topic. :param id: An arbitrary id representing the operation. :type id: String - - + + .. js:function:: removeRunDependency(id) Removes a specified ``id`` from the list of run dependencies. :param id: The identifier for the specific dependency to be removed (added with :js:func:`addRunDependency`) :type id: String - -Stack trace + +Stack trace ===================== .. js:function:: stackTrace() - Returns the current stack track. + Returns the current stack track. .. note:: The stack trace is not available at least on IE10 and Safari 6. @@ -352,50 +352,50 @@ The :ref:`emscripten-memory-model` uses a typed array buffer (``ArrayBuffer``) t .. js:data:: HEAP8 - View for 8-bit signed memory. + View for 8-bit signed memory. + - .. js:data:: HEAP16 - View for 16-bit signed memory. + View for 16-bit signed memory. + - .. js:data:: HEAP32 - View for 32-bit signed memory. - + View for 32-bit signed memory. + .. js:data:: HEAPU8 - View for 8-bit unsigned memory. + View for 8-bit unsigned memory. + - .. js:data:: HEAPU16 - View for 16-bit unsigned memory. + View for 16-bit unsigned memory. + - .. js:data:: HEAPU32 - View for 32-bit unsigned memory. + View for 32-bit unsigned memory. .. js:data:: HEAPF32 - View for 32-bit float memory. + View for 32-bit float memory. + - .. js:data:: HEAPF64 - View for 64-bit float memory. + View for 64-bit float memory. + + + - - - .. COMMENT (not rendered) : The following methods are explicitly not part of the public API and not documented. Note that in some case referred to by function name, other cases by Module assignment. - + function allocate(slab, types, allocator, ptr) — Internal and use is discouraged. Documentation can remain in source code but not here. associated contants ALLOC_NORMAL, ALLOC_STACK, ALLOC_STATIC, ALLOC_DYNAMIC, ALLOC_NONE @@ -442,10 +442,10 @@ The :ref:`emscripten-memory-model` uses a typed array buffer (``ArrayBuffer``) t .. PRIVATE NOTES (not rendered) : - In theory JavaScript exceptions could be thrown for very bad input (e.g., provide an integer instead of a string, and the function does .length on it). These are implied everywhere and not documented. - - noSafe parameter: It solves technical problem of infinite recursion in some cases where SAFE_HEAP is being used. Not really interesting for users. + - noSafe parameter: It solves technical problem of infinite recursion in some cases where SAFE_HEAP is being used. Not really interesting for users. + - diff --git a/site/source/docs/api_reference/val.h.rst b/site/source/docs/api_reference/val.h.rst index 5857a75135577..5fdd8f78ff2af 100644 --- a/site/source/docs/api_reference/val.h.rst +++ b/site/source/docs/api_reference/val.h.rst @@ -6,17 +6,17 @@ val.h (under-construction) .. COMMENT (Not rendered) : This created from val.h header file on 10 Aug 2014-03 -The *Embind* C++ class :cpp:class:`emscripten::val` (defined in `val.h `_) is used to *transliterate* JavaScript code to C++. +The *Embind* C++ class :cpp:class:`emscripten::val` (defined in `val.h `_) is used to *transliterate* JavaScript code to C++. Guide material for this class can be found in :ref:`embind-val-guide`. .. cpp:namespace:: emscripten - + .. cpp:class:: emscripten::val This class is a C++ data type that can be used to represent (and provide convenient access to) any JavaScript object. You can use it to call a JavaScript object, read and write its properties, or coerce it to a C++ value like a ``bool``, ``int``, or ``std::string``. - + For example, the code below shows some simple JavaScript for making an XHR request on a URL: .. code:: javascript @@ -24,21 +24,21 @@ Guide material for this class can be found in :ref:`embind-val-guide`. var xhr = new XMLHttpRequest; xhr.open("GET", "http://url"); - + This same code can be written in C++, using :cpp:func:`~emscripten::val::global` to get the symbol for the global ``XMLHttpRequest`` object and then using it to open a URL. - + .. code:: cpp val xhr = val::global("XMLHttpRequest").new_(); xhr.call("open", std::string("GET"), std::string("http://url")); - + See :ref:`embind-val-guide` for other examples. - - .. todo:: - + + .. todo:: + **HamishW** Notes from source FYI: Can/should these be included? :: // missing operators: @@ -60,112 +60,112 @@ Guide material for this class can be found in :ref:`embind-val-guide`. .. cpp:function:: static val array() Creates and returns a new ``Array``. - + :returns: The new ``Array``. - + .. cpp:function:: static val object() Creates and returns a new ``Object``. - + :returns: The new ``Object``. - + .. cpp:function:: static val undefined() Creates a ``val`` that represents ``undefined``. - + :returns: The ``val`` that represents ``undefined``. - - + + .. cpp:function:: static val null() Creates a ``val`` that represents ``null``. ``val::undefined()`` is the same, but for undefined. - - :returns: A ``val`` that represents ``null``. - + :returns: A ``val`` that represents ``null``. + + .. cpp:function:: static val take_ownership(internal::EM_VAL e) **HamishW**-Replace with description. - - :returns: **HamishW**-Replace with description. + + :returns: **HamishW**-Replace with description. .. cpp:function:: static val global(const char* name) Looks up a global symbol. - + :param const char* name: **HamishW**-Replace with description. - :returns: **HamishW**-Replace with description. - + :returns: **HamishW**-Replace with description. + .. cpp:function:: static val module_property(const char* name) Looks up a symbol on the emscripten Module object. - + :param const char* name: **HamishW**-Replace with description. - :returns: **HamishW**-Replace with description. + :returns: **HamishW**-Replace with description. + - .. cpp:function:: static val module_property(const char* name) **HamishW**-Replace with description. - + :param const char* name: **HamishW**-Replace with description. - :returns: **HamishW**-Replace with description. + :returns: **HamishW**-Replace with description. .. cpp:function:: explicit val(T&& value) Constructor. - + A ``val`` can be constructed by explicit construction from any C++ type. For example, ``val(true)`` or ``val(std::string("foo"))``. - + :param T&& value: Any C++ type. - - + + **HamishW** Don't know how following "floating statement works". Leaving here for discussion ``val() = delete;`` - + .. cpp:function:: explicit val(const char* v) **HamishW**-Replace with description. - - :param const char* v: **HamishW**-Replace with description. - + + :param const char* v: **HamishW**-Replace with description. + .. cpp:function:: val(val&& v) **HamishW**-Replace with description. - - :param val&& v: **HamishW**-Replace with description. - + + :param val&& v: **HamishW**-Replace with description. + .. cpp:function:: val(const val& v) **HamishW**-Replace with description. - - :param const val& v: **HamishW**-Replace with description. - + + :param const val& v: **HamishW**-Replace with description. + .. cpp:function:: ~val() Destructor. **HamishW**-Replace with further description or delete comment. - + .. cpp:function:: val(const val& v) **HamishW**-Replace with description. - - :param const val& v: **HamishW**-Replace with description. - + + :param const val& v: **HamishW**-Replace with description. + .. cpp:function:: val& operator=(val&& v) **HamishW**-Replace with description. - + :param val&& v: **HamishW**-Replace with description. :returns: **HamishW**-Replace with description. @@ -173,90 +173,90 @@ Guide material for this class can be found in :ref:`embind-val-guide`. .. cpp:function:: val& operator=(const val& v) **HamishW**-Replace with description. - + :param val&& v: **HamishW**-Replace with description. - :returns: **HamishW**-Replace with description. + :returns: **HamishW**-Replace with description. + - .. cpp:function:: bool hasOwnProperty(const char* key) const Test whether ... **HamishW**-Replace with description. - + :param const char* key: **HamishW**-Replace with description. - :returns: **HamishW**-Replace with description. + :returns: **HamishW**-Replace with description. + - .. cpp:function:: val new_() - - prototype: - + + prototype: + :: - + template val new_(Args&&... args) const **HamishW**-Replace with description. - + :param Args&&... args: **HamishW**-Replace with description. Note that this is a templated value. - :returns: **HamishW**-Replace with description. + :returns: **HamishW**-Replace with description. .. cpp:function:: val operator[](const T& key) const **HamishW**-Replace with description. - + :param const T& key: **HamishW**-Replace with description. Note that this is a templated value. - :returns: **HamishW**-Replace with description. + :returns: **HamishW**-Replace with description. .. cpp:function:: void set(const K& key, const val& v) Set the specified (``key``) property of a JavaScript object (accessed through a ``val``) with the value ``v``. **HamishW**-Replace with description. - + :param const K& key: **HamishW**-Replace with description. Note that this is a templated value. :param const val& v: **HamishW**-Replace with description. Note that this is a templated value. - + .. cpp:function:: val operator()(Args&&... args) **HamishW**-Replace with description. - - :param Args&&... args: **HamishW**-Replace with description. Note that this is a templated value. - + + :param Args&&... args: **HamishW**-Replace with description. Note that this is a templated value. + .. cpp:function:: ReturnValue call(const char* name, Args&&... args) const **HamishW**-Replace with description. - - :param const char* name: **HamishW**-Replace with description. - :param Args&&... args: **HamishW**-Replace with description. Note that this is a templated value. - + :param const char* name: **HamishW**-Replace with description. + :param Args&&... args: **HamishW**-Replace with description. Note that this is a templated value. + + .. cpp:function:: T as() const **HamishW**-Replace with description. - - :returns: **HamishW**-Replace with description. Note that this is a templated value. + + :returns: **HamishW**-Replace with description. Note that this is a templated value. .. cpp:function:: val typeof() const **HamishW**-Replace with description. - - :returns: **HamishW**-Replace with description. - - + + :returns: **HamishW**-Replace with description. + + .. cpp:function:: std::vector vecFromJSArray(val v) **HamishW**-Replace with description. - + **HamishW**. I believe NOT internal. Please confirm. - - :param val v: **HamishW**-Replace with description. - :returns: **HamishW**-Replace with description. - - + + :param val v: **HamishW**-Replace with description. + :returns: **HamishW**-Replace with description. + + .. cpp:type: EMSCRIPTEN_SYMBOL(name) - **HamishW**-Replace with description. + **HamishW**-Replace with description. diff --git a/site/source/docs/building_from_source/building_emscripten_from_source_on_linux.rst b/site/source/docs/building_from_source/building_emscripten_from_source_on_linux.rst index 4b205fab885c6..3b370ef55156d 100644 --- a/site/source/docs/building_from_source/building_emscripten_from_source_on_linux.rst +++ b/site/source/docs/building_from_source/building_emscripten_from_source_on_linux.rst @@ -21,64 +21,64 @@ Installing required tools These instructions explain how to install **all** the :ref:`required tools `. You can :ref:`test whether some of these are already installed ` on the platform and skip those steps. -1. Update the *system package manager* to ensure the package lists are up to date: +1. Update the *system package manager* to ensure the package lists are up to date: :: - + sudo apt-get update -#. Install *Python* using the *system package manager*: +#. Install *Python* using the *system package manager*: :: - + sudo apt-get install python2.7 -#. Install `node.js `_ using the *system package manager*: +#. Install `node.js `_ using the *system package manager*: :: - + sudo apt-get install nodejs -#. Install *gcc* and *cmake* using the *system package manager*: +#. Install *gcc* and *cmake* using the *system package manager*: :: - + sudo apt-get install build-essential sudo apt-get install cmake -#. Install *git* using the *system package manager*: +#. Install *git* using the *system package manager*: :: - + sudo apt-get install git-core -#. Install *Java* using the *system package manager*: +#. Install *Java* using the *system package manager*: :: - + sudo apt-get install default-jre -#. Build :ref:`Fastcomp ` (LLVM + Clang) from source using :ref:`these instructions `. - +#. Build :ref:`Fastcomp ` (LLVM + Clang) from source using :ref:`these instructions `. + #. Clone the `kripken/emscripten `_ repository from Github. This repository contains the main compiler tool for compiling C/C++ programs to JavaScript: - - Create a directory (with no spaces in the name) to contain the clone. + - Create a directory (with no spaces in the name) to contain the clone. - Enter the following command into the terminal: :: - + git clone https://github.com/kripken/emscripten.git - + Configuring Emscripten settings =============================== Almost all the compiler settings used by Emscripten are defined in the :ref:`compiler configuration file (~/.emscripten) `, a user-specific file located in the user's home directory. -Instructions for creating and manually configuring up this file are given in :ref:`configuring-emscripten-settings`. - +Instructions for creating and manually configuring up this file are given in :ref:`configuring-emscripten-settings`. + Validating the environment =============================== @@ -87,7 +87,7 @@ The best way to validate the environment is to build some code. Open the termina ./emcc tests/hello_world.cpp -If this builds **a.out.js** in the current directory, and you don't see any build errors in the terminal, Emscripten is good to go! +If this builds **a.out.js** in the current directory, and you don't see any build errors in the terminal, Emscripten is good to go! There are additional validation and troubleshooting instructions in the topic: :ref:`verifying-the-emscripten-environment`. diff --git a/site/source/docs/building_from_source/building_emscripten_from_source_on_mac_os_x.rst b/site/source/docs/building_from_source/building_emscripten_from_source_on_mac_os_x.rst index c683d6b5c481c..527de9c359f1d 100644 --- a/site/source/docs/building_from_source/building_emscripten_from_source_on_mac_os_x.rst +++ b/site/source/docs/building_from_source/building_emscripten_from_source_on_mac_os_x.rst @@ -30,27 +30,27 @@ These instructions explain how to install **all** the :ref:`required tools `_, or installing the git package won't succeed. - Install XCode and the XCode Command Line Tools (should already have been done). This will provide *git* to the system PATH (see `this stackoverflow post `_). - - Download and install git directly from http://git-scm.com/. + - Download and install git directly from http://git-scm.com/. #. Install *CMake* if you do not have it yet: - Download and install `CMake `_, and make sure it is available in PATH after installation. - -#. Install *node.js* from http://nodejs.org/ + +#. Install *node.js* from http://nodejs.org/ .. _getting-started-on-osx-install-python2: -#. Build :ref:`Fastcomp ` (LLVM + Clang) from source using :ref:`these instructions `. - +#. Build :ref:`Fastcomp ` (LLVM + Clang) from source using :ref:`these instructions `. + #. Clone the `kripken/emscripten `_ repository from Github. This repository contains the main compiler tool for compiling C/C++ programs to JavaScript: - - Create a directory (with no spaces in the name) to contain the clone. + - Create a directory (with no spaces in the name) to contain the clone. - Enter the following command into the terminal: :: - + git clone https://github.com/kripken/emscripten.git - - + + Configuring Emscripten settings @@ -58,8 +58,8 @@ Configuring Emscripten settings Almost all the compiler settings used by Emscripten are defined in the :ref:`compiler configuration file (~/.emscripten) `, a user-specific file located in the user's home directory. -Instructions for creating and manually configuring up this file are given in :ref:`configuring-emscripten-settings`. - +Instructions for creating and manually configuring up this file are given in :ref:`configuring-emscripten-settings`. + Validating the environment =============================== @@ -68,7 +68,7 @@ The best way to validate the environment is to build some code. Open the termina ./emcc tests/hello_world.cpp -If this builds **a.out.js** in the current directory, and you don't see any build errors in the terminal, Emscripten is good to go! +If this builds **a.out.js** in the current directory, and you don't see any build errors in the terminal, Emscripten is good to go! There are additional validation and troubleshooting instructions in the topic: :ref:`verifying-the-emscripten-environment`. diff --git a/site/source/docs/building_from_source/building_emscripten_from_source_on_windows.rst b/site/source/docs/building_from_source/building_emscripten_from_source_on_windows.rst index 8eaf99def7295..804df9ca8a979 100644 --- a/site/source/docs/building_from_source/building_emscripten_from_source_on_windows.rst +++ b/site/source/docs/building_from_source/building_emscripten_from_source_on_windows.rst @@ -4,7 +4,7 @@ Manually Building Emscripten on Windows ======================================= -This page contains basic instructions on how to manually build and configure Emscripten from source on a clean Windows box. +This page contains basic instructions on how to manually build and configure Emscripten from source on a clean Windows box. .. note:: The instructions clone from the main Emscripten repository (https://github.com/kripken/emscripten). :ref:`Contributors ` should instead clone from their own Emscripten fork, and submit changes as pull requests. @@ -27,12 +27,12 @@ These instructions explain how to install **all** the :ref:`required tools `_ (not 3.x): - For example `python-2.7.5.amd64.msi `_ (64-bit version) or `python-2.7.5.msi `_ (32-bit version). - - Add the path to the Python directory containing **Python.exe** to your PATH. - - - Paths are set by opening **System Settings | Advanced system properties**, clicking **Environment Variables** and selecting **PATH**. + - Add the path to the Python directory containing **Python.exe** to your PATH. + + - Paths are set by opening **System Settings | Advanced system properties**, clicking **Environment Variables** and selecting **PATH**. - Add the path to python, separated by semicolons: e.g. ``;C:/Python27/;`` or ``;C:/Python27/bin;`` (depending on the location of the exe). - - + + #. Install `node.js `_: - For example `node-v0.10.17-x64.msi `_ (64-bit version) or `node-v0.10.17-x86.msi `_ (32-bit version). @@ -46,24 +46,24 @@ These instructions explain how to install **all** the :ref:`required tools `_ (Java is optional, you only need it for Closure Compiler minification). -#. Build :ref:`Fastcomp ` (LLVM + Clang) from source using :ref:`these instructions `. - +#. Build :ref:`Fastcomp ` (LLVM + Clang) from source using :ref:`these instructions `. + #. Clone the `kripken/emscripten `_ repository from Github. This repository contains the main compiler tool for compiling C/C++ programs to JavaScript: - Using *Github for Windows*: - Launch the *GitHub for Windows* client. Click **Skip Setup** if you don't have a Github account. - (optional) Select **Options** from the gear menu, and customize the default storage directory. Ensure the path has no spaces. - In your web browser, open https://github.com/kripken/emscripten and press the **Clone in Windows** button. - + - Using the command line: - - Create a directory (with no spaces in the name) to contain the clone. + - Create a directory (with no spaces in the name) to contain the clone. - Enter the following command into the terminal: :: - + git clone https://github.com/kripken/emscripten.git - + Configuring Emscripten settings =============================== @@ -71,7 +71,7 @@ Almost all the compiler settings used by Emscripten are defined in the :ref:`com Instructions for creating and manually configuring this file are given in :ref:`configuring-emscripten-settings`. - + Validating the environment =============================== @@ -80,7 +80,7 @@ The best way to validate the environment is to build some code. Open the termina ./emcc tests/hello_world.cpp -If this builds **a.out.js** in the current directory, and you don't see any build errors in the terminal, Emscripten is good to go! +If this builds **a.out.js** in the current directory, and you don't see any build errors in the terminal, Emscripten is good to go! There are additional validation and troubleshooting instructions in the topic :ref:`verifying-the-emscripten-environment`. diff --git a/site/source/docs/building_from_source/building_emscripten_from_source_using_the_sdk.rst b/site/source/docs/building_from_source/building_emscripten_from_source_using_the_sdk.rst index e191230be6d79..9d98ed096be46 100644 --- a/site/source/docs/building_from_source/building_emscripten_from_source_using_the_sdk.rst +++ b/site/source/docs/building_from_source/building_emscripten_from_source_using_the_sdk.rst @@ -4,13 +4,13 @@ Building Emscripten from Source using the SDK ============================================= -The SDK can be used to fetch and build Emscripten from the latest sources in the Emscripten and :ref:`Fastcomp ` repositories. This allows you to obtain new features and defect fixes as soon as they are pushed to Github. +The SDK can be used to fetch and build Emscripten from the latest sources in the Emscripten and :ref:`Fastcomp ` repositories. This allows you to obtain new features and defect fixes as soon as they are pushed to Github. :ref:`Contributors ` can replace these sources with their own forks of Emscripten and *Fastcomp*, build them, and then use the normal process to pull changes into the main repository. The instructions below explain how use the SDK to build Emscripten from both the main repositories and your own forks (for all supported platforms). -.. note:: The SDK is recommended if you need to manage both SDK and source-built environments within the same user login. +.. note:: The SDK is recommended if you need to manage both SDK and source-built environments within the same user login. For :ref:`contributors ` the actual process of getting and building the sources for your fork is very similar to the :ref:`manual build process `. However the setup is easier because the SDK automatically installs and validates most of the needed tools and dependencies, and manages the compiler configuration file for you. @@ -18,7 +18,7 @@ The instructions below explain how use the SDK to build Emscripten from both the What you'll need ================ -First :ref:`download and install the SDK `. The SDK automatically installs and activates *most* of the :ref:`central-list-of-emscripten-tools-and-dependencies`. +First :ref:`download and install the SDK `. The SDK automatically installs and activates *most* of the :ref:`central-list-of-emscripten-tools-and-dependencies`. Then :ref:`download and install the compiler toolchain ` for your platform. @@ -31,13 +31,13 @@ Building Emscripten from the main repositories The :ref:`emsdk` controls which tool and SDK "targets" are installed and activated. To start using the latest upstream git development branch (``incoming``), run the following commands: :: - + # Clone, pull, and build the latest "sdk" Emscripten environment ./emsdk install sdk-incoming-64bit - + # Set the "incoming SDK" as the active version. - ./emsdk activate sdk-incoming-64bit - + ./emsdk activate sdk-incoming-64bit + .. todo:: **HamishW** Check whether the bug (https://github.com/juj/emsdk/issues/13) is fixed and remove the windows specific line if it is. If you want to use the upstream stable branch ``master``, replace ``-incoming-`` with ``-master-`` in the commands above. @@ -45,13 +45,13 @@ If you want to use the upstream stable branch ``master``, replace ``-incoming-`` .. note:: The SDK supplies a number of other "repository" targets. These targets are viewed by entering ``./emsdk list`` on the command prompt: - ``sdk-incoming-64bit`` is the target for a complete 64-bit Emscripten environment build from the incoming branch of the Emscripten and *Fastcomp* repositories. This is equivalent to: - + :: - + emsdk install clang-incoming-64bit node-0.10.17-64bit python-2.7.5.3-64bit java-7.45-64bit emscripten-incoming git-1.8.3 - + Other ``sdk-`` targets are provided for the master branch and 32bit builds. - + - ``emscripten-incoming`` and ``emscripten-master`` are targets for the Emscripten repository (only) - ``clang-incoming-64bit`` is the target for getting and building Fastcomp (only) from its repositories. Other ``clang-`` targets are provided for the master branch and 32bit builds. @@ -69,35 +69,35 @@ After installing the main repositories: #. Get your fork of Fastcomp: :: - + # From your emsdk "root" (where emsdk is installed). Navigate to the LLVM clone: cd clang/fastcomp/src - + # Add a git remote link to your LLVM repository fork git remote add myremote https://github.com/mygituseraccount/emscripten-fastcomp.git - + # Fetch the changes in the remote. git fetch myremote - + # Checkout the code in your LLVM fork to replace the original repository code git checkout -b myremote --track myremote/incoming - - + + #. Get your fork of Fastcomp-Clang: :: - + # Navigate to the tools/clang directory ( /clang/fastcomp/src/tools/clang ) cd tools/clang - + # Add a git remote link to your Clang repository fork git remote add myremote https://github.com/mygituseraccount/emscripten-fastcomp-clang.git - + # Fetch the changes in the remote. git fetch myremote - + # Checkout the code in your Clang fork to replace the original repository code git checkout -b myremote --track myremote/incoming @@ -105,21 +105,21 @@ After installing the main repositories: #. The SDK builds *Fastcomp* into a branch- and build-specific directory — in this case **/clang/fastcomp/build_incoming_64**. We need to build to the same location. - :: - + :: + #Navigate to the /clang/fastcomp/build_incoming_64 cd ../../../build_incoming_64 - - - + + + #. Configure the build using *cmake*: - + :: - + cmake .. -DCMAKE_BUILD_TYPE=Release -DLLVM_TARGETS_TO_BUILD="X86;JSBackend" -DLLVM_INCLUDE_EXAMPLES=OFF -DLLVM_INCLUDE_TESTS=OFF -DCLANG_INCLUDE_EXAMPLES=OFF -DCLANG_INCLUDE_TESTS=OFF - + .. note:: On Windows you will need Visual Studio 2012 or newer to build. - + #. Determine the number of available cores on your system (Emscripten can run many operations in parallel, so using more cores may have a significant impact on compilation time): - On Mac OS X you can get the number of cores using: **Apple menu | About this mac | System report**. The **Hardware overview** on the resulting dialog includes a *Total number of cores* entry. @@ -129,26 +129,26 @@ After installing the main repositories: #. Call *make* to build the sources, specifying the number of available cores: :: - + make -j1 - + At this point Fastcomp is compiled, and available in the same location as the original. #. Get your fork of Emscripten: :: - + # From your emsdk "root" (where emsdk is installed). Navigate to the Emscripten clone: cd emscripten/incoming - + # Add a git remote link to your Emscripten repository fork git remote add myremote https://github.com/mygituseraccount/emscripten.git - + # Fetch the changes in the remote. git fetch myremote - + # Checkout the code in your LLVM fork to replace the original repository code git checkout -b myremote --track myremote/incoming diff --git a/site/source/docs/building_from_source/building_fastcomp_manually_from_source.rst b/site/source/docs/building_from_source/building_fastcomp_manually_from_source.rst index ada90ba9e46e4..75345dfb85da7 100644 --- a/site/source/docs/building_from_source/building_fastcomp_manually_from_source.rst +++ b/site/source/docs/building_from_source/building_fastcomp_manually_from_source.rst @@ -4,7 +4,7 @@ Manually building Fastcomp from source ====================================== -:ref:`Fastcomp ` is the default compiler core for Emscripten. It is a new :term:`LLVM backend` that converts the LLVM Intermediate Representation (IR) created by *Clang* (from C/C++) into JavaScript. +:ref:`Fastcomp ` is the default compiler core for Emscripten. It is a new :term:`LLVM backend` that converts the LLVM Intermediate Representation (IR) created by *Clang* (from C/C++) into JavaScript. This article explains how you can build Fastcomp's sources using a fully manual process. @@ -26,56 +26,56 @@ Then follow the instructions for your platform showing how to :ref:`manually bui Building Fastcomp ================= -To build the Fastcomp code from source: +To build the Fastcomp code from source: - Create a directory to store the build. It doesn't matter where, because Emscripten gets the information from the :ref:`compiler configuration file (~/.emscripten) `. We show how to update this file later in these instructions: :: - + mkdir myfastcomp cd myfastcomp - -- Clone the fastcomp LLVM repository (https://github.com/kripken/emscripten-fastcomp): + +- Clone the fastcomp LLVM repository (https://github.com/kripken/emscripten-fastcomp): :: - + git clone https://github.com/kripken/emscripten-fastcomp - -- Clone the `kripken/emscripten-fastcomp-clang `_ repository into **emscripten-fastcomp/tools/clang**: + +- Clone the `kripken/emscripten-fastcomp-clang `_ repository into **emscripten-fastcomp/tools/clang**: :: - + cd emscripten-fastcomp git clone https://github.com/kripken/emscripten-fastcomp-clang tools/clang - .. warning:: You **must** clone it into a directory named **clang** as shown, so that :term:`Clang` is present in **tools/clang**! - + .. warning:: You **must** clone it into a directory named **clang** as shown, so that :term:`Clang` is present in **tools/clang**! + - Create a *build* directory (inside the **emscripten-fastcomp** directory) and then navigate into it: - + :: - + mkdir build cd build - + - Configure the build using *either* *cmake* or the *configure* script: - - - Using *cmake*: + + - Using *cmake*: :: - + cmake .. -DCMAKE_BUILD_TYPE=Release -DLLVM_TARGETS_TO_BUILD="X86;JSBackend" -DLLVM_INCLUDE_EXAMPLES=OFF -DLLVM_INCLUDE_TESTS=OFF -DCLANG_INCLUDE_EXAMPLES=OFF -DCLANG_INCLUDE_TESTS=OFF - + .. note:: On Windows add the ``-G "Visual Studio 10 Win64"`` directive to build using Visual Studio (Visual Studio 2011 and 2012 do NOT work). - - Using *configure* (Linux/Mac only): - + - Using *configure* (Linux/Mac only): + :: - + ../configure --enable-optimized --disable-assertions --enable-targets=host,js - + - Determine the number of available cores on your system (Emscripten can run many operations in parallel, so using more cores may have a significant impact on compilation time): - On Mac OS X you can get the number of cores using: **Apple menu | About this mac | More info | System report**. The **Hardware overview** on the resulting dialog includes a *Total number of cores* entry. @@ -85,25 +85,25 @@ To build the Fastcomp code from source: - Call *make* to build the sources, specifying the number of available cores: :: - + make -j4 - + .. note:: If the build completes successfully, *clang*, *clang++*, and a number of other files will be created in the release directory (**/build/Release/bin**). .. _llvm-update-compiler-configuration-file: - -- - - The final step is to update the :ref:`~/.emscripten ` file, specifying the location of *fastcomp* in the ``LLVM_ROOT`` variable. - + +- + + The final step is to update the :ref:`~/.emscripten ` file, specifying the location of *fastcomp* in the ``LLVM_ROOT`` variable. + .. note:: If you're building the **whole** of Emscripten from source, following the platform-specific instructions in :ref:`installing-from-source`, you won't yet have Emscripten installed. In this case, skip this step and return to those instructions. - If you already have an Emscripten environment (for example if you're building Fastcomp using the SDK), then set ``LLVM_ROOT`` to the location of the *clang* binary under the **build** directory. This will be something like **/build/Release/bin** or **/build/bin**: + If you already have an Emscripten environment (for example if you're building Fastcomp using the SDK), then set ``LLVM_ROOT`` to the location of the *clang* binary under the **build** directory. This will be something like **/build/Release/bin** or **/build/bin**: :: - + LLVM_ROOT='/home/ubuntu/yourpath/emscripten-fastcomp/build/bin' .. _building-fastcomp-from-source-branches: @@ -115,11 +115,11 @@ You should use the **same** branch (*incoming*, or *master*) for building all th - Emscripten: `emscripten `_. - Emscripten's LLVM fork: `emscripten-fastcomp `_. -- Emscripten's *Clang* fork `emscripten-fastcomp-clang `_. +- Emscripten's *Clang* fork `emscripten-fastcomp-clang `_. Mixing *incoming* and *master* branches may result in errors when building the three repositories. -Run ``emcc -v`` to check if the branches are synchronized. +Run ``emcc -v`` to check if the branches are synchronized. .. note:: ``emcc -v`` checks the code in the repositories, not the builds. Before building make sure that you fetch the latest changes to LLVM and Clang. diff --git a/site/source/docs/building_from_source/configuring_emscripten_settings.rst b/site/source/docs/building_from_source/configuring_emscripten_settings.rst index bab0440b642f8..ffdadb13c0966 100644 --- a/site/source/docs/building_from_source/configuring_emscripten_settings.rst +++ b/site/source/docs/building_from_source/configuring_emscripten_settings.rst @@ -18,25 +18,25 @@ Creating the compiler configuration file The settings file is created the first time a user runs :ref:`emcc ` (or any of the other Emscripten tools): 1. Navigate to the directory where you cloned the Emscripten repository. -2. Enter the command: +2. Enter the command: :: - + ./emcc --help You should get a ``Welcome to Emscripten!`` message. Behind the scenes, Emscripten generates a file called ``.emscripten`` in your home folder. - - -Emscripten makes a "best guess" at the correct locations for tools and updates the file appropriately. Where possible it will look for "system" apps (like Python and Java) and infer the location of the ``EMSCRIPTEN_ROOT`` (where :ref:`emcc ` is located) from the location of the command prompt. + + +Emscripten makes a "best guess" at the correct locations for tools and updates the file appropriately. Where possible it will look for "system" apps (like Python and Java) and infer the location of the ``EMSCRIPTEN_ROOT`` (where :ref:`emcc ` is located) from the location of the command prompt. The file will probably not include the link to :term:`Fastcomp` (``LLVM_ROOT``) as a manual source build can create this anywhere. Locating the compiler configuration file (.emscripten) ======================================================= -The settings file is created in the user's home directory: +The settings file is created in the user's home directory: - - On Linux and Mac OS X this file is named **~/.emscripten**, where ~ is the user's home directory. + - On Linux and Mac OS X this file is named **~/.emscripten**, where ~ is the user's home directory. .. note:: Files with the "." prefix are hidden by default. You may need to change your view settings to find the file. @@ -52,24 +52,24 @@ Compiler configuration file-format The file simply assigns paths to a number of *variables* representing the main tools used by Emscripten. For example, if the user cloned Emscripten to the **C:/Users/username/Documents/GitHub/emscripten** directory, then the file would have the line: :: EMSCRIPTEN_ROOT = 'C:/Users/username/Documents/GitHub/emscripten' - + The default *emcc* configuration file often gets the paths from environment variables if defined. If no variable is defined the system will also attempt to find "system executables". For example: :: PYTHON = os.path.expanduser(os.getenv('PYTHON', 'C:\\Python27\\python2.exe')) -You can find out the other variable names from the default *.emscripten* file or the :ref:`example here `. +You can find out the other variable names from the default *.emscripten* file or the :ref:`example here `. Editing the compiler configuration file ======================================= The compiler configuration file can be edited with the text editor of your choice. As stated above, most default settings are likely to be correct. If you're building manually from source, you are most likely to have to update the variable ``LLVM_ROOT`` (for :term:`Fastcomp`). - + #. Edit the variable ``LLVM_ROOT`` to point to the directory where you :ref:`built Fastcomp `. This path is likely to be something like **/build/Release/bin** or **/build/bin**, where ```` is the path to the directory where you cloned LLVM: - + :: - + LLVM_ROOT = 'os.path.expanduser(os.getenv('LLVM', '/home/ubuntu/a-path/emscripten-fastcomp/build/bin'))' .. note:: Use forward slashes! @@ -77,29 +77,29 @@ The compiler configuration file can be edited with the text editor of your choic #. Edit the variable ``TEMP_DIR`` to point to a valid path on your local system, e.g. ``TEMP_DIR = '/tmp'`` (``TEMP_DIR = 'c:/tmp'`` on Windows), and create that folder on the local filesystem if it doesn't exist. #. You *may* need to edit the variable ``EMSCRIPTEN_ROOT`` to point to the Emscripten root folder, e.g.: - + :: - + EMSCRIPTEN_ROOT = os.path.expanduser(os.getenv('EMSCRIPTEN', '/home/ubuntu/yourpath/emscripten')) # directory - + .. comment .. The settings are now correct in the configuration file, but the paths and environment variables are not set in the command prompt/terminal. **HamishW** Follow up with Jukka on this. - + After setting those paths, run ``emcc`` again. It should again perform the sanity checks to test the specified paths. There are further validation tests available at :ref:`verifying-the-emscripten-environment`. - - - - + + + + diff --git a/site/source/docs/building_from_source/index.rst b/site/source/docs/building_from_source/index.rst index 3e40d590bb506..ec96b7770f400 100644 --- a/site/source/docs/building_from_source/index.rst +++ b/site/source/docs/building_from_source/index.rst @@ -12,14 +12,14 @@ There are two approaches to building from source: - Using the SDK package manager to set up the environment and get the sources. The manual approach gives you a better understanding of the toolchain and all the build steps. The SDK method is easier because it automates and tests much of the setup process. It also enables a workflow where you can easily switch between source builds and SDK environments. - + .. note:: You can't use both approaches at the same time because the SDK overwrites manual changes made to the user's :ref:`compiler configuration file `. The instructions for building Emscripten using both methods are given below, followed by guidance on how to update the configuration file and validate your environment once it is complete: .. toctree:: :maxdepth: 1 - + toolchain_what_is_needed building_emscripten_from_source_using_the_sdk building_emscripten_from_source_on_linux diff --git a/site/source/docs/building_from_source/manually_integrating_emscripten_with_vs2010.rst b/site/source/docs/building_from_source/manually_integrating_emscripten_with_vs2010.rst index 39566ba51570e..19b07a06cd5de 100644 --- a/site/source/docs/building_from_source/manually_integrating_emscripten_with_vs2010.rst +++ b/site/source/docs/building_from_source/manually_integrating_emscripten_with_vs2010.rst @@ -6,7 +6,7 @@ Manually Integrating Emscripten into Visual Studio 2010 .. tip:: The :term:`vs-tool` plugin is installed automatically by the :term:`Windows NSIS Installer Emscripten SDK` if *Visual Studio 2010* is present on the target system at install time. These instructions are only needed if you're :ref:`manually building from source `, or for some other reason cannot use the SDK. -*vs-tool* is an *MSBuild* plugin that tells *Visual Studio* how to use the *Fastcomp* (LLVM + Clang) and Emscripten toolchain. The plugin allows existing Visual Studio **.sln** files to be directly built through the IDE using :ref:`emcc `. The Microsoft compiler property pages are replaced by *Fastcomp*- and *emcc*- specific options. +*vs-tool* is an *MSBuild* plugin that tells *Visual Studio* how to use the *Fastcomp* (LLVM + Clang) and Emscripten toolchain. The plugin allows existing Visual Studio **.sln** files to be directly built through the IDE using :ref:`emcc `. The Microsoft compiler property pages are replaced by *Fastcomp*- and *emcc*- specific options. The following instructions explain how to manually set up *vs-tool*. @@ -22,49 +22,49 @@ Install the vs-tool plugin #. Clone the juj/vs-tool repository from github: :: - + git clone https://github.com/juj/vs-tool #. Install the *vs-tool* plugin: #. Navigate to the **vs-tool** folder in the repository clone. #. Copy the folders **Clang** and **Emscripten** to **C:/Program Files (x86)/MSBuild/Microsoft.Cpp/v4.0/Platforms/**. - + #. Set up the required environment variables for *vs-tool*. #. Open the Environment Variables setting: - + - Windows 7: Open **Control Panel | System | Advanced System Settings | Environment Variables**. - Windows 8: Right click on the **Windows menu icon | System | Advanced System Settings | Environment Variables**. - + #. Create a new environment variable ``CLANG_BIN`` and set it to point to the folder where you built *Fastcomp* (path to **clang.exe**) — for example: - - :: - + + :: + SETX CLANG_BIN C:/Projects/llvm-build/bin/Release - + This variable is how *vs-tool* locates the folder containing your *Fastcomp* compiler. Alternatively, this path can be set on a per-project basis in the *Visual Studio project property* pages. #. Create a new environment variable ``EMSCRIPTEN`` and set it to point to the Emscripten git repository root folder (the path where you copied **emcc.exe** and the other exe files), for example: - + :: SETX EMSCRIPTEN C:/Projects/emscripten - + This variable is how *vs-tool* locates the Emscripten compiler. This path can also be overridden on a per-project basis in the Visual Studio property pages. #. Create a new environment variable ``EMCC_WEBBROWSER_EXE`` and set it to point to an executable you want to use to browse web pages generated using Emscripten via Visual Studio. This process is spawned when you tap **Start** (**Ctrl-F5**) in Visual Studio for an Emscripten-targeted project: - + :: SETX EMCC_WEBBROWSER_EXE C:/Program Files (x86)/Mozilla Firefox/firefox.exe -#. Now you are all set to start developing Emscripten-based projects using *Visual Studio*. +#. Now you are all set to start developing Emscripten-based projects using *Visual Studio*. Test the installation ====================== -To test the installation, open and build the Visual Studio solution file **/emscripten/tests/msvc10/tests_msvc10.sln**. +To test the installation, open and build the Visual Studio solution file **/emscripten/tests/msvc10/tests_msvc10.sln**. That project builds a few select samples from inside the Emscripten **tests/** folder ("hello world", "hello gles", etc.), and is a good verification of the integration. @@ -73,4 +73,4 @@ Learn more ========== To start working with Emscripten using the IDE, see :ref:`getting-started-emscripten-from-visual-studio`. - \ No newline at end of file + diff --git a/site/source/docs/building_from_source/toolchain_what_is_needed.rst b/site/source/docs/building_from_source/toolchain_what_is_needed.rst index 33d111fd49143..8777a8aef2ae6 100644 --- a/site/source/docs/building_from_source/toolchain_what_is_needed.rst +++ b/site/source/docs/building_from_source/toolchain_what_is_needed.rst @@ -27,9 +27,9 @@ A complete Emscripten environment requires the following tools. First test to se - :term:`Java` (1.6.0_31 or later). Java is optional. It is required to use the :term:`Closure Compiler` (in order to minify your code). - :term:`Git` client. Git is required if building tools from source. - :term:`Fastcomp` (Emscripten's fork of LLVM and Clang) - - The `Emscripten code `_, from GitHub + - The `Emscripten code `_, from GitHub -.. note: 64-bit versions of all needed dependencies are preferred, and may be required if you are building large projects. +.. note: 64-bit versions of all needed dependencies are preferred, and may be required if you are building large projects. .. note:: The `Spidermonkey shell `_ is also required if you want to run **100%** of the tests in the test suite. Most developers will not need this, and should instead use *node.js*. @@ -42,28 +42,28 @@ When building Emscripten from source code, whether "manually" or using the SDK, - Windows: Install `Visual Studio 2010 `_ and `cmake `_. You may also need `Microsoft Windows SDK for Windows 7 and .NET Framework 4 `_). - .. note:: - + .. note:: + - Visual Studio 2010 is required! Visual Studio 2012 and Visual Studio 2013 do not correctly compile :ref:`Fastcomp `. This issue will be fixed (eventually) when *Fastcomp* is migrated to use a LLVM 3.4 or later. - SDK users can also install and activate the MinGW compiler toolchain in order to build their own projects: :: - + emsdk install mingw-4.6.2-32bit emsdk activate mingw-4.6.2-32bit - + While this toolchain can in theory also be used to build :ref:`Fastcomp `, Visual Studio 2010 is recommended (by the LLVM development team). - + - Linux: Install *gcc* and *cmake*: - + :: - + #Install gcc sudo apt-get install build-essential # Install cmake sudo apt-get install cmake - + - Mac OS X: Install the *XCode Command Line Tools*: - Install XCode from the `Mac OS X App Store `_. @@ -76,7 +76,7 @@ When building Emscripten from source code, whether "manually" or using the SDK, Test which tools are installed ============================== -Some of the tools are pre-installed on the various platforms (for example, Python is always available on Linux builds). +Some of the tools are pre-installed on the various platforms (for example, Python is always available on Linux builds). You can check which tools are already present using the following commands: @@ -84,26 +84,26 @@ You can check which tools are already present using the following commands: # Check for Python python --version - + # Check for node.js on Linux nodejs --version - + # Check for node.js on Windows node --version - + # Check for node.js on Mac OS X node -v - + # Check for git git --version - + # Check for Java java -version # Check for gcc / g++ gcc --version g++ - + # Check for cmake cmake - + diff --git a/site/source/docs/building_from_source/verify_emscripten_environment.rst b/site/source/docs/building_from_source/verify_emscripten_environment.rst index f2259794222c7..929e6a451d627 100644 --- a/site/source/docs/building_from_source/verify_emscripten_environment.rst +++ b/site/source/docs/building_from_source/verify_emscripten_environment.rst @@ -13,17 +13,17 @@ Testing the environment Sanity tests ------------ -The first step in verifying the environment is to run Emscripten with the version command (``-v``). The command prints out information about the toolchain and runs some basic sanity tests to check that the required tools are available. +The first step in verifying the environment is to run Emscripten with the version command (``-v``). The command prints out information about the toolchain and runs some basic sanity tests to check that the required tools are available. -Open a terminal in the directory in which you installed Emscripten (on Windows open the :ref:`Emscripten Command Prompt `). Then call the :ref:`Emscripten Compiler Frontend (emcc) ` as shown: +Open a terminal in the directory in which you installed Emscripten (on Windows open the :ref:`Emscripten Command Prompt `). Then call the :ref:`Emscripten Compiler Frontend (emcc) ` as shown: :: ./emcc -v .. note:: On Windows, invoke the tool with **emsdk** instead of **./emsdk**. - -For example, the following output reports an installation where Java is missing: + +For example, the following output reports an installation where Java is missing: .. code-block:: javascript :emphasize-lines: 6 @@ -39,16 +39,16 @@ At this point you need to :ref:`Install and activate ` and reset it to a known good state. +First run ``./emcc -v`` and examine the output to find missing components. You can also try ``./emcc --clear-cache`` to empty the :ref:`compiler's internal cache ` and reset it to a known good state. .. _fixing-missing-components-emcc: -Installing missing components +Installing missing components ----------------------------- Missing tools can often be added using the :ref:`emsdk`. For example, to fix a warning that Java is missing, locate it in the repository, install it, and then set it as active: :: - + #List all the components. Look for the missing component (in this case "java-7.45-64bit") ./emsdk list - - #Install the missing component + + #Install the missing component ./emsdk install java-7.45-64bit - + #Set the component as active ./emsdk activate java-7.45-64bit diff --git a/site/source/docs/compiling/Building-Projects.rst b/site/source/docs/compiling/Building-Projects.rst index a202a09954a2d..8cce29fae4492 100644 --- a/site/source/docs/compiling/Building-Projects.rst +++ b/site/source/docs/compiling/Building-Projects.rst @@ -24,27 +24,27 @@ Consider the case where you normally build with the following commands: To build with Emscripten, you would instead use the following commands: .. code-block:: bash - + # Run emconfigure with the normal configure command as an argument. ./emconfigure ./configure - + # Run emmake with the normal make to generate linked LLVM bitcode. ./emmake make - + # Compile the linked bitcode generated by make (project.bc) to JavaScript. # 'project.bc' should be replaced with the make output for your project (e.g. 'yourproject.so') # [-Ox] represents build optimisations (discussed in the next section). ./emcc [-Ox] project.bc -o project.js - + *emconfigure* is called with the normal *configure* as an argument (in *configure*-based build systems), and *emmake* with *make* as an argument. If your build system doesn't use configure, then you can omit the first step. .. tip:: We recommend you call both *emconfigure* and *emmake* scripts in *configure*-based build systems. Whether you actually **need** to call both tools depends on the build system (some systems will store the environment variables in the configure step, and others will not). -*Make* generates linked LLVM bitcode. It does not automatically generate JavaScript during linking because all the files must be compiled using the :ref:`same optimizations and compiler options ` — and it makes sense to do this in the final conversion from bitcode to JavaScript. +*Make* generates linked LLVM bitcode. It does not automatically generate JavaScript during linking because all the files must be compiled using the :ref:`same optimizations and compiler options ` — and it makes sense to do this in the final conversion from bitcode to JavaScript. -.. note:: +.. note:: The file output from *make* might have a different suffix: **.a** for a static library archive, **.so** for a shared library, **.o** or **.bc** for object files (these file extensions are the same as *gcc* would use for the different types). Irrespective of the file extension, these files contain linked LLVM bitcode that *emcc* can compile into JavaScript in the final step. @@ -78,23 +78,23 @@ Consider the examples below: ./emcc -O1 a.cpp -o a.bc ./emcc -O2 b.cpp -o b.bc ./emcc -O3 a.bc b.bc -o project.js - + # Correct. The SAME LLVM and JavaScript options are provided at both levels. ./emcc -O2 a.cpp -o a.bc ./emcc -O2 b.cpp -o b.bc ./emcc -O2 a.bc b.bc -o project.js -The same rule applies when :ref:`building Emscripten using a build system ` — both LLVM and JavaScript must be optimized using the same settings. +The same rule applies when :ref:`building Emscripten using a build system ` — both LLVM and JavaScript must be optimized using the same settings. .. note:: Unfortunately each build-system defines its own mechanisms for setting compiler and optimization methods. **You will need to work out the correct approach to set the LLVM optimization flags for your system**. - - Some build systems have a flag like ``./configure --enable-optimize``. + - Some build systems have a flag like ``./configure --enable-optimize``. - You can control whether LLVM optimizations are run using ``--llvm-opts N`` where N is an integer in the range 0-3. Sending ``-O2 --llvm-opts 0`` to *emcc* during all compilation stages will disable LLVM optimizations but utilize JavaScript optimizations. This can be useful when debugging a build failure. JavaScript optimizations are specified in the final step, when you compile the linked LLVM bitcode to JavaScript. For example, to compile with :ref:`-O1 `: - + .. code-block:: bash # Compile the linked bitcode to JavaScript with -O1 optimizations. @@ -112,15 +112,15 @@ To make *Clang* and LLVM emit debug information in the bitcode files you need to .. note:: Each build-system defines its own mechanisms for setting debug flags. **To get Clang to emit LLVM debug information, you will need to work out the correct approach for your system**. - - Some build systems have a flag like ``./configure --enable-debug``. + - Some build systems have a flag like ``./configure --enable-debug``. The flags for emitting debug information when compiling from bitcode to JavaScript are specified as an *emcc* option in the final step: - + .. code-block:: bash # Compile the linked bitcode to JavaScript. # -g or -gN can be used to set the debug level (N) - ./emcc -g project.bc -o project.js + ./emcc -g project.bc -o project.js For more general information, see the topic :ref:`Debugging`. @@ -130,24 +130,24 @@ Using libraries Built-in support is available for a number of standard libraries: *libc*, *libc++* and *SDL*. These will automatically be linked when you compile code that uses them (you do not even need to add ``-lSDL``, but see below for more SDL-specific details). -If your project uses other libraries, for example `zlib `_ or *glib*, you will need to build and link them. The normal approach is to build the libraries to bitcode and then compile library and main program bitcode together to JavaScript. +If your project uses other libraries, for example `zlib `_ or *glib*, you will need to build and link them. The normal approach is to build the libraries to bitcode and then compile library and main program bitcode together to JavaScript. For example, consider the case where a project "project" uses a library "libstuff": .. code-block:: bash - + # Compile libstuff to bitcode ./emconfigure ./configure ./emmake make - + # Compile project to bitcode ./emconfigure ./configure ./emmake make - + # Compile the library and code together to HTML emcc project.bc libstuff.bc -o final.html - + It is also possible to link the bitcode libraries first, and then compile the combined **.bc** file to JavaScript: .. code-block:: bash @@ -157,7 +157,7 @@ It is also possible to link the bitcode libraries first, and then compile the co # Link together the bitcode files emcc project.bc libstuff.bc -o allproject.bc - + # Compile the combined bitcode to HTML emcc allproject.bc -o final.html @@ -241,7 +241,7 @@ The :ref:`Tutorial` showed how :ref:`emcc ` can be used to compile sing :: - # Generate a.out.js from C++. Can also take .ll (LLVM assembly) or .bc (LLVM bitcode) as input + # Generate a.out.js from C++. Can also take .ll (LLVM assembly) or .bc (LLVM bitcode) as input ./emcc src.cpp # Generate src.o containing LLVM bitcode. @@ -300,12 +300,12 @@ Troubleshooting =============== - Make sure to use bitcode-aware *llvm-ar* instead of *ar* (which may discard code). *emmake* and *emconfigure* set the AR environment variable correctly, but a build system might incorrectly hardcode *ar*. -- +- The compilation error ``multiply defined symbol`` indicates that the project has linked a particular static library multiple times. The project will need to be changed so that the problem library is linked only once. .. note:: You can use ``llvm-nm`` to see which symbols are defined in each bitcode file. - - One solution is to use the :ref:`building-projects-dynamic-linking-workaround` approach described above. This ensures that libraries are linked only once, in the final build stage. + + One solution is to use the :ref:`building-projects-dynamic-linking-workaround` approach described above. This ensures that libraries are linked only once, in the final build stage. diff --git a/site/source/docs/compiling/Deploying-Pages.rst b/site/source/docs/compiling/Deploying-Pages.rst index de49a614c1213..7e4e1b2fe6471 100644 --- a/site/source/docs/compiling/Deploying-Pages.rst +++ b/site/source/docs/compiling/Deploying-Pages.rst @@ -17,7 +17,7 @@ Additional build output files can also exist, depending on which features are us Developers can choose to output either to JavaScript or HTML. If outputting JavaScript (``emcc -o out.js``), the developer is expected to manually create the ``out.html`` main page in which the code is run in browsers. When targeting HTML with ``emcc -o out.html`` (the recommended build mode), Emscripten will generate the HTML shell file automatically. This shell file can be customized by using the ``emcc -o out.html --shell-file path/to/custom_shell.html`` linker directive. Copy the `default minimal HTML shell file `_ from Emscripten repository to your project tree to get a good starting template for a customized shell file. -The following sections offer tips for improving the site experience. +The following sections offer tips for improving the site experience. Optimizing Download Sizes ========================= diff --git a/site/source/docs/compiling/Running-html-files-with-emrun.rst b/site/source/docs/compiling/Running-html-files-with-emrun.rst index 3744e320e6eb6..2ea900a10996e 100644 --- a/site/source/docs/compiling/Running-html-files-with-emrun.rst +++ b/site/source/docs/compiling/Running-html-files-with-emrun.rst @@ -25,13 +25,13 @@ Quick how-to Using *emrun* is simple: -#. Rebuild your Emscripten application and add the ``--emrun`` :ref:`linker flag `. +#. Rebuild your Emscripten application and add the ``--emrun`` :ref:`linker flag `. - This flag injects code into the generated :ref:`Module` to enable capture of ``stdout``, ``stderr`` and ``exit()``. + This flag injects code into the generated :ref:`Module` to enable capture of ``stdout``, ``stderr`` and ``exit()``. .. note:: If you skip this step, you can still run any **.html** file with *emrun*, but the capture will not work. -#. Open a terminal, navigate to the build output directory, and call ``emrun page.html``. +#. Open a terminal, navigate to the build output directory, and call ``emrun page.html``. This will spawn a new web server to host the page and launch your default system browser to visit that page. *emrun* will block until the page calls ``exit(returncode)``, after which it will quit back to shell with the given process exit code. @@ -39,7 +39,7 @@ Using *emrun* is simple: Choosing the browser to run =========================== -The ``--browser `` command line option allows you to launch an HTML file using a particular browser, by specifying either its "browser alias" or the full path to its executable (if the flag is not specified, the default system browser is launched). +The ``--browser `` command line option allows you to launch an HTML file using a particular browser, by specifying either its "browser alias" or the full path to its executable (if the flag is not specified, the default system browser is launched). To enumerate the list of browser aliases on your system, use the ``--list_browsers`` command: @@ -65,7 +65,7 @@ You can pass the ``--browser `` option to launch with a given browser. Fo .. code-block:: bash emrun --browser firefox_nightly page.html - + To launch using a browser's filename use: .. code-block:: bash @@ -87,15 +87,15 @@ Security implications Controlling web server operation ================================ -The following command line flags control how *emrun* spawns the web server: +The following command line flags control how *emrun* spawns the web server: -- ``--no_server``: Do not launch a web server. The target file is run via the ``file://`` protocol, if possible. -- ``--serve_after_close``: Do not quit *emrun*; continue running the server even after the user closes the web browser. Use this flag when you want to visit the page multiple times or with different browsers during the same run. -- ``--serve_after_exit``: Do not quit *emrun*; continue running the server after the page finishes with a call to ``exit(returncode)``. -- ``--serve_root ``: Specify a custom directory to use as the root directory for the spawned web server. By default, the directory where the **.html** file resides is used. -- ``--port ``: Specify the web server TCP port. The default port is ``6931``. -- ``--silence_timeout ``: Specify the *emrun* silence timeout. If the application does not print anything to ``stdout`` or ``stderr`` in this many seconds, the page/browser is assumed to be hung, and *emrun* will quit. This is disabled by default. -- ``--timeout ``: Specify the *emrun* timeout. If the whole page run lasts longer than this many seconds, the page/browser is assumed to be hung, and *emrun* will quit. This is disabled by default. +- ``--no_server``: Do not launch a web server. The target file is run via the ``file://`` protocol, if possible. +- ``--serve_after_close``: Do not quit *emrun*; continue running the server even after the user closes the web browser. Use this flag when you want to visit the page multiple times or with different browsers during the same run. +- ``--serve_after_exit``: Do not quit *emrun*; continue running the server after the page finishes with a call to ``exit(returncode)``. +- ``--serve_root ``: Specify a custom directory to use as the root directory for the spawned web server. By default, the directory where the **.html** file resides is used. +- ``--port ``: Specify the web server TCP port. The default port is ``6931``. +- ``--silence_timeout ``: Specify the *emrun* silence timeout. If the application does not print anything to ``stdout`` or ``stderr`` in this many seconds, the page/browser is assumed to be hung, and *emrun* will quit. This is disabled by default. +- ``--timeout ``: Specify the *emrun* timeout. If the whole page run lasts longer than this many seconds, the page/browser is assumed to be hung, and *emrun* will quit. This is disabled by default. - ``--hostname ``: Specify the web server TCP hostname. The default hostname is ``localhost``. - ``--timeout_returncode ``: Specifies the process return code that *emrun* quits with if a page run timeout occurs. By default this is ``99999``. @@ -122,7 +122,7 @@ These command line flags allow you to clean up open browser processes before sta - ``--kill_start``: Terminate all instances of the target browser process before starting the run. Pass this flag to ensure that no old (hung) instances of the target browser process exist that could interfere with the current run. This is disabled by default. - ``--kill_exit``: Terminate all instances of the target browser process when *emrun* quits. Pass this flag to ensure that browser pages closed when the run is over. This is disabled by default. Note that it may be necessary to explicitly use the ``--browser=/path/to/browser`` command line option when using ``--kill_exit``, or otherwise the termination might not function properly. -.. warning:: These operations cause the browser process to be forcibly terminated. Any windows or tabs you have open will be closed, including any that might contain unsaved data. +.. warning:: These operations cause the browser process to be forcibly terminated. Any windows or tabs you have open will be closed, including any that might contain unsaved data. Running web pages in Firefox @@ -166,18 +166,18 @@ To set a Firefox browser pref, navigate to the page ``about:config`` in the brow Running web pages on an Android device ====================================== -*emrun* can automate browser-based testing on Android. +*emrun* can automate browser-based testing on Android. For this to work, you need to: -- Connect an Android phone to the local system via USB, with its developer mode enabled. There is no need to root the phone. -- Install the *adb* tool on the host system and make sure it is present in the ``PATH`` environment variable. -- Check that *adb* is working by calling ``adb devices`` to see that your device is listed. +- Connect an Android phone to the local system via USB, with its developer mode enabled. There is no need to root the phone. +- Install the *adb* tool on the host system and make sure it is present in the ``PATH`` environment variable. +- Check that *adb* is working by calling ``adb devices`` to see that your device is listed. - Install any browser apk to the device that you want to be able to run. -To run on Android, add the ``--android`` command line flag and use the ``--browser `` command line flag to explicitly choose the correct browser to run. +To run on Android, add the ``--android`` command line flag and use the ``--browser `` command line flag to explicitly choose the correct browser to run. -.. note:: Omitting ``--browser`` (to launch a default Android browser) is not supported. +.. note:: Omitting ``--browser`` (to launch a default Android browser) is not supported. .. note:: Running on Android will omit the ``--hostname`` option @@ -185,7 +185,7 @@ The following browser aliases have been tested and shown to work: ``firefox, fir The following browser aliases are also supported, but have known issues: -- ``opera_mini``: The browser launches, but for some reason it times out when trying to load any page. +- ``opera_mini``: The browser launches, but for some reason it times out when trying to load any page. - ``dolphin``: Works, but does not support WebGL. Otherwise, using *emrun* for browser-based testing on Android is the same as when testing on the host system. diff --git a/site/source/docs/compiling/index.rst b/site/source/docs/compiling/index.rst index d0d0f62397040..7a4558dd6e925 100644 --- a/site/source/docs/compiling/index.rst +++ b/site/source/docs/compiling/index.rst @@ -4,7 +4,7 @@ Compiling and Running Projects ============================== -This section contains topics about building projects and running the output. +This section contains topics about building projects and running the output. - :ref:`Building-Projects` shows how to use :ref:`emccdoc` as a drop-in replacement for *gcc* in your existing project. - :ref:`Running-html-files-with-emrun` explains how to use *emrun* to run generated HTML pages in a locally launched web server. @@ -13,7 +13,7 @@ This section contains topics about building projects and running the output. .. toctree:: :hidden: - + Building-Projects Running-html-files-with-emrun Deploying-Pages diff --git a/site/source/docs/contributing/contributing.rst b/site/source/docs/contributing/contributing.rst index dabd0e2557250..85592ef535e2f 100644 --- a/site/source/docs/contributing/contributing.rst +++ b/site/source/docs/contributing/contributing.rst @@ -4,7 +4,7 @@ Contributing ============ -Anyone can contribute to Emscripten — if you find it useful and want to help improve the project, follow the suggestions below. +Anyone can contribute to Emscripten — if you find it useful and want to help improve the project, follow the suggestions below. Feel free to file :ref:`bug reports `, :ref:`join the discussion ` and share your own ideas with the community! @@ -12,7 +12,7 @@ Feel free to file :ref:`bug reports `, :ref:`join the discussion `_. Many issues can be resolved without an in-depth knowledge of compiler internals, and this is a great way to learn more about the project. +A good starting point is to work on the `open issues on Github `_. Many issues can be resolved without an in-depth knowledge of compiler internals, and this is a great way to learn more about the project. .. tip:: We really appreciate your help. Every existing issue closed means more time for the core contributors to work on new features, optimizations and other enhancements. diff --git a/site/source/docs/contributing/developers_guide.rst b/site/source/docs/contributing/developers_guide.rst index fda4b17c387cb..ae5bf35faf947 100644 --- a/site/source/docs/contributing/developers_guide.rst +++ b/site/source/docs/contributing/developers_guide.rst @@ -4,7 +4,7 @@ Developer's Guide ================= -This article provides information that is relevant to people working on Emscripten itself, as opposed to those that use Emscripten in their own projects. +This article provides information that is relevant to people working on Emscripten itself, as opposed to those that use Emscripten in their own projects. .. tip:: The information will be less relevant if you're just using Emscripten, but may still be of interest. @@ -36,13 +36,13 @@ When :ref:`building Emscripten from source ` you should Submitting patches ================== -Patches should be submitted as *pull requests* to the **incoming** branch. +Patches should be submitted as *pull requests* to the **incoming** branch. .. note:: Before submitting your first patch, add yourself to the `AUTHORS `_ file. By doing so, you agree to license your code under the project's :ref:`open source licenses (MIT/LLVM) `. When submitting patches, please: -- Make pull requests to **incoming**, not master. +- Make pull requests to **incoming**, not master. - Do not include merge commits in pull requests; include only commits with the new relevant code. - :ref:`Run all the automatic tests ` and make sure they pass. Some tests might not be required for very simple patches (for example, when just adding tests for new library functions). If you don't have time to run all the tests, at least run a random subset of them (say, 100), see that link. - "Add an automatic test to `tests/runner.py `_ if you add any new functionality or fix a bug. @@ -52,7 +52,7 @@ When submitting patches, please: Code reviews ============ -`@kripken `_ reviews all pull requests before merging. +`@kripken `_ reviews all pull requests before merging. Exceptions are sub-projects that are 'owned' by other people. These owners can push to incoming directly: @@ -81,7 +81,7 @@ The :ref:`Emscripten Compiler Frontend (emcc) ` is a python script that Emscripten Test Suite ===================== -Emscripten has a :ref:`comprehensive test suite `, which covers virtually all Emscripten functionality. These tests must all pass when you are :ref:`submitting patches `. +Emscripten has a :ref:`comprehensive test suite `, which covers virtually all Emscripten functionality. These tests must all pass when you are :ref:`submitting patches `. See also ======== diff --git a/site/source/docs/contributing/index.rst b/site/source/docs/contributing/index.rst index a4f81cbb22c7a..1faeb81071f00 100644 --- a/site/source/docs/contributing/index.rst +++ b/site/source/docs/contributing/index.rst @@ -4,15 +4,15 @@ Contributing to Emscripten ========================== -This section contains articles that are relevant to anyone who wants to contribute to Emscripten and help improve the project. +This section contains articles that are relevant to anyone who wants to contribute to Emscripten and help improve the project. -- :ref:`contributing` provides an introduction to contributing, along with a few ideas for how you can help. +- :ref:`contributing` provides an introduction to contributing, along with a few ideas for how you can help. - The :ref:`Developer's-Guide` contains contributor-relevant information, covering compiler operation and submitting patches to the Emscripten repositories. - :ref:`emscripten-authors` is a list of all Emscripten contributors. If you contribute you must accept the project’s :ref:`open source licenses (MIT/LLVM) ` and add yourself to the list! .. toctree:: :hidden: - + contributing developers_guide AUTHORS diff --git a/site/source/docs/debugging/CyberDWARF.rst b/site/source/docs/debugging/CyberDWARF.rst index f3bd2a9b89570..1b1999d22eb2c 100644 --- a/site/source/docs/debugging/CyberDWARF.rst +++ b/site/source/docs/debugging/CyberDWARF.rst @@ -36,10 +36,10 @@ This small example will show how to use CyberDWARF to visualize a simple struct. TinyStruct example; example.chars = "Hello World"; example.len = strlen(example.chars); - + printf("%p\n", &example); - EM_ASM({ debugger }); - + EM_ASM({ debugger }); + return 0; } @@ -80,11 +80,11 @@ API .. js:function:: Module['cyberdwarf'].initialize_debugger Called to load the CyberDWARF file for the script. - + .. js:function:: Module['cyberdwarf'].set_current_function(name) Sets the function to lookup variable type by ``name``. Supports either C/mangled name or minified name from symbol file. - + .. js:function:: Module['cyberdwarf'].decode_var_by_var_name(address, name, depth) Looks up the type given by variable ``name`` in the current function, then dumps a JSON formatted representation of that type at ``address`` up to ``depth`` *(defaults to 1)* diff --git a/site/source/docs/getting_started/FAQ.rst b/site/source/docs/getting_started/FAQ.rst index 1552175ef1e2b..d910b9543ed62 100644 --- a/site/source/docs/getting_started/FAQ.rst +++ b/site/source/docs/getting_started/FAQ.rst @@ -47,17 +47,17 @@ Emscripten makes some trade-offs that make the generated code faster and smaller The main tips for improving build time are: - Create fully optimized builds less frequently — use ``-O0`` during frequent development iterations (or don't specify an optimization level). - - - Compiling with higher levels of optimization can in some cases be noticeably slower: ``-O2`` is slower than ``-O1``, which is in turn slower than ``-O0``. + + - Compiling with higher levels of optimization can in some cases be noticeably slower: ``-O2`` is slower than ``-O1``, which is in turn slower than ``-O0``. - Compiling with ``-O3`` is **especially** slow — this can be mitigated by also enabling ``-s AGGRESSIVE_VARIABLE_ELIMINATION=1`` (removing variables makes the ``-O3`` regalloc easier). - + - Compile without :ref:`line number debug information ` (use ``-O1`` or ``-g0`` instead of ``-g``): - Currently builds with line-number debug information are slow (see issue `#216 `_). Stripping the debug information significantly improves compile times. - -- Compile on a machine with more cores: - - Emscripten can run some passes in parallel (specifically, the JavaScript optimisations). Increasing the number of cores results in an almost linear improvement. +- Compile on a machine with more cores: + + - Emscripten can run some passes in parallel (specifically, the JavaScript optimisations). Increasing the number of cores results in an almost linear improvement. - Emscripten will automatically use more cores if they are available. You can control how many cores are used with ``EMCC_CORES=N`` (this is useful if you have many cores but relatively less memory). - Make sure that the native optimizer is being used, which greatly speeds up optimized builds as of 1.28.2. ``EMCC_DEBUG=1`` output should not report errors about the native optimizer failing to build or not being used because of a previous failed build (if it previously failed, do ``emcc --clear-cache`` then compile your file again, and the optimizer will be automatically rebuilt). @@ -68,7 +68,7 @@ The main tips for improving build time are: - You don't need to link into a single bitcode file yourself, you can call the final ``emcc`` command that emits JS with a list of files. ``emcc`` can then defer linking and avoid an intermediary step, if possible (this optimization is disabled by LTO and by `EMCC_DEBUG=2`). - + Why does my code run slowly? ============================ @@ -105,7 +105,7 @@ Why does my code fail to compile with an error message about inline assembly (or Emscripten cannot compile inline assembly code (because it is CPU specific, and Emscripten is not a CPU emulator). -You will need to find where inline assembly is used, and disable it or replace it with platform-independent code. +You will need to find where inline assembly is used, and disable it or replace it with platform-independent code. .. note:: Emscripten automatically unsets the following ``#define`` values, as these are commonly set in projects to enable platform dependent code (inline assembly): @@ -122,7 +122,7 @@ Why does my HTML app hang? The browser event model uses *co-operative multitasking* — each event has a "turn" to run, and must then return control to the browser event loop so that other events can be processed. A common cause of HTML pages hanging is JavaScript that does not complete and return control to the browser. -Graphical C++ apps typically have an infinite main loop in which event handling, processing and rendering is done, followed by a delay to keep the frame-rate right (``SDL_DELAY`` in :term:`SDL` apps). As the main loop does not complete (is infinite) it cannot return control to the browser, and the app will hang. +Graphical C++ apps typically have an infinite main loop in which event handling, processing and rendering is done, followed by a delay to keep the frame-rate right (``SDL_DELAY`` in :term:`SDL` apps). As the main loop does not complete (is infinite) it cannot return control to the browser, and the app will hang. Apps that use an infinite main loop should be re-coded to put the actions for a single iteration of the loop into a single "finite" function. In the native build this function can be run in an infinite loop as before. In the Emscripten build it is set as the :ref:`main loop function ` and will be called by the browser at a specified frequency. @@ -134,14 +134,14 @@ There is more information on this topic in :ref:`emscripten-runtime-environment` How do I run an event loop? =========================== -To run a C function repeatedly, use :c:func:`emscripten_set_main_loop` (this is discussed in :ref:`emscripten-runtime-environment`). The related functions in :ref:`emscripten.h ` are also useful, allowing you to add events that block the main loop, etc. +To run a C function repeatedly, use :c:func:`emscripten_set_main_loop` (this is discussed in :ref:`emscripten-runtime-environment`). The related functions in :ref:`emscripten.h ` are also useful, allowing you to add events that block the main loop, etc. To respond to browser events use the SDL API in the normal way. There are examples in the SDL tests (search for SDL in **tests/runner.py**). See also: :ref:`faq-my-html-app-hangs` - + Why doesn't my SDL app work? ============================= @@ -159,7 +159,7 @@ There is a set of libraries ported to Emscripten for convenient use, Emscripten Another option is to implement needed C APIs as JavaScript libraries (see ``--js-library`` in :ref:`emcc ` and :ref:`implement-c-in-javascript`). Emscripten itself does this for *libc* (not including *malloc*) and :term:`SDL` (but not *libc++* or *malloc*). -.. note:: +.. note:: - Unlike other compilers, you don't need ``-lSDL`` to include SDL (specifying it will do no harm). - In the specific case of *Boost*, if you only need the boost headers then you don't need to compile anything. @@ -196,7 +196,7 @@ How can I tell when the page is fully loaded and it is safe to call compiled fun Calling a compiled function before a page has fully loaded can result in an error, if the function relies on files that may not be present (for example the :ref:`.mem ` file and :ref:`preloaded ` files are loaded asynchronously, and therefore if you just place some JS that calls compiled code in a ``--post-js``, that code will be called synchronously at the end of the combined JS file, potentially before the asynchronous event happens, which is bad). -The easiest way to find out when loading is complete is to add a ``main()`` function, and within it call a JavaScript function to notify your code that loading is complete. +The easiest way to find out when loading is complete is to add a ``main()`` function, and within it call a JavaScript function to notify your code that loading is complete. .. note:: The ``main()`` function is called after startup is complete as a signal that it is safe to call any compiled method. @@ -253,17 +253,17 @@ The crucial thing is that ``Module`` exists, and has the property ``onRuntimeIni Why do functions in my C/C++ source code vanish when I compile to JavaScript, and/or I get ``No functions to process``? ======================================================================================================================= -Emscripten does dead code elimination of functions that are not called from the compiled code. While this does minimize code size, it can remove functions that you plan to call yourself (outside of the compiled code). +Emscripten does dead code elimination of functions that are not called from the compiled code. While this does minimize code size, it can remove functions that you plan to call yourself (outside of the compiled code). To make sure a C function remains available to be called from normal JavaScript, it must be added to the `EXPORTED_FUNCTIONS `_ using the *emcc* command line. For example, to prevent functions ``my_func()`` and ``main()`` from being removed/renamed, run *emcc* with: :: ./emcc -s EXPORTED_FUNCTIONS="['_main', '_my_func']" ... -.. note:: +.. note:: `_main` should be in the export list, as in that example, if you have a `main()` function. Otherwise, it will be removed as dead code; there is no special logic to keep `main()` alive by default. -.. note:: +.. note:: `EXPORTED_FUNCTIONS` affects compilation to JavaScript. If you first compile to an object file, then compile the object to JavaScript, you need that option on the second command. @@ -273,17 +273,17 @@ If your function is used in other functions, LLVM may inline it and it will not void EMSCRIPTEN_KEEPALIVE yourCfunc() {..} `EMSCRIPTEN_KEEPALIVE` also exports the function, as if it were on `EXPORTED_FUNCTIONS`. - -.. note:: + +.. note:: - All functions not kept alive through ``EXPORTED_FUNCTIONS`` or :c:type:`EMSCRIPTEN_KEEPALIVE` will potentially be removed. Make sure you keep the things you need alive using one or both of those methods. - + - Exported functions need to be C functions (to avoid C++ name mangling). - Decorating your code with :c:type:`EMSCRIPTEN_KEEPALIVE` can be useful if you don't want to have to keep track of functions to export explicitly, and when these exports do not change. It is not necessarily suitable for exporting functions from other libraries — for example it is not a good idea to decorate and recompile the source code of the C standard library. If you build the same source in multiple ways and change what is exported, then managing exports on the command line is easier. - - Running *emcc* with ``-s LINKABLE=1`` will also disable link-time optimizations and dead code elimination. This is not recommended as it makes the code larger and less optimized. - + - Running *emcc* with ``-s LINKABLE=1`` will also disable link-time optimizations and dead code elimination. This is not recommended as it makes the code larger and less optimized. + Another possible cause of missing code is improper linking of ``.a`` files. The ``.a`` files link only the internal object files needed by previous files on the command line, so the order of files matters, and this can be surprising. If you are linking ``.a`` files, make sure they are at the end of the list of files, and in the right order amongst themselves. Alternatively, just use ``.so`` files instead in your project. .. tip:: It can be useful to compile with ``EMCC_DEBUG=1`` set for the environment (``EMCC_DEBUG=1 emcc ...`` on Linux, ``set EMMCC_DEBUG=1`` on Windows). This splits up the compilation steps and saves them in ``/tmp/emscripten_temp``. You can then see at what stage the code vanishes (you will need to do ``llvm-dis`` on the bitcode stages to read them, or ``llvm-nm``, etc.). @@ -299,11 +299,11 @@ The :term:`Closure Compiler` will minify the File Server API code. Code that use Why does my code break and gives odd errors when using ``-O2 --closure 1``? =========================================================================== -The :term:`Closure Compiler` minifies variable names, which results in very short variable names like ``i``, ``j``, ``xa``, etc. If other code declares variables with the same names in global scope, this can cause serious problems. +The :term:`Closure Compiler` minifies variable names, which results in very short variable names like ``i``, ``j``, ``xa``, etc. If other code declares variables with the same names in global scope, this can cause serious problems. This is likely to be the cause if you can successfully run code compiled with ``-O2`` set and ``--closure`` unset. -One solution is to stop using small variable names in the global scope (often this is a mistake — forgetting to use ``var`` when assigning to a variable). +One solution is to stop using small variable names in the global scope (often this is a mistake — forgetting to use ``var`` when assigning to a variable). Another alternative is to wrap the generated code (or your other code) in a closure, as shown: @@ -336,9 +336,9 @@ Another possible cause of this error is the lack of ``make``, which is necessary Why does running LLVM bitcode generated by emcc through **lli** break with errors about ``impure_ptr``? ======================================================================================================= -.. note:: :term:`lli` is not maintained, and has odd errors and crashes. We do include **tools/nativize_llvm.py** (which compiles bitcode to a native executable) but it will also hit the ``impure_ptr`` error. +.. note:: :term:`lli` is not maintained, and has odd errors and crashes. We do include **tools/nativize_llvm.py** (which compiles bitcode to a native executable) but it will also hit the ``impure_ptr`` error. -The issue is that *newlib* uses ``impure_ptr`` code, while *glibc* uses something else. The result is that bitcode built with the Emscripten will not run locally unless your machine uses *newlib* (basically, only embedded systems). +The issue is that *newlib* uses ``impure_ptr`` code, while *glibc* uses something else. The result is that bitcode built with the Emscripten will not run locally unless your machine uses *newlib* (basically, only embedded systems). The ``impure_ptr`` error only occurs during explicit use of ``stdout`` etc., so ``printf(..)`` will work, but ``fprintf(stdout, ..)`` will not. **Usually it is simple to modify your code to avoid this problem.** @@ -346,7 +346,7 @@ The ``impure_ptr`` error only occurs during explicit use of ``stdout`` etc., so Why do I get a stack size error when optimizing: ``RangeError: Maximum call stack size exceeded`` or similar? ============================================================================================================= -You may need to increase the stack size for :term:`node.js`. +You may need to increase the stack size for :term:`node.js`. On Linux and Mac OS X, you can just do ``NODE_JS = ['node', '--stack_size=8192']`` in the :ref:`compiler-configuration-file`. On Windows, you will also need ``--max-stack-size=8192``, and also run ``editbin /stack:33554432 node.exe``. @@ -356,7 +356,7 @@ Why do I get ``error: cannot compile this aggregate va_arg expression yet`` and This is a limitation of the asm.js target in :term:`Clang`. This code is not currently supported. - + Why does building from source fail during linking (at 100%)? ============================================================ @@ -385,7 +385,7 @@ So by using MODULARIZE and creating a proper Module object for each module, and Another option is to use an iframe, in which case the default HTML shell will just work, as each will have its own canvas, etc. But this is overkill for small programs, which can run modularly as described above. - + Why the weird name for the project? =================================== diff --git a/site/source/docs/getting_started/Tutorial.rst b/site/source/docs/getting_started/Tutorial.rst index 0cabc2450b8bd..cb9abd7746e0f 100644 --- a/site/source/docs/getting_started/Tutorial.rst +++ b/site/source/docs/getting_started/Tutorial.rst @@ -19,12 +19,12 @@ Emscripten is accessed using the :ref:`emccdoc`. This script invokes all the oth For the next section you will need to open a command prompt: -- On Linux or Mac OS X, open a *Terminal*. +- On Linux or Mac OS X, open a *Terminal*. - On Windows open the :ref:`Emscripten Command Prompt `, a command prompt that has been pre-configured with the correct system paths and settings to point to the :term:`active ` Emscripten tools. To access this prompt, type **Emscripten** in the Windows 8 start screen, and then select the **Emscripten Command Prompt** option. Navigate with the command prompt to the :term:`SDK root directory` for your target SDK. This is an SDK-version-specific folder below the :term:`emsdk root directory`, for example **/emscripten/1.20.0/**. -.. note:: The tests should be compiled from the "SDK Root" directory. This is required because some tests load files, and the locations of these files within Emscripten's virtual file system root is relative to the current directory at build time. +.. note:: The tests should be compiled from the "SDK Root" directory. This is required because some tests load files, and the locations of these files within Emscripten's virtual file system root is relative to the current directory at build time. Verifying Emscripten @@ -32,7 +32,7 @@ Verifying Emscripten If you haven't run Emscripten before, run it now with: :: - ./emcc -v + ./emcc -v If the output contains warnings about missing tools, see :ref:`verifying-the-emscripten-environment` for debugging help. Otherwise continue to the next sections where we'll build some code. @@ -84,42 +84,42 @@ The source code for the second example is given below: .. include:: ../../../../tests/hello_world_sdl.cpp :literal: - + .. _tutorial-files: Using files =========== -.. note:: Your C/C++ code can access files using the normal libc stdio API (``fopen``, ``fclose``, etc.) +.. note:: Your C/C++ code can access files using the normal libc stdio API (``fopen``, ``fclose``, etc.) JavaScript is usually run in the sandboxed environment of a web browser, without direct access to the local file system. Emscripten simulates a file system that you can access from your compiled C/C++ code using the normal libc stdio API. -Files that you want to access should be :ref:`preloaded ` or :ref:`embedded ` into the virtual file system. Preloading (or embedding) generates a virtual file system that corresponds to the file system structure at *compile* time, *relative to the current directory*. +Files that you want to access should be :ref:`preloaded ` or :ref:`embedded ` into the virtual file system. Preloading (or embedding) generates a virtual file system that corresponds to the file system structure at *compile* time, *relative to the current directory*. The `hello_world_file.cpp `_ example shows how to load a file (both the test code and the file to be loaded shown below): .. include:: ../../../../tests/hello_world_file.cpp :literal: - + .. include:: ../../../../tests/hello_world_file.txt :literal: .. note:: The example expects to be able to load a file located at **tests/hello_world_file.txt**: :: FILE *file = fopen("tests/hello_world_file.txt", "rb"); - + We compile the example from the directory "above" **tests** to ensure that virtual filesystem is created with the correct structure relative to the compile-time directory. - + The following command is used to specify a data file to :ref:`preload ` into Emscripten's virtual file system — before running any compiled code. This approach is useful because Browsers can only load data from the network asynchronously (except in Web Workers) while a lot of native code uses synchronous file system access. Preloading ensures that the asynchronous download of data files is complete (and the file is available) before compiled code has the opportunity to access the Emscripten file system. :: ./emcc tests/hello_world_file.cpp -o hello.html --preload-file tests/hello_world_file.txt - -Run the above command, then open **hello.html** in the *Firefox web browser* to see the data from **hello_world_file.txt** being displayed. + +Run the above command, then open **hello.html** in the *Firefox web browser* to see the data from **hello_world_file.txt** being displayed. .. note:: Unfortunately *Chrome* and *Internet Explorer* do not support ``file://`` :term:`XHR` requests, and can't directly load the local file in which preloaded data is stored. For these browsers you'll need to serve the files using a webserver. The easiest way to do this is to use the python **SimpleHTTPServer** (in the current directory do ``python -m SimpleHTTPServer 8080`` and then open ``http://localhost:8080/hello.html``). @@ -133,7 +133,7 @@ Emscripten, like *gcc* and *clang*, generates unoptimized code by default. You c ./emcc -O1 tests/hello_world.cpp -The "hello world" code created in **a.out.js** doesn't really need to be optimized, so you won't see a difference in speed when compared to the unoptimized version. +The "hello world" code created in **a.out.js** doesn't really need to be optimized, so you won't see a difference in speed when compared to the unoptimized version. However, you can compare the generated code to see the differences. ``-O1`` applies several minor optimizations and removes some runtime assertions. For example, ``printf`` will have been replaced by ``puts`` in the generated code. @@ -149,7 +149,7 @@ For more information about compiler optimization options see :ref:`Optimizing-Co Emscripten Test Suite and Benchmarks ==================================== -Emscripten has a comprehensive test suite, which covers virtually all Emscripten functionality. These tests are an excellent resource for developers as they provide practical examples of most features, and are known to build successfully on the master branch. +Emscripten has a comprehensive test suite, which covers virtually all Emscripten functionality. These tests are an excellent resource for developers as they provide practical examples of most features, and are known to build successfully on the master branch. See :ref:`emscripten-test-suite` for more information. diff --git a/site/source/docs/getting_started/bug_reports.rst b/site/source/docs/getting_started/bug_reports.rst index 34063b04272f3..c0d7d71e606d2 100644 --- a/site/source/docs/getting_started/bug_reports.rst +++ b/site/source/docs/getting_started/bug_reports.rst @@ -32,10 +32,10 @@ Site and documentation bugs Documentation (site) bugs should be filed in the same `Issue Tracker `_. -Include relevant information including: +Include relevant information including: - The URL and title of the affected page(s). - A description of the problem. - Suggestions for a possible solution. -.. tip:: The `Page bug `_ link on the bottom-right of every page opens the Issue Tracker pre-seeded with the current page URL and title. +.. tip:: The `Page bug `_ link on the bottom-right of every page opens the Issue Tracker pre-seeded with the current page URL and title. diff --git a/site/source/docs/getting_started/downloads.rst b/site/source/docs/getting_started/downloads.rst index 2ae157e4f614d..9f9d2a8445fc0 100644 --- a/site/source/docs/getting_started/downloads.rst +++ b/site/source/docs/getting_started/downloads.rst @@ -26,8 +26,8 @@ Linux and Mac OS X ------------------ .. _emscripten-sdk-linux-osx: - -- `Emscripten SDK for Linux and OS X `_ (emsdk-portable.tar.gz) + +- `Emscripten SDK for Linux and OS X `_ (emsdk-portable.tar.gz) A tar.gz archive package of the SDK that does not require system installation privileges. To install, follow the :ref:`platform-specific notes ` and the :ref:`general instructions `. .. _sdk-installation-instructions: @@ -41,25 +41,25 @@ Install or update the SDK using the following steps: 1. Download and unzip the SDK package to a directory of your choice. This directory will contain the Emscripten SDK. #. Open a command prompt inside the SDK directory and run the following :ref:`emsdk ` commands to get the latest tools from Github and set them as :term:`active `: - + :: # Fetch the latest registry of available tools. ./emsdk update - + # Download and install the latest SDK tools. ./emsdk install latest # Make the "latest" SDK "active" for the current user. (writes ~/.emscripten file) ./emsdk activate latest - + # Activate PATH and other environment variables in the current terminal source ./emsdk_env.sh - .. note:: On Windows, run ``emsdk`` instead of ``./emsdk``, and ``emsdk_env.bat`` instead of ``source ./emsdk_env.sh``. + .. note:: On Windows, run ``emsdk`` instead of ``./emsdk``, and ``emsdk_env.bat`` instead of ``source ./emsdk_env.sh``. + +If you change the location of the SDK (e.g. take it to another computer on an USB), re-run the ``./emsdk activate latest`` and ``source ./emsdk_env.sh`` commands. -If you change the location of the SDK (e.g. take it to another computer on an USB), re-run the ``./emsdk activate latest`` and ``source ./emsdk_env.sh`` commands. - .. _platform-notes-installation_instructions-SDK: Platform-specific notes @@ -79,13 +79,13 @@ These instructions explain how to install **all** the :ref:`required tools `_, or installing the git package won't succeed. - Install XCode and the XCode Command Line Tools (should already have been done). This will provide *git* to the system PATH (see `this stackoverflow post `_). - - Download and install git directly from http://git-scm.com/. + - Download and install git directly from http://git-scm.com/. #. Install *cmake* if you do not have it yet: - Download and install latest CMake from `Kitware CMake downloads `_. - -#. Install *node.js* from http://nodejs.org/ + +#. Install *node.js* from http://nodejs.org/ .. _getting-started-on-osx-install-python2: @@ -94,38 +94,38 @@ Linux .. note:: *Emsdk* does not install any tools to the system, or otherwise interact with Linux package managers. All file changes are done inside the **emsdk/** directory. -- The system must have a working :ref:`compiler-toolchain` (because *emsdk* builds software from the source): +- The system must have a working :ref:`compiler-toolchain` (because *emsdk* builds software from the source): + + :: - :: - #Update the package lists sudo apt-get update - + # Install *gcc* (and related dependencies) sudo apt-get install build-essential - + # Install cmake sudo apt-get install cmake - + - *Python*, *node.js* or *Java* are not provided by *emsdk*. The user is expected to install these beforehand with the *system package manager*: :: - - # Install Python + + # Install Python sudo apt-get install python2.7 - + # Install node.js sudo apt-get install nodejs - + # Install Java (optional, only needed for Closure Compiler minification) sudo apt-get install default-jre .. note:: Your system may provide Node.js as ``node`` instead of ``nodejs``. In that case, you may need to also update the ``NODE_JS`` attribute of your ``~/.emscripten`` file. - -- *Git* is not installed automatically. Git is only needed if you want to use tools from one of the development branches **emscripten-incoming** or **emscripten-master**: + +- *Git* is not installed automatically. Git is only needed if you want to use tools from one of the development branches **emscripten-incoming** or **emscripten-master**: :: - + # Install git sudo apt-get install git-core @@ -135,7 +135,7 @@ More detailed instructions on the toolchain are provided in: :ref:`building-emsc Verifying the installation ========================== -The easiest way to verify the installation is to compile some code using Emscripten. +The easiest way to verify the installation is to compile some code using Emscripten. You can jump ahead to the :ref:`Tutorial`, but if you have any problems building you should run through the basic tests and troubleshooting instructions in :ref:`verifying-the-emscripten-environment`. @@ -145,19 +145,19 @@ You can jump ahead to the :ref:`Tutorial`, but if you have any problems building Updating the SDK ================ -.. tip:: You only need to install the SDK once! After that you can update to the latest SDK at any time using :ref:`Emscripten SDK (emsdk) `. +.. tip:: You only need to install the SDK once! After that you can update to the latest SDK at any time using :ref:`Emscripten SDK (emsdk) `. Type the following in a command prompt :: # 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 @@ -177,7 +177,7 @@ It is also possible to :ref:`remove specific tools in the SDK using emsdk `_ - `emsdk-1.22.0-full-64bit.exe `_ - `emsdk-1.21.0-full-64bit.exe `_ -- `emsdk-1.16.0-full-64bit.exe `_ (first stable fastcomp release) +- `emsdk-1.16.0-full-64bit.exe `_ (first stable fastcomp release) - `emsdk-1.13.0-full-32bit.exe `_ (a unstable first fastcomp release with Clang 3.3) - `emsdk-1.12.0-full-64bit.exe `_ (the last non-fastcomp version with Clang 3.2) - `emsdk-1.12.0-full-32bit.exe `_ diff --git a/site/source/docs/getting_started/getting_started_with_emscripten_and_vs2010.rst b/site/source/docs/getting_started/getting_started_with_emscripten_and_vs2010.rst index b2a2610013c32..a06f28fac319b 100644 --- a/site/source/docs/getting_started/getting_started_with_emscripten_and_vs2010.rst +++ b/site/source/docs/getting_started/getting_started_with_emscripten_and_vs2010.rst @@ -25,7 +25,7 @@ First select the **Emscripten** configuration from the *Configuration Manager* d How to launch a project in a web browser from Visual Studio =========================================================== -To launch a project directly to a web browser from Visual Studio: +To launch a project directly to a web browser from Visual Studio: #. Create a new environment variable ``EMCC_WEBBROWSER_EXE`` and set it to point to an executable you want to use to browse web pages generated using Emscripten via Visual Studio. Any browser can be used — below we specify *Mozilla Firefox*: @@ -34,7 +34,7 @@ To launch a project directly to a web browser from Visual Studio: SETX EMCC_WEBBROWSER_EXE C:/Program Files (x86)/Mozilla Firefox/firefox.exe -#. Right-click on the project to run, choose **Set as Startup Project**, and select **Start without Debugging** (**Ctrl+F5**). +#. Right-click on the project to run, choose **Set as Startup Project**, and select **Start without Debugging** (**Ctrl+F5**). This should launch the generated **.html** file to the browser you specified in ``EMCC_WEBBROWSER_EXE``. @@ -57,7 +57,7 @@ To add Emscripten as a build option for an existing project: #. Open the *Configuration Manager* dialog for the solution. #. In the *Active Solution Platform* dropdown, choose **New**. -#. In the *New* dialog, choose **Emscripten** as the platform name, and **Copy settings from Empty**. +#. In the *New* dialog, choose **Emscripten** as the platform name, and **Copy settings from Empty**. Now you should be able to switch between building the solution for Win32 and Emscripten by selecting the desired option from the *Configuration Manager* dropdown list. @@ -66,4 +66,4 @@ Creating a new Visual Studio solution for Emscripten ==================================================== To create a new Visual Studio project for Emscripten, first create a **Visual C++ Empty Project** (a new project for the Win32 platform). Then convert that project to also build for Emscripten as outlined in the previous section: :ref:`getting-started-emscripten-vs-existing-solution`. - \ No newline at end of file + diff --git a/site/source/docs/getting_started/index.rst b/site/source/docs/getting_started/index.rst index f9c83f1a2a7db..46956a11d6617 100644 --- a/site/source/docs/getting_started/index.rst +++ b/site/source/docs/getting_started/index.rst @@ -8,11 +8,11 @@ Now you know why Emscripten is :ref:`right for you `, it's tim This section provides a walk-through of :ref:`downloading and installing the SDK ` and the basics of :ref:`using the Emscripten toolchain `. The general :ref:`FAQ` answers many common questions about setting up and using Emscripten. -We also explain where to :ref:`Report Bugs ` in the toolchain and the site, and how to use Emscripten with :ref:`Visual Studio 2010 ` (Windows only). The :ref:`emscripten-test-suite` is a great resource for finding examples of how to use Emscripten. +We also explain where to :ref:`Report Bugs ` in the toolchain and the site, and how to use Emscripten with :ref:`Visual Studio 2010 ` (Windows only). The :ref:`emscripten-test-suite` is a great resource for finding examples of how to use Emscripten. .. toctree:: :maxdepth: 1 - + downloads Tutorial test-suite diff --git a/site/source/docs/getting_started/test-suite.rst b/site/source/docs/getting_started/test-suite.rst index d33f1b6a12987..ec1e430490ff4 100644 --- a/site/source/docs/getting_started/test-suite.rst +++ b/site/source/docs/getting_started/test-suite.rst @@ -11,13 +11,13 @@ This article explains how to run the test and benchmark suite, and provides an o Running the whole test suite ============================ -The whole core test suite can be run using the script `tests/runner.py `_: +The whole core test suite can be run using the script `tests/runner.py `_: .. code-block:: bash python tests/runner.py - -.. note:: + +.. note:: - The core test suite is not the entire test suite, see :ref:`section about core test modes ` - This may take several hours. @@ -31,7 +31,7 @@ You can also use *runner.py* to run different parts of the test suite, or indivi .. code-block:: bash python tests/runner.py test_hello_world - + Tests in the "core" test suite (``tests/test_core.py``) can be run as above. Other tests may need a prefix, for example ``browser.test_cubegeom`` for a test in ``tests/test_browser.py``. You can also specify an optional prefix for tests in core, to run them with extra options, for example ``asm2.test_hello_world`` will run ``hello_world`` using ``asm2`` opts (basically ``-O2``). See more examples in :ref:`emscripten-test-suite-list-of-tests`. It is possible to pass a wildcard to match multiple tests by name. For example, the commands @@ -80,10 +80,10 @@ You can also run a specific mode or test in a mode, or a specific test across al python tests/runner.py asm1 # Run one test in asm1 mode (-O1 optimizations). - python tests/runner.py asm1.test_hello_world - + python tests/runner.py asm1.test_hello_world + # Run one test in all modes. - python tests/runner.py ALL.test_hello_world + python tests/runner.py ALL.test_hello_world The core test modes are documented at the end of `/tests/test_core.py `_. @@ -111,7 +111,7 @@ You can run the tests yourself using the following command: python tests/runner.py benchmark - + .. _emscripten-test-suite-list-of-tests: Common tests @@ -122,40 +122,40 @@ Below is a list of some common tests/example commands. These include a comment e .. code-block:: bash # Run all (core) tests - python tests/runner.py + python tests/runner.py # Run hello world test, in default mode python tests/runner.py test_hello_world # Run it in asm1 mode - python tests/runner.py asm1.test_hello_world - + python tests/runner.py asm1.test_hello_world + # Run it in all modes - python tests/runner.py ALL.test_hello_world + python tests/runner.py ALL.test_hello_world - # Run all (core) tests in asm1 mode - python tests/runner.py asm1 + # Run all (core) tests in asm1 mode + python tests/runner.py asm1 - # Run all "other" tests - that have no mode + # Run all "other" tests - that have no mode python tests/runner.py other - # Run a specific test in "other" - python tests/runner.py other.test_static_link + # Run a specific test in "other" + python tests/runner.py other.test_static_link - # Run all browser tests + # Run all browser tests python tests/runner.py browser - - # Run a specific browser test - python tests/runner.py browser.test_sdlglshader - + + # Run a specific browser test + python tests/runner.py browser.test_sdlglshader + # Run all network tests. Note that you can also run specific tests (sockets.test_*) python tests/runner.py sockets - # Run all sanity tests. Note that you can also run specific tests (sanity.test_*) + # Run all sanity tests. Note that you can also run specific tests (sanity.test_*) python tests/runner.py sanity - # Run all benchmarks. Note that you can also run specific tests (benchmark.test_*) - python tests/runner.py benchmark + # Run all benchmarks. Note that you can also run specific tests (benchmark.test_*) + python tests/runner.py benchmark Debugging test failures @@ -166,18 +166,18 @@ Setting the :ref:`debugging-EMCC_DEBUG` is useful for debugging tests, as it emi .. code-block:: bash # On Windows, use "set" to set and un-set the EMCC_DEBUG environment variable: - set EMCC_DEBUG=1 + set EMCC_DEBUG=1 python tests/runner.py test_hello_world set EMCC_DEBUG=0 - + # On Linux, you can do this all in one line EMCC_DEBUG=1 python tests/runner.py test_hello_world - + # EMCC_DEBUG=2 generates additional debug information. EMCC_DEBUG=2 python tests/runner.py test_hello_world You can also specify ``EM_SAVE_DIR=1`` in the environment to save the temporary directory that the test runner uses into **/tmp/emscripten_temp/**. This is a test suite-specific feature, and is useful for tests that create temporary files. -The :ref:`Debugging` topic provides more guidance on how to debug Emscripten-generated code. +The :ref:`Debugging` topic provides more guidance on how to debug Emscripten-generated code. diff --git a/site/source/docs/introducing_emscripten/Talks-and-Publications.rst b/site/source/docs/introducing_emscripten/Talks-and-Publications.rst index 21c4344b4f4ad..0050b6b28f0fc 100644 --- a/site/source/docs/introducing_emscripten/Talks-and-Publications.rst +++ b/site/source/docs/introducing_emscripten/Talks-and-Publications.rst @@ -9,7 +9,7 @@ Presentations - Slides from Mozlando 2015: `Emscripten, WebAssembly, and Binaryen `_ (`kripken `_) -- Slides from CppCon 2014: +- Slides from CppCon 2014: - `Emscripten & asm.js: C++'s role in the modern web `_ (`kripken `_) @@ -20,16 +20,16 @@ Presentations - `Video of talk `_ - Slides from GDC 2014: `Getting started with asm.js and Emscripten `_ (`kripken `_, `lwagner `_) -- Slides from Strange Loop 2013: `Native speed on the web, JavaScript and asm.js `_ (`kripken `_) -- Slides from GDC Europe 2013: `C++ on the Web `_ (`floh `_) +- Slides from Strange Loop 2013: `Native speed on the web, JavaScript and asm.js `_ (`kripken `_) +- Slides from GDC Europe 2013: `C++ on the Web `_ (`floh `_) - Slides from QCon 2013: `Connecting languages together `_ (`kripken `_) -- Slides from Quo Vadis 2013: `C++ on the Web: Run your big 3D game in the browser! `_ (`floh `_) +- Slides from Quo Vadis 2013: `C++ on the Web: Run your big 3D game in the browser! `_ (`floh `_) - Slides from GDC 2013: - `Compiling C/C++ to JavaScript `_ (`kripken `_) - - `Multiplatform C++ on the Web with Emscripten `_ (`chadaustin `_) + - `Multiplatform C++ on the Web with Emscripten `_ (`chadaustin `_) -- Slides from mloc.js: `Big Web App? Compile it! `_ (`kripken `_) +- Slides from mloc.js: `Big Web App? Compile it! `_ (`kripken `_) - JSConf.eu 2011: `Emscripten `_ (`kripken `_) diff --git a/site/source/docs/introducing_emscripten/about_emscripten.rst b/site/source/docs/introducing_emscripten/about_emscripten.rst index 275da7361d1e3..6e2d22b62e288 100644 --- a/site/source/docs/introducing_emscripten/about_emscripten.rst +++ b/site/source/docs/introducing_emscripten/about_emscripten.rst @@ -6,11 +6,11 @@ About Emscripten Emscripten is an :ref:`Open Source ` LLVM to JavaScript compiler. Using Emscripten you can: -- Compile C and C++ code into JavaScript +- Compile C and C++ code into JavaScript - Compile any other code that can be translated into LLVM bitcode into JavaScript. - Compile the C/C++ **runtimes** of other languages into JavaScript, and then run code in those other languages in an *indirect* way (this has been done for Python and Lua)! -.. tip:: Emscripten makes native code immediately available on the Web: a platform that is standards-based, has numerous independent compatible implementations, and runs everywhere from PCs to iPads. +.. tip:: Emscripten makes native code immediately available on the Web: a platform that is standards-based, has numerous independent compatible implementations, and runs everywhere from PCs to iPads. With Emscripten, C/C++ developers don't have the high cost of porting code manually to JavaScript — or having to learn JavaScript at all. Web developers also benefit, as they can use the many thousands of pre-existing native utilities and libraries in their sites. @@ -25,14 +25,14 @@ Practically any **portable** C or C++ codebase can be compiled into JavaScript u :alt: Dead Trigger 2 Game logo :target: http://beta.unity3d.com/jonas/DT2/ :align: left - + .. raw:: html
For more demos, see the `list on the wiki `_. -Emscripten generates fast code! Its default output format is `asm.js `_ , a highly optimizable subset of JavaScript that can execute at close to native speed in many cases (check out the `current benchmark results `_ or run the :ref:`benchmark tests ` yourself). Optimized Emscripten code has also been `shown to have `_ a similar *effective size* to native code, when both are gzipped. +Emscripten generates fast code! Its default output format is `asm.js `_ , a highly optimizable subset of JavaScript that can execute at close to native speed in many cases (check out the `current benchmark results `_ or run the :ref:`benchmark tests ` yourself). Optimized Emscripten code has also been `shown to have `_ a similar *effective size* to native code, when both are gzipped. For a better understanding of just how fast and fluid Emscripten-ported code can be, check out the `Dead Trigger 2 `_ and `Angrybots `_ demos above. @@ -41,13 +41,13 @@ For a better understanding of just how fast and fluid Emscripten-ported code can Emscripten Toolchain ==================== -A high level view of the Emscripten toolchain is given below. The main tool is the :ref:`emccdoc`. This is a drop-in replacement for a standard compiler like *gcc*. +A high level view of the Emscripten toolchain is given below. The main tool is the :ref:`emccdoc`. This is a drop-in replacement for a standard compiler like *gcc*. .. image:: EmscriptenToolchain.png *Emcc* uses :term:`Clang` to convert C/C++ files to LLVM bitcode, and :ref:`Fastcomp ` (Emscripten's Compiler Core — an LLVM backend) to compile the bitcode to JavaScript. The output JavaScript can be executed by :term:`node.js`, or from within HTML in a browser. -The :ref:`emsdk` is used to manage multiple SDKs and tools, and to specify the particular SDK/set of tools currently being used to compile code (the :term:`Active Tool/SDK`). It can even "install" (download and build) the latest toolchain from Github! +The :ref:`emsdk` is used to manage multiple SDKs and tools, and to specify the particular SDK/set of tools currently being used to compile code (the :term:`Active Tool/SDK`). It can even "install" (download and build) the latest toolchain from Github! *Emsdk* writes the "active" configuration to the :ref:`compiler-configuration-file`. This file is used by *emcc* to get the correct current toolchain for building. @@ -60,9 +60,9 @@ The whole toolchain is delivered in the :ref:`Emscripten SDK `_ support is sufficient to run quite a lot of code. :ref:`OpenGL-support` support is excellent for OpenGL ES 2.0-type code, and acceptable for other types. +Emscripten support for **portable** C/C++ code is fairly comprehensive. Support for the C standard library, C++ standard library, C++ exceptions, etc. is very good. `SDL `_ support is sufficient to run quite a lot of code. :ref:`OpenGL-support` support is excellent for OpenGL ES 2.0-type code, and acceptable for other types. -There are differences between the native and :ref:`emscripten-runtime-environment`, which mean some changes usually need to be made to the native code. That said, many applications will only need to change the way they define their main loop, and also modify their :ref:`file handling ` to adapt to the limitations of the browser/JavaScript. +There are differences between the native and :ref:`emscripten-runtime-environment`, which mean some changes usually need to be made to the native code. That said, many applications will only need to change the way they define their main loop, and also modify their :ref:`file handling ` to adapt to the limitations of the browser/JavaScript. There are also limitations that can make some code easier to port — read :ref:`code-portability-guidelines` to determine where you may need to spend more effort. diff --git a/site/source/docs/introducing_emscripten/community.rst b/site/source/docs/introducing_emscripten/community.rst index b8b156c7e5a61..de4fad628924e 100644 --- a/site/source/docs/introducing_emscripten/community.rst +++ b/site/source/docs/introducing_emscripten/community.rst @@ -4,7 +4,7 @@ Community ========= -Welcome to the Emscripten community! +Welcome to the Emscripten community! .. _contact: @@ -15,11 +15,11 @@ Get in touch The best ways to contact us for support are the *mailing list* and the *IRC* channel. Ask questions, share your ideas, or just join the conversation. - Mailing list: `emscripten-discuss `_ -- IRC: **#emscripten** on `irc.mozilla.org `_ +- IRC: **#emscripten** on `irc.mozilla.org `_ Emscripten also has a presence on social media: -- `#emscripten `_ (Emscripten Hashtag on Twitter) +- `#emscripten `_ (Emscripten Hashtag on Twitter) - `@kripken `_ (an Emscripten developer's account on Twitter, mentions Emscripten updates) @@ -37,7 +37,7 @@ Blogs Get the latest official Emscripten news on the blogs: `Developer blog (azakai) `_ and `Mozilla blog `_. -In addition, other interesting blogs and demos are regularly shared on Twitter by the development team `(@kripken) `_ and the broader community `(#emscripten) `_. +In addition, other interesting blogs and demos are regularly shared on Twitter by the development team `(@kripken) `_ and the broader community `(#emscripten) `_. .. todo :: **HamishW** At some point in future would be nice to actually display RSS feeds from above links here. Perhaps including @kripken in feed. In this case would need a dedicated blogs link as well. diff --git a/site/source/docs/introducing_emscripten/emscripten_license.rst b/site/source/docs/introducing_emscripten/emscripten_license.rst index 75320885c4312..a9c95b46969c5 100644 --- a/site/source/docs/introducing_emscripten/emscripten_license.rst +++ b/site/source/docs/introducing_emscripten/emscripten_license.rst @@ -4,12 +4,12 @@ Open Source License =================== -Emscripten is made available under two permissive open source licenses: the *MIT license* and the *University of Illinois/NCSA Open Source License*. +Emscripten is made available under two permissive open source licenses: the *MIT license* and the *University of Illinois/NCSA Open Source License*. There is little, if any, practical difference between the licenses. They are both offered because the: - *MIT license* is well known and understood. -- *University of Illinois/NCSA Open Source License* allows Emscripten's code to be integrated upstream into LLVM, should the opportunity arise. +- *University of Illinois/NCSA Open Source License* allows Emscripten's code to be integrated upstream into LLVM, should the opportunity arise. The license for Emscripten |release| (|today|) is reproduced below. The `current full licence `_ can be found on Github (and is also present in the root of the SDK). diff --git a/site/source/docs/introducing_emscripten/index.rst b/site/source/docs/introducing_emscripten/index.rst index cb614769e74cc..d913f6e09423e 100644 --- a/site/source/docs/introducing_emscripten/index.rst +++ b/site/source/docs/introducing_emscripten/index.rst @@ -4,7 +4,7 @@ Introducing Emscripten ====================== -This section explains what Emscripten does, why it is needed, its limitations and its licensing. After reading, you will understand whether Emscripten is the right tool for you, and where to go if you have :ref:`further questions `. +This section explains what Emscripten does, why it is needed, its limitations and its licensing. After reading, you will understand whether Emscripten is the right tool for you, and where to go if you have :ref:`further questions `. .. toctree:: :maxdepth: 1 diff --git a/site/source/docs/optimizing/Optimizing-Code.rst b/site/source/docs/optimizing/Optimizing-Code.rst index be31b2e41841d..a3e286cf9210a 100644 --- a/site/source/docs/optimizing/Optimizing-Code.rst +++ b/site/source/docs/optimizing/Optimizing-Code.rst @@ -9,7 +9,7 @@ Generally you should first compile and run your code without optimizations (the How to optimize code ==================== -Code is optimized by specifying :ref:`optimization flags ` when running :ref:`emcc `. The levels include: :ref:`-O0 ` (no optimization), :ref:`-O1 `, :ref:`-O2 `, :ref:`-Os `, :ref:`-Oz `, and :ref:`-O3 `. +Code is optimized by specifying :ref:`optimization flags ` when running :ref:`emcc `. The levels include: :ref:`-O0 ` (no optimization), :ref:`-O1 `, :ref:`-O2 `, :ref:`-Os `, :ref:`-Oz `, and :ref:`-O3 `. For example, to compile with optimization level ``-O2``: @@ -19,7 +19,7 @@ For example, to compile with optimization level ``-O2``: The higher optimization levels introduce progressively more aggressive optimization, resulting in improved performance and code size at the cost of increased compilation time. The levels can also highlight different issues related to undefined behavior in code. -The optimization level you should use depends mostly on the current stage of development: +The optimization level you should use depends mostly on the current stage of development: - When first porting code, run *emcc* on your code using the default settings (without optimization). Check that your code works and :ref:`debug ` and fix any issues before continuing. - Build with lower optimization levels during development for a shorter compile/test iteration cycle (``-O0`` or ``-O1``). @@ -40,17 +40,17 @@ There are several flags you can :ref:`pass to the compiler A few useful flags are: -- +- .. _optimizing-code-no-exit-runtime: - + ``NO_EXIT_RUNTIME``: Building with ``-s NO_EXIT_RUNTIME=1`` lets the compiler know that you don't want to shut down the runtime environment after the ``main()`` function finishes. This allows it to discard the ``atexit`` and global destructor calls it would otherwise make, improving code size and startup speed. - This is useful if your ``main()`` function finishes but you still want to execute code, for example in an app that uses a :ref:`main loop function `. - + This is useful if your ``main()`` function finishes but you still want to execute code, for example in an app that uses a :ref:`main loop function `. + .. note:: Emscripten will not shut down the runtime if it detects :c:func:`emscripten_set_main_loop`, but it is better to optimise away the unnecessary code. - + Code size ========= @@ -61,18 +61,18 @@ This section describes optimisations and issues that are relevant to code size. Memory initialization --------------------- -By default Emscripten emits the static memory initialization code inside the **.js** file. This can cause the JavaScript file to be very large, which will slow down startup. It can also cause problems in JavaScript engines with limits on array sizes, resulting in errors like ``Array initializer too large`` or ``Too much recursion``. +By default Emscripten emits the static memory initialization code inside the **.js** file. This can cause the JavaScript file to be very large, which will slow down startup. It can also cause problems in JavaScript engines with limits on array sizes, resulting in errors like ``Array initializer too large`` or ``Too much recursion``. -The ``--memory-init-file 1`` :ref:`emcc option ` causes the compiler to emit this code in a separate binary file with suffix **.mem**. The **.mem** file is loaded (asynchronously) by the main **.js** file before ``main()`` is called and compiled code is able to run. +The ``--memory-init-file 1`` :ref:`emcc option ` causes the compiler to emit this code in a separate binary file with suffix **.mem**. The **.mem** file is loaded (asynchronously) by the main **.js** file before ``main()`` is called and compiled code is able to run. - .. note:: From Emscripten 1.21.1 this setting is enabled by default for fully optimized builds, that is, ``-O2`` and above. + .. note:: From Emscripten 1.21.1 this setting is enabled by default for fully optimized builds, that is, ``-O2`` and above. .. _optimizing-code-oz-os: Trading off code size and performance ------------------------------------- -You may wish to build the less performance-sensitive source files in your project using :ref:`-Os ` or :ref:`-Oz ` and the remainder using :ref:`-O2 ` (:ref:`-Os ` and :ref:`-Oz ` are similar to :ref:`-O2 `, but reduce code size at the expense of performance. :ref:`-Oz ` reduces code size more than :ref:`-Os `.) +You may wish to build the less performance-sensitive source files in your project using :ref:`-Os ` or :ref:`-Oz ` and the remainder using :ref:`-O2 ` (:ref:`-Os ` and :ref:`-Oz ` are similar to :ref:`-O2 `, but reduce code size at the expense of performance. :ref:`-Oz ` reduces code size more than :ref:`-Os `.) Note that ``-Oz`` may take longer to build. For example, it enables ``EVAL_CTORS`` which tries to optimize out C++ global constructors, which takes time. @@ -133,7 +133,7 @@ If you hit memory limits in browsers, it can help to run your project by itself, Outlining --------- -JavaScript engines will often compile very large functions slowly (relative to their size), and fail to optimize them effectively (or at all). One approach to this problem is to use "outlining": breaking them into smaller functions that can be compiled and optimized more effectively. +JavaScript engines will often compile very large functions slowly (relative to their size), and fail to optimize them effectively (or at all). One approach to this problem is to use "outlining": breaking them into smaller functions that can be compiled and optimized more effectively. Outlining increases overall code size, and can itself make some code less optimised. Despite this, outlining can sometimes improve both startup and runtime speed. For more information read `Outlining: a workaround for JITs and big functions `_. @@ -145,9 +145,9 @@ The ``OUTLINING_LIMIT`` setting defines the function size at which Emscripten wi Aggressive variable elimination ------------------------------- -Aggressive variable elimination attempts to remove variables whenever possible, even at the cost of increasing code size by duplicating expressions. This can improve speed in cases where you have extremely large functions. For example it can make sqlite (which has a huge interpreter loop with thousands of lines in it) 7% faster. +Aggressive variable elimination attempts to remove variables whenever possible, even at the cost of increasing code size by duplicating expressions. This can improve speed in cases where you have extremely large functions. For example it can make sqlite (which has a huge interpreter loop with thousands of lines in it) 7% faster. -You can enable aggressive variable elimination with ``-s AGGRESSIVE_VARIABLE_ELIMINATION=1``. +You can enable aggressive variable elimination with ``-s AGGRESSIVE_VARIABLE_ELIMINATION=1``. .. note:: This setting can be harmful in some cases. Test before using it. @@ -160,7 +160,7 @@ Other optimization issues C++ exceptions -------------- -C++ exceptions are turned off by default in ``-O1`` (and above). This prevents the generation of ``try-catch`` blocks, which lets the code run much faster, and also makes the code smaller. +C++ exceptions are turned off by default in ``-O1`` (and above). This prevents the generation of ``try-catch`` blocks, which lets the code run much faster, and also makes the code smaller. To re-enable exceptions in optimized code, run *emcc* with ``-s DISABLE_EXCEPTION_CATCHING=0`` (see `src/settings.js `_). @@ -174,7 +174,7 @@ Building with ``-s ALLOW_MEMORY_GROWTH=1`` allows the total amount of memory use Inlining -------- -`Inlining `_ often generates large functions, as these allow the compiler's optimizations to be more effective. Unfortunately large functions can be slower at runtime than multiple smaller functions because JavaScript engines often either don't optimize big functions (for fear of long JIT times), or they do optimize them resulting in noticeable pauses. +`Inlining `_ often generates large functions, as these allow the compiler's optimizations to be more effective. Unfortunately large functions can be slower at runtime than multiple smaller functions because JavaScript engines often either don't optimize big functions (for fear of long JIT times), or they do optimize them resulting in noticeable pauses. .. note:: ``-O1`` and ``-O2`` inline functions by default. Ironically, this can actually decrease performance in some cases! @@ -201,7 +201,7 @@ A few **UNSAFE** optimizations you might want to try are: Profiling ========= -Modern browsers have JavaScript profilers that can help find the slower parts in your code. As each browser's profiler has limitations, profiling in multiple browsers is highly recommended. +Modern browsers have JavaScript profilers that can help find the slower parts in your code. As each browser's profiler has limitations, profiling in multiple browsers is highly recommended. To ensure that compiled code contains enough information for profiling, build your project with :ref:`profiling ` as well as optimization and other flags: diff --git a/site/source/docs/optimizing/Optimizing-WebGL.rst b/site/source/docs/optimizing/Optimizing-WebGL.rst index a581c7402d3c1..4a536afdf0ec6 100644 --- a/site/source/docs/optimizing/Optimizing-WebGL.rst +++ b/site/source/docs/optimizing/Optimizing-WebGL.rst @@ -109,7 +109,7 @@ The most important aspect of efficient GPU usage is to make sure that the CPU wi - Never call ``glGetError()`` or ``glCheckFramebufferStatus()`` at render time. These functions should be restricted to be checked at loading time only, since both of these can do a full pipeline sync. - - Similarly, do not call any of the ``glGet*()`` API functions at render time, but query them at startup and loading time, and refer to cached results at render time. + - Similarly, do not call any of the ``glGet*()`` API functions at render time, but query them at startup and loading time, and refer to cached results at render time. - Try to avoid compiling shaders at render time, both ``glCompileShader()`` and ``glLinkProgram()`` can be extremely slow. @@ -209,7 +209,7 @@ These extensions were adopted without any functional changes, so when initializi - In WebGL 2/GLES 3.0, a number of texture format enums changed for texture formats introduced by extensions. It is no longer possible to use so called `unsized` texture formats from WebGL 1/GLES 2 extensions, but instead, the new sized variants of the formats must be used for the ``internalFormat`` field. For example, instead of creating a texture with ``format=GL_DEPTH_COMPONENT, type=GL_UNSIGNED_INT, internalFormat=GL_DEPTH_COMPONENT``, it is required to specify the size in the ``internalFormat`` field, i.e. ``format=GL_DEPTH_COMPONENT, type=GL_UNSIGNED_INT, internalFormat=GL_DEPTH_COMPONENT24``. -- A particular gotcha with WebGL 2/GLES 3.0 texture formats is that the enum value for the half float (float16) texture type changed value when the WebGL 1/GLES 2 extension ``OES_texture_half_float`` was subsumed to the core WebGL 2/GLES 3.0 specification. In WebGL1/GLES 2, half floats were denoted by the value ``GL_HALF_FLOAT_OES=0x8d61``, but in WebGL2/GLES 3.0, the enum value ``GL_HALF_FLOAT=0x140b`` is used, contrast to other texture type extensions where inclusion to the core specification generally preserved the value of the enum that is used. +- A particular gotcha with WebGL 2/GLES 3.0 texture formats is that the enum value for the half float (float16) texture type changed value when the WebGL 1/GLES 2 extension ``OES_texture_half_float`` was subsumed to the core WebGL 2/GLES 3.0 specification. In WebGL1/GLES 2, half floats were denoted by the value ``GL_HALF_FLOAT_OES=0x8d61``, but in WebGL2/GLES 3.0, the enum value ``GL_HALF_FLOAT=0x140b`` is used, contrast to other texture type extensions where inclusion to the core specification generally preserved the value of the enum that is used. Overall, to ease simultaneously targeting both WebGL1/GLES 2 and WebGL2/GLES 3.0 contexts, Emscripten provides a linker flag ``-s WEBGL2_BACKWARDS_COMPATIBILITY_EMULATION=1``, which hides the above differences behind automatically detected migration, to allow existing WebGL 1 content to transparently also target WebGL 2 for the free speed boost it provides. diff --git a/site/source/docs/optimizing/Profiling-Toolchain.rst b/site/source/docs/optimizing/Profiling-Toolchain.rst index 30a067a3977df..3ec48b4793cc5 100644 --- a/site/source/docs/optimizing/Profiling-Toolchain.rst +++ b/site/source/docs/optimizing/Profiling-Toolchain.rst @@ -38,7 +38,7 @@ The command ``tools/emprofile.py --reset`` deletes all previously stored profili EM_PROFILE_TOOLCHAIN=1 emcc tests/hello_world.c -o a.bc EM_PROFILE_TOOLCHAIN=1 emcc a.bc -O3 -o a.html tools/emprofile.py --graph --outfile=myresults.html - + Any number of commands can be profiled within one session, and when ``tools/emprofile.py --graph`` is finally called, it will pick up records from all Emscripten tool invocations up to that point. Calling ``--graph`` also clears the recorded profiling data. The output HTML filename can be chosen with the optional ``--outfile=myresults.html`` parameter. diff --git a/site/source/docs/porting/Debugging.rst b/site/source/docs/porting/Debugging.rst index d831ef2af4f4e..604aeb243955c 100644 --- a/site/source/docs/porting/Debugging.rst +++ b/site/source/docs/porting/Debugging.rst @@ -4,7 +4,7 @@ Debugging ========= -One of the main advantages of debugging cross-platform Emscripten code is that the same cross-platform source code can be debugged on either the native platform or using the web browser's increasingly powerful toolset — including debugger, profiler, and other tools. +One of the main advantages of debugging cross-platform Emscripten code is that the same cross-platform source code can be debugged on either the native platform or using the web browser's increasingly powerful toolset — including debugger, profiler, and other tools. Emscripten provides a lot of functionality and tools to aid debugging: @@ -16,7 +16,7 @@ Emscripten provides a lot of functionality and tools to aid debugging: This article describes the main tools and settings provided by Emscripten for debugging, along with a section explaining how to debug a number of :ref:`debugging-emscripten-specific-issues`. - + .. _debugging-debug-information-g: Debug information @@ -24,13 +24,13 @@ Debug information :ref:`Emcc ` strips out most of the debug information from :ref:`optimized builds ` by default. Optimisation levels :ref:`-01 ` and above remove LLVM debug information, and also disable runtime :ref:`ASSERTIONS ` checks. From optimization level :ref:`-02 ` the code is minified by the :term:`Closure Compiler` and becomes virtually unreadable. -The *emcc* :ref:`-g flag ` can be used to preserve debug information in the compiled output. By default, this option preserves white-space, function names and variable names. +The *emcc* :ref:`-g flag ` can be used to preserve debug information in the compiled output. By default, this option preserves white-space, function names and variable names. + +The flag can also be specified with one of five levels: :ref:`-g0 `, :ref:`-g1 `, :ref:`-g2 `, :ref:`-g3 `, and :ref:`-g4 `. Each level builds on the last to provide progressively more debug information in the compiled output. The :ref:`-g3 flag ` provides the same level of debug information as the :ref:`-g flag `. -The flag can also be specified with one of five levels: :ref:`-g0 `, :ref:`-g1 `, :ref:`-g2 `, :ref:`-g3 `, and :ref:`-g4 `. Each level builds on the last to provide progressively more debug information in the compiled output. The :ref:`-g3 flag ` provides the same level of debug information as the :ref:`-g flag `. +The :ref:`-g4 ` option provides the most debug information — it generates source maps that allow you to view and debug the *C/C++ source code* in your browser's debugger on Firefox, Chrome or Safari! -The :ref:`-g4 ` option provides the most debug information — it generates source maps that allow you to view and debug the *C/C++ source code* in your browser's debugger on Firefox, Chrome or Safari! - -.. note:: Some optimizations may be disabled when used in conjunction with the debug flags. For example, if you compile with ``-O3 -g4`` some of the normal ``-O3`` optimizations will be disabled in order to provide the requested debugging information. +.. note:: Some optimizations may be disabled when used in conjunction with the debug flags. For example, if you compile with ``-O3 -g4`` some of the normal ``-O3`` optimizations will be disabled in order to provide the requested debugging information. .. _debugging-EMCC_DEBUG: @@ -45,17 +45,17 @@ The ``EMCC_DEBUG`` environment variable can be set to enable Emscripten's debug EMCC_DEBUG=1 ./emcc tests/hello_world.cpp -o hello.html # Windows - set EMCC_DEBUG=1 + set EMCC_DEBUG=1 emcc tests/hello_world.cpp -o hello.html - set EMCC_DEBUG=0 + set EMCC_DEBUG=0 + +With ``EMCC_DEBUG=1`` set, :ref:`emcc ` emits debug output and generates intermediate files for the compiler's various stages. ``EMCC_DEBUG=2`` additionally generates intermediate files for each JavaScript optimizer pass. -With ``EMCC_DEBUG=1`` set, :ref:`emcc ` emits debug output and generates intermediate files for the compiler's various stages. ``EMCC_DEBUG=2`` additionally generates intermediate files for each JavaScript optimizer pass. +The debug logs and intermediate files are output to **TEMP_DIR/emscripten_temp**, where ``TEMP_DIR`` is by default **/tmp** (it is defined in the :ref:`.emscripten configuration file `). -The debug logs and intermediate files are output to **TEMP_DIR/emscripten_temp**, where ``TEMP_DIR`` is by default **/tmp** (it is defined in the :ref:`.emscripten configuration file `). - The debug logs can be analysed to profile and review the changes that were made in each step. -.. note:: The debug mode can also be enabled by specifying the :ref:`verbose output ` compiler flag (``emcc -v``). +.. note:: The debug mode can also be enabled by specifying the :ref:`verbose output ` compiler flag (``emcc -v``). .. _debugging-compilation-settings: @@ -71,14 +71,14 @@ Emscripten has a number of compiler settings that can be useful for debugging. T The most important settings are: - - + - .. _debugging-ASSERTIONS: - + ``ASSERTIONS=1`` is used to enable runtime checks for common memory allocation errors (e.g. writing more memory than was allocated). It also defines how Emscripten should handle errors in program flow. The value can be set to ``ASSERTIONS=2`` in order to run additional tests. - - ``ASSERTIONS=1`` is enabled by default. Assertions are turned off for optimized code (:ref:`-01 ` and above). - - - + + ``ASSERTIONS=1`` is enabled by default. Assertions are turned off for optimized code (:ref:`-01 ` and above). + + - .. _debugging-SAFE-HEAP: ``SAFE_HEAP=1`` adds additional memory access checks, and will give clear errors for problems like dereferencing 0 and memory alignment issues. @@ -98,9 +98,9 @@ A number of other useful debug settings are defined in `src/settings.js ` option passes ``-v`` to LLVM and runs Emscripten's internal sanity checks on the toolchain. +Compiling with the :ref:`emcc -v ` option passes ``-v`` to LLVM and runs Emscripten's internal sanity checks on the toolchain. -The verbose mode also enables Emscripten's :ref:`debugging-EMCC_DEBUG` to generate intermediate files for the compiler’s various stages. +The verbose mode also enables Emscripten's :ref:`debugging-EMCC_DEBUG` to generate intermediate files for the compiler’s various stages. .. _debugging-manual-debugging: @@ -129,7 +129,7 @@ Debug printouts can even execute arbitrary JavaScript. For example: Disabling optimizations ======================= -It can sometimes be useful to compile with either LLVM optimizations (:ref:`llvm-opts `) or JavaScript optimizations (:ref:`js-opts `) disabled. +It can sometimes be useful to compile with either LLVM optimizations (:ref:`llvm-opts `) or JavaScript optimizations (:ref:`js-opts `) disabled. For example, the following command enables :ref:`debugging-debug-information-g` and :ref:`-02 ` optimization (for both LLVM and JavaScript), but then explicitly turns off the JavaScript optimizer. @@ -145,10 +145,10 @@ The result is code that can be more useful for debugging issues related to LLVM- var label = 0; var $puts=_puts(((8)|0)); //@line 4 "tests/hello_world.c" return 1; //@line 5 "tests/hello_world.c" - } + } + - .. _debugging-emscripten-specific-issues: Emscripten-specific issues @@ -157,7 +157,7 @@ Emscripten-specific issues Memory Alignment Issues ----------------------- -The :ref:`Emscripten memory representation ` assumes loads and stores are aligned. Performing a normal load or store on an unaligned address can fail. +The :ref:`Emscripten memory representation ` assumes loads and stores are aligned. Performing a normal load or store on an unaligned address can fail. .. tip:: :ref:`SAFE_HEAP ` can be used to reveal memory alignment issues. @@ -166,15 +166,15 @@ Generally it is best to avoid unaligned reads and writes — often they occur as Emscripten supports unaligned reads and writes, but they will be much slower, and should be used only when absolutely necessary. To force an unaligned read or write you can: - Manually read individual bytes and reconstruct the full value -- Use the :c:type:`emscripten_align* ` typedefs, which define unaligned versions of the basic types (``short``, ``int``, ``float``, ``double``). All operations on those types are not fully aligned (use the ``1`` variants in most cases, which mean no alignment whatsoever). +- Use the :c:type:`emscripten_align* ` typedefs, which define unaligned versions of the basic types (``short``, ``int``, ``float``, ``double``). All operations on those types are not fully aligned (use the ``1`` variants in most cases, which mean no alignment whatsoever). Function Pointer Issues ----------------------- -If you get an ``abort()`` from a function pointer call to ``nullFunc`` or ``b0`` or ``b1`` (possibly with an error message saying "incorrect function pointer"), the problem is that the function pointer was not found in the expected function pointer table when called. +If you get an ``abort()`` from a function pointer call to ``nullFunc`` or ``b0`` or ``b1`` (possibly with an error message saying "incorrect function pointer"), the problem is that the function pointer was not found in the expected function pointer table when called. -.. note:: ``nullFunc`` is the function used to populate empty index entries in the function pointer tables (``b0`` and ``b1`` are shorter names used for ``nullFunc`` in more optimized builds). A function pointer to an invalid index will call this function, which simply calls ``abort()``. +.. note:: ``nullFunc`` is the function used to populate empty index entries in the function pointer tables (``b0`` and ``b1`` are shorter names used for ``nullFunc`` in more optimized builds). A function pointer to an invalid index will call this function, which simply calls ``abort()``. There are several possible causes: @@ -183,13 +183,13 @@ There are several possible causes: In order to debug these sorts of issues: -- Compile with ``-Werror``. This turns warnings into errors, which can be useful as some cases of undefined behavior would otherwise show warnings. -- Use ``-s ASSERTIONS=2`` to get some useful information about the function pointer being called, and its type. -- Look at the browser stack trace to see where the error occurs and which function should have been called. +- Compile with ``-Werror``. This turns warnings into errors, which can be useful as some cases of undefined behavior would otherwise show warnings. +- Use ``-s ASSERTIONS=2`` to get some useful information about the function pointer being called, and its type. +- Look at the browser stack trace to see where the error occurs and which function should have been called. - Build with :ref:`SAFE_HEAP=1 ` and function pointer aliasing disabled (``ALIASING_FUNCTION_POINTERS=0``). This should make it impossible for a function pointer to be called with the wrong type without raising an error: ``-s SAFE_HEAP=1 -s ALIASING_FUNCTION_POINTERS=0`` -Another function pointer issue is when the wrong function is called. :ref:`SAFE_HEAP=1 ` can help with this as it detects some possible errors with function table accesses. +Another function pointer issue is when the wrong function is called. :ref:`SAFE_HEAP=1 ` can help with this as it detects some possible errors with function table accesses. ``ALIASING_FUNCTION_POINTERS=0`` is also useful because it ensures that calls to function pointer addresses in the wrong table result in clear errors. Without this setting such calls just execute whatever function is at the address, which can be much harder to debug. @@ -232,9 +232,9 @@ To run the *AutoDebugger*, compile with the environment variable ``EMCC_AUTODEBU EMCC_AUTODEBUG=1 ./emcc tests/hello_world.cpp -o hello.html # Windows - set EMCC_AUTODEBUG=1 + set EMCC_AUTODEBUG=1 emcc tests/hello_world.cpp -o hello.html - set EMCC_AUTODEBUG=0 + set EMCC_AUTODEBUG=0 .. _debugging-autodebugger-regressions: @@ -246,16 +246,16 @@ Use the following workflow to find regressions with the *AutoDebugger*: - Compile the working code with ``EMCC_AUTODEBUG=1`` set in the environment. - Compile the code using ``EMCC_AUTODEBUG=1`` in the environment again, but this time with the settings that cause the regression. Following this step we have one build before the regression and one after. -- Run both versions of the compiled code and save their output. +- Run both versions of the compiled code and save their output. - Compare the output using a *diff* tool. -Any difference between the outputs is likely to be caused by the bug. +Any difference between the outputs is likely to be caused by the bug. .. note:: False positives can be caused by calls to ``clock()``, which will differ slightly between runs. -You can also make native builds using the :term:`LLVM Nativizer` tool. This can be run on the autodebugged **.ll** file, which will be emitted in ``/tmp/emscripten_temp`` when ``EMCC_DEBUG=1`` is set. +You can also make native builds using the :term:`LLVM Nativizer` tool. This can be run on the autodebugged **.ll** file, which will be emitted in ``/tmp/emscripten_temp`` when ``EMCC_DEBUG=1`` is set. -.. note:: +.. note:: - The native build created using the :term:`LLVM Nativizer` will use native system libraries. Direct comparisons of output with Emscripten-compiled code can therefore be misleading. - Attempting to interpret code compiled with ``-g`` using the *LLVM Nativizer* or :term:`lli` may crash, so you may need to build once without ``-g`` for these tools, then build again with ``-g``. Another option is to use `tools/exec_llvm.py `_ in Emscripten, which will run *lli* after cleaning out debug info. diff --git a/site/source/docs/porting/asyncify.rst b/site/source/docs/porting/asyncify.rst index 977f1e7c63bb4..013a92e5cbbf3 100644 --- a/site/source/docs/porting/asyncify.rst +++ b/site/source/docs/porting/asyncify.rst @@ -57,11 +57,11 @@ Specifically, a number of aspects should be taken into consideration: - Split the function when an async function is called, and the second function should be registered as the callback for the async function - Any function that calls an async function also becomes an async function. - Keep all local variables available to the callback - - Closure cannot be used in order to make asm.js validated code. + - Closure cannot be used in order to make asm.js validated code. - Take care of loops and branches - Make the return value available to the callee - Some functions could be both sync or async, depending on the input. - + And the ``ASYNCIFY`` option does all above automatically, through a number of transformations on LLVM IR. @@ -90,7 +90,7 @@ Limitations =========== Code size increase should be expected, depending on the specific input. -``-Os`` (or ``-Oz`` for linking) is recommended when ``ASYNCIFY`` is turned on. +``-Os`` (or ``-Oz`` for linking) is recommended when ``ASYNCIFY`` is turned on. E.g. usually the following loop is expanded to speed up:: for(int i = 0; i < 3; ++i) { @@ -99,7 +99,7 @@ E.g. usually the following loop is expanded to speed up:: // do something else } -However by expanding the loop, two more async calls are introduced, such that more callback functions will be produced during the asyncify transformation. +However by expanding the loop, two more async calls are introduced, such that more callback functions will be produced during the asyncify transformation. **Asyncify can make performance much slower, if it ends up splitting a function which you need to be fast.** diff --git a/site/source/docs/porting/connecting_cpp_and_javascript/Interacting-with-code.rst b/site/source/docs/porting/connecting_cpp_and_javascript/Interacting-with-code.rst index 160ac96666b2f..3a57409f15876 100644 --- a/site/source/docs/porting/connecting_cpp_and_javascript/Interacting-with-code.rst +++ b/site/source/docs/porting/connecting_cpp_and_javascript/Interacting-with-code.rst @@ -278,7 +278,7 @@ You can also send values from C into JavaScript inside :c:macro:`EM_ASM_` Module.print('I received: ' + $0); }, 100); -This will show ``I received: 100``. +This will show ``I received: 100``. You can also receive values back, for example the following will print out ``I received: 100`` and then ``101``. @@ -387,7 +387,7 @@ some common JavaScript practices can not be used in certain ways in emscripten library files. To save space, by default, emscripten only includes library properties -referenced from C/C++. It does this by calling ``toString`` on each +referenced from C/C++. It does this by calling ``toString`` on each used property on the JavaScript libraries that are linked in. That means that you can't use a closure directly, for example, as ``toString`` isn't compatible with that - just like when using a string to create @@ -415,7 +415,7 @@ initialization. good_02: function() { _good_02 = document.querySelector.bind(document); }, - + // Solution for closures good_03__postset: '_good_03();', good_03: function() { @@ -424,11 +424,11 @@ initialization. console.log("times called: ", ++callCount); }; }, - + // Solution for curry/transform good_05__postset: '_good_05();', good_05: function() { - _good_05 = curry(scrollTo, 0); + _good_05 = curry(scrollTo, 0); }, }); @@ -441,24 +441,24 @@ output file. For the example above this code will be emitted. function _good_02() { _good_o2 = document.querySelector.bind(document); } - + function _good_03() { var callCount = 0; _good_03 = function() { console.log("times called: ", ++callCount); }; } - + function _good_05() { - _good_05 = curry(scrollTo, 0); + _good_05 = curry(scrollTo, 0); }; - + // Call each function once so it will replace itself _good_02(); _good_03(); _good_05(); -You can also put most of your code in the ``xxx__postset`` strings. +You can also put most of your code in the ``xxx__postset`` strings. The example below each method declares a dependency on ``$method_support`` and are otherwise dummy functions. ``$method_support`` itself has a corresponding ``__postset`` property with all the code to set the @@ -492,7 +492,7 @@ various methods to the functions we actually want. ' _method_03 = inst.reset.bind(inst); ', '}()); ', ].join('\n'), - method_01: function() {}, + method_01: function() {}, method_01__deps: ['$method_support'], method_02: function() {}, method_01__deps: ['$method_support'], @@ -513,29 +513,29 @@ a function, $method_support__postset: 'method_support();', $method_support: { init: function() { - var SomeLib = function() { - this.callCount = 0; - }; - + var SomeLib = function() { + this.callCount = 0; + }; + SomeLib.prototype.getCallCount = function() { - return this.callCount; - }; - - SomeLib.prototype.process = function() { - ++this.callCount; - }; - - SomeLib.prototype.reset = function() { - this.callCount = 0; - }; - - var inst = new SomeLib(); - _method_01 = inst.getCallCount.bind(inst); - _method_02 = inst.process.bind(inst); - _method_03 = inst.reset.bind(inst); - } + return this.callCount; + }; + + SomeLib.prototype.process = function() { + ++this.callCount; + }; + + SomeLib.prototype.reset = function() { + this.callCount = 0; + }; + + var inst = new SomeLib(); + _method_01 = inst.getCallCount.bind(inst); + _method_02 = inst.process.bind(inst); + _method_03 = inst.reset.bind(inst); + } }, - method_01: function() {}, + method_01: function() {}, method_01__deps: ['$method_support'], method_02: function() {}, method_01__deps: ['$method_support'], diff --git a/site/source/docs/porting/connecting_cpp_and_javascript/WebIDL-Binder.rst b/site/source/docs/porting/connecting_cpp_and_javascript/WebIDL-Binder.rst index 085f77b75952e..69682017422a2 100644 --- a/site/source/docs/porting/connecting_cpp_and_javascript/WebIDL-Binder.rst +++ b/site/source/docs/porting/connecting_cpp_and_javascript/WebIDL-Binder.rst @@ -4,7 +4,7 @@ WebIDL Binder ============= -The *WebIDL Binder* provides a simple and lightweight approach to binding C++, so that compiled code can be called from JavaScript as if it were a normal JavaScript library. +The *WebIDL Binder* provides a simple and lightweight approach to binding C++, so that compiled code can be called from JavaScript as if it were a normal JavaScript library. The *WebIDL Binder* uses `WebIDL `_ to define the bindings, an interface language that was *specifically designed* for gluing together C++ and JavaScript. Not only is this a natural choice for the bindings, but because it is low-level it is relatively easy to optimize. @@ -16,16 +16,16 @@ This topic shows how bind and use C++ classes, functions and other types using I A quick example -=============== +=============== -Binding using the *WebIDL Binder* is a three-stage process: +Binding using the *WebIDL Binder* is a three-stage process: - Create a WebIDL file that describes the C++ interface. - Use the binder to generate C++ and JavaScript "glue" code. -- Compile this glue code with the Emscripten project. +- Compile this glue code with the Emscripten project. -Defining the WebIDL file +Defining the WebIDL file ------------------------ The first step is to create a *WebIDL file* that describes the C++ types you are going to bind. This file will duplicate some of the information in the C++ header file, in a format that is explicitly designed both for easy parsing, and for representing code items. @@ -63,7 +63,7 @@ The following IDL file can be used to describe them: The mapping between the IDL definition and the C++ is fairly obvious. The main things to notice are: - - The IDL class definitions include a function returning ``void`` that has the same name as the interface. This constructor allows you to create the object from JavaScript, and must be defined in IDL even if the C++ uses the default constructor (see ``Foo`` above). + - The IDL class definitions include a function returning ``void`` that has the same name as the interface. This constructor allows you to create the object from JavaScript, and must be defined in IDL even if the C++ uses the default constructor (see ``Foo`` above). - The type names in WebIDL are not identical to those in C++ (for example, ``int`` maps to ``long`` above). For more information about the mappings see :ref:`webidl-binder-type-name`. .. note:: ``structs`` are defined in the same way as the classes above — using the ``interface`` keyword. @@ -91,11 +91,11 @@ To use the glue code files (``glue.cpp`` and ``glue.js``) in a project: .. code-block:: cpp - #include <...> // Where "..." represents the headers for the classes we are binding. + #include <...> // Where "..." represents the headers for the classes we are binding. #include .. note:: The C++ glue code emitted by the *bindings generator* does not include the headers for the classes it binds because they are not present in the Web IDL file. The step above makes these available to the glue code. Another alternative would be to include the headers at the top of **glue.cpp**, but then they would be overwritten every time the IDL file is recompiled. - + #. Add **my_glue_wrapper.cpp** to the final *emcc* command. @@ -138,9 +138,9 @@ for convenience. Using C++ classes in JavaScript -================================ +================================ -Once binding is complete, C++ objects can be created and used in JavaScript as though they were normal JavaScript objects. For example, continuing the above example, you can create the ``Foo`` and ``Bar`` objects and call methods on them. +Once binding is complete, C++ objects can be created and used in JavaScript as though they were normal JavaScript objects. For example, continuing the above example, you can create the ``Foo`` and ``Bar`` objects and call methods on them. .. code-block:: javascript @@ -151,7 +151,7 @@ Once binding is complete, C++ objects can be created and used in JavaScript as t var b = new Module.Bar(123); b.doSomething(); -.. important:: Always access objects through the :ref:`module` object, as shown above. +.. important:: Always access objects through the :ref:`module` object, as shown above. While the objects are also available in the global namespace by default, there are cases where they will not be (for example, if you use the :term:`closure compiler` to minify code or wrap compiled code in a function to avoid polluting the global namespace). You can of course use whatever name you like for the module by assigning it to a new variable: ``var MyModuleName = Module;``. @@ -166,10 +166,10 @@ If a C++ object does need to be cleaned up, you must explicitly call :js:func:`M var b = new Module.Bar(123); b.doSomething(); Module.destroy(b); // If the C++ object requires clean up - + .. note:: The C++ constructor is called transparently when a C++ object is created in JavaScript. There is no way, however, to tell if a JavaScript object is about to be garbage collected, so the binder glue code can't automatically call the destructor. - You will usually need to destroy the objects which you create, but this depends on the library being ported. + You will usually need to destroy the objects which you create, but this depends on the library being ported. Pointers, References, Value types (Ref and Value) @@ -180,24 +180,24 @@ C++ arguments and return types can be pointers, references, or value types (allo Undecorated argument and return values in the IDL are assumed to be *pointers* in the C++: .. code-block:: cpp - + // C++ MyClass* process(MyClass* input); - + .. code-block:: idl - + // WebIDL - MyClass process(MyClass input); + MyClass process(MyClass input); References should be decorated using ``[Ref]``: .. code-block:: cpp - + // C++ MyClass& process(MyClass& input); - + .. code-block:: idl - + // WebIDL [Ref] MyClass process([Ref] MyClass input); @@ -206,26 +206,26 @@ References should be decorated using ``[Ref]``: If the C++ returns an object (rather than a reference or a pointer) then the return type should be decorated using ``[Value]``. This will allocate a static (singleton) instance of that class and return it. You should use it immediately, and drop any references to it after use. .. code-block:: cpp - + // C++ MyClass process(MyClass& input); - + .. code-block:: idl - + // WebIDL [Value] MyClass process([Ref] MyClass input); -Const +Const ===== C++ arguments or return types that use ``const`` can be specified in IDL using ``[Const]``. -For example, the following code fragments show the C++ and IDL for a function that returns a constant pointer object. +For example, the following code fragments show the C++ and IDL for a function that returns a constant pointer object. .. code-block:: cpp - + //C++ const myObject* getAsConst(); @@ -237,7 +237,7 @@ For example, the following code fragments show the C++ and IDL for a function th Attributes that correspond to const data members must be specified with the ``readonly`` keyword, not with ``[Const]``. For example: .. code-block:: cpp - + //C++ const int numericalConstant; @@ -290,16 +290,16 @@ You can bind to C++ operators using ``[Operator=]``: [Operator="+="] TYPE1 add(TYPE2 x); -.. note:: +.. note:: - - The operator name can be anything (``add`` is just an example). + - The operator name can be anything (``add`` is just an example). - Support is currently limited to operators that contain ``=``: ``+=``, ``*=``, ``-=`` etc., and to the array indexing operator ``[]``. enums ===== -Enums are declared very similarly in C++ and IDL: +Enums are declared very similarly in C++ and IDL: .. code-block:: cpp @@ -319,7 +319,7 @@ The syntax is slightly more complicated for enums declared inside a namespace: .. code-block:: cpp - // C++ + // C++ namespace EnumNamespace { enum EnumInNamespace { e_namespace_val = 78 @@ -329,13 +329,13 @@ The syntax is slightly more complicated for enums declared inside a namespace: // WebIDL enum EnumNamespace_EnumInNamespace { "EnumNamespace::e_namespace_val" - }; + }; When the enum is defined inside a class, the IDL definitions for the enum and class interface are separate: .. code-block:: cpp - // C++ + // C++ class EnumClass { public: enum EnumWithinClass { @@ -344,8 +344,8 @@ When the enum is defined inside a class, the IDL definitions for the enum and cl EnumWithinClass GetEnum() { return e_val; } EnumNamespace::EnumInNamespace GetEnumFromNameSpace() { return EnumNamespace::e_namespace_val; } - }; - + }; + // WebIDL @@ -366,7 +366,7 @@ When the enum is defined inside a class, the IDL definitions for the enum and cl Sub-classing C++ base classes in JavaScript (JSImplementation) =============================================================== -The *WebIDL Binder* allows C++ base classes to be sub-classed in JavaScript. In the IDL fragment below, ``JSImplementation="Base"`` means that the associated interface (``ImplJS``) will be a JavaScript implementation of the C++ class ``Base``. +The *WebIDL Binder* allows C++ base classes to be sub-classed in JavaScript. In the IDL fragment below, ``JSImplementation="Base"`` means that the associated interface (``ImplJS``) will be a JavaScript implementation of the C++ class ``Base``. .. code-block:: idl @@ -386,7 +386,7 @@ After running the bindings generator and compiling, you can implement the interf When C++ code has a pointer to a ``Base`` instance and calls ``virtualFunc()``, that call will reach the JavaScript code defined above. -.. note:: +.. note:: - You *must* implement all the methods you mentioned in the IDL of the ``JSImplementation`` class (``ImplJS``) or compilation will fail with an error. - You will also need to provide an interface definition for the ``Base`` class in the IDL file. @@ -396,26 +396,26 @@ Pointers and comparisons All the binding functions expect to receive wrapper objects (which contain a raw pointer) rather than a raw pointer. You shouldn't normally need to deal with raw pointers (these are simply memory addresses/integers). If you do, the following functions in the compiled code can be useful: -- ``wrapPointer(ptr, Class)`` — Given a raw pointer (an integer), returns a wrapped object. +- ``wrapPointer(ptr, Class)`` — Given a raw pointer (an integer), returns a wrapped object. .. note:: If you do not pass the ``Class``, it will be assumed to be the root class — this probably isn't what you want! - + - ``getPointer(object)`` — Returns a raw pointer. - ``castObject(object, Class)`` — Returns a wrapping of the same pointer but to another class. - ``compare(object1, object2)`` — Compares two objects' pointers. -.. note:: There is always a *single* wrapped object for a certain pointer to a certain class. This allows you to add data on that object and use it elsewhere using normal JavaScript syntax (``object.attribute = someData`` etc.) +.. note:: There is always a *single* wrapped object for a certain pointer to a certain class. This allows you to add data on that object and use it elsewhere using normal JavaScript syntax (``object.attribute = someData`` etc.) + + ``compare()`` should be used instead of direct pointer comparison because it is possible to have different wrapped objects with the same pointer if one class is a subclass of the other. - ``compare()`` should be used instead of direct pointer comparison because it is possible to have different wrapped objects with the same pointer if one class is a subclass of the other. - NULL ==== All the binding functions that return pointers, references, or objects will return wrapped pointers. The reason is that by always returning a wrapper, you can take the output and pass it to another binding function without that function needing to check the type of the argument. -One case where this can be confusing is when returning a ``NULL`` pointer. When using bindings, the returned pointer will be ``NULL`` (a global singleton with a wrapped pointer of 0) rather than ``null`` (the JavaScript built-in object) or 0. +One case where this can be confusing is when returning a ``NULL`` pointer. When using bindings, the returned pointer will be ``NULL`` (a global singleton with a wrapped pointer of 0) rather than ``null`` (the JavaScript built-in object) or 0. .. _webidl-binder-voidstar: @@ -423,7 +423,7 @@ One case where this can be confusing is when returning a ``NULL`` pointer. When void* ===== -The ``void*`` type is supported through a ``VoidPtr`` type that you can use in IDL files. You can also use the ``any`` type. +The ``void*`` type is supported through a ``VoidPtr`` type that you can use in IDL files. You can also use the ``any`` type. The difference between them is that ``VoidPtr`` behaves like a pointer type in that you get a wrapper object, while ``any`` behaves like a 32-bit integer (which is what raw pointers are in Emscripten-compiled code). @@ -435,23 +435,23 @@ WebIDL types The type names in WebIDL are not identical to those in C++. This section shows the mapping for the more common types you'll encounter. -.. csv-table:: +.. csv-table:: :header: "C++", "IDL" :widths: 50, 50 - "``bool``", "``boolean``" + "``bool``", "``boolean``" "``float``", "``float``" "``double``", "``double``" - "``char``", "``byte``" + "``char``", "``byte``" "``char*``", "``DOMString`` (represents a JavaScript string)" - "``unsigned char``", "``octet``" - "``unsigned short int``", "``unsigned short``" - "``unsigned short``", "``unsigned short``" - "``unsigned long``", "``unsigned long``" - "``int``", "``long``" + "``unsigned char``", "``octet``" + "``unsigned short int``", "``unsigned short``" + "``unsigned short``", "``unsigned short``" + "``unsigned long``", "``unsigned long``" + "``int``", "``long``" "``void``", "``void``" "``void*``", "``any`` or ``VoidPtr`` (see :ref:`webidl-binder-voidstar`)" - + .. note:: The WebIDL types are fully documented in `this W3C specification `_. @@ -460,6 +460,6 @@ The type names in WebIDL are not identical to those in C++. This section shows t Test and example code ===================== -For a complete working example, see `test_webidl `_ in the `test suite `_. The test suite code is guaranteed to work and covers more cases than this article alone. +For a complete working example, see `test_webidl `_ in the `test suite `_. The test suite code is guaranteed to work and covers more cases than this article alone. Another good example is `ammo.js `_, which uses the *WebIDL Binder* to port the `Bullet Physics engine `_ to the Web. diff --git a/site/source/docs/porting/connecting_cpp_and_javascript/index.rst b/site/source/docs/porting/connecting_cpp_and_javascript/index.rst index cd08f9b067d66..d24ca32b94d08 100644 --- a/site/source/docs/porting/connecting_cpp_and_javascript/index.rst +++ b/site/source/docs/porting/connecting_cpp_and_javascript/index.rst @@ -4,16 +4,16 @@ Connecting C++ and JavaScript ============================= -Emscripten provides various options for connecting "normal" JavaScript and compiled code, which range from functions to call compiled C/C++ from JavaScript (and vice versa) through to accessing environment variables from compiled code. +Emscripten provides various options for connecting "normal" JavaScript and compiled code, which range from functions to call compiled C/C++ from JavaScript (and vice versa) through to accessing environment variables from compiled code. The topic :ref:`Interacting-with-code` provides an overview of all the methods. The other two topics provide additional detail on the :ref:`Embind` and :ref:`WebIDL-Binder` tools. -.. note:: For information on how compiled code interacts with the browser environment, see :ref:`emscripten-runtime-environment`. For file system-related manners, see the :ref:`file-system-overview`. +.. note:: For information on how compiled code interacts with the browser environment, see :ref:`emscripten-runtime-environment`. For file system-related manners, see the :ref:`file-system-overview`. .. toctree:: :maxdepth: 1 - + Interacting-with-code embind WebIDL-Binder - + diff --git a/site/source/docs/porting/emscripten-runtime-environment.rst b/site/source/docs/porting/emscripten-runtime-environment.rst index 0117f13b88673..75e73954557ae 100644 --- a/site/source/docs/porting/emscripten-runtime-environment.rst +++ b/site/source/docs/porting/emscripten-runtime-environment.rst @@ -4,7 +4,7 @@ Emscripten Runtime Environment ============================== -The Emscripten runtime environment is different to that expected by most C/C++ applications. Emscripten works hard to abstract and mitigate these differences, so that in general code can be compiled with little or no change. +The Emscripten runtime environment is different to that expected by most C/C++ applications. Emscripten works hard to abstract and mitigate these differences, so that in general code can be compiled with little or no change. This article expands on some of the differences and the resulting :ref:`api-limitations`, and outlines the few changes you may need to make to your C/C++ code. @@ -26,7 +26,7 @@ File Systems A lot of C/C++ code uses the synchronous file system APIs in *libc* and *libcxx* to access code in the local file system. This is problematic because the browser prevents code from directly accessing files on the host system, and because JavaScript only supports asynchronous file access outside of web workers. -Emscripten provides an implementation of *libc* and *libcxx* and a *virtual file system* so that normal C/C++ code can be compiled and run without change. Most developers need only specify the set of files to be :ref:`packaged ` for preloading into the virtual file system at runtime. +Emscripten provides an implementation of *libc* and *libcxx* and a *virtual file system* so that normal C/C++ code can be compiled and run without change. Most developers need only specify the set of files to be :ref:`packaged ` for preloading into the virtual file system at runtime. .. note:: Using a virtual file system bypasses the limitations listed above. The file data is packaged at compile time and downloaded into the file system using *asynchronous* JavaScript APIs before the compiled code is allowed to run. The compiled code then makes "file" calls that are really just calls into program memory. @@ -55,9 +55,9 @@ Implementing an asynchronous main loop in C/C++ The standard solution for this problem is to define a C function that performs one iteration of your main loop (not including the "delay"). For a native build this function can be called in an infinite loop, leaving the behaviour effectively unchanged. -Within Emscripten compiled code we use :c:func:`emscripten_set_main_loop` to get the environment to call this same function at a specified frequency. The iteration is still run "infinitely" but now other code can run between iterations and the browser does not hang. +Within Emscripten compiled code we use :c:func:`emscripten_set_main_loop` to get the environment to call this same function at a specified frequency. The iteration is still run "infinitely" but now other code can run between iterations and the browser does not hang. -.. todo:: Check this statement out: (just call it from JavaScript, all you need is an underscore at the beginning of the name), +.. todo:: Check this statement out: (just call it from JavaScript, all you need is an underscore at the beginning of the name), Typically you will have a small section with ``#ifdef __EMSCRIPTEN__`` for the two cases. For example: @@ -83,28 +83,28 @@ Typically you will have a small section with ``#ifdef __EMSCRIPTEN__`` for the t // render to screen } - + .. note:: When using SDL you will probably need to set the main loop. You should also note: - - The current Emscripten implementation of ``SDL_QUIT`` will work if you use :c:func:`emscripten_set_main_loop`. As the page is shut, it will force a final direct call to the main loop, giving it a chance to notice the ``SDL_QUIT`` event. If you do not use a main loop, your app will close before you have had an opportunity to notice this event. + - The current Emscripten implementation of ``SDL_QUIT`` will work if you use :c:func:`emscripten_set_main_loop`. As the page is shut, it will force a final direct call to the main loop, giving it a chance to notice the ``SDL_QUIT`` event. If you do not use a main loop, your app will close before you have had an opportunity to notice this event. - There are limitations to what you can do as the page shuts (in ``onunload``). Some actions like showing alerts are banned by browsers at this point. Execution lifecycle =================== -When an Emscripten-compiled application is loaded, it starts by preparing data in the ``preloading`` phase. Files you marked for :ref:`preloading ` (using ``emcc --preload-file``, or manually from JavaScript with :js:func:`FS.createPreloadedFile`) are set up at this stage. +When an Emscripten-compiled application is loaded, it starts by preparing data in the ``preloading`` phase. Files you marked for :ref:`preloading ` (using ``emcc --preload-file``, or manually from JavaScript with :js:func:`FS.createPreloadedFile`) are set up at this stage. -You can add additional operations with :js:func:`addRunDependency`, which is a counter of all dependencies to be executed before compiled code can run. As these are completed you can call :js:func:`removeRunDependency` to remove the completed dependencies. +You can add additional operations with :js:func:`addRunDependency`, which is a counter of all dependencies to be executed before compiled code can run. As these are completed you can call :js:func:`removeRunDependency` to remove the completed dependencies. .. note:: Generally it is not necessary to add additional operations — preloading is suitable for almost all use cases. -When all dependencies are met, Emscripten will call ``run()``, which proceeds to call your ``main()`` function. The ``main()`` function should be used to perform initialization tasks, and will often call :c:func:`emscripten_set_main_loop` (as :ref:`described above `). The main loop function will be then be called at the requested frequency. +When all dependencies are met, Emscripten will call ``run()``, which proceeds to call your ``main()`` function. The ``main()`` function should be used to perform initialization tasks, and will often call :c:func:`emscripten_set_main_loop` (as :ref:`described above `). The main loop function will be then be called at the requested frequency. You can affect the operation of the main loop in several ways: -- - :c:func:`emscripten_push_main_loop_blocker` adds a function that **blocks** the main loop until the blocker completes. +- + :c:func:`emscripten_push_main_loop_blocker` adds a function that **blocks** the main loop until the blocker completes. This is useful, for example, to manage loading new game levels. After a level completes, you can push blockers for each action involved (unpacking the file, generate the data structures, etc.) When all the blockers have completed the main loop will resume and the game should run the new level. You can also use this function in conjunction with :c:func:`emscripten_set_main_loop_expected_blockers` to keep the user informed of progress. @@ -120,13 +120,13 @@ The :ref:`browser execution environment reference (emscripten.h) `_, with different *views* providing access to different types (:js:data:`HEAPU32` for 32-bit unsigned integers, etc.) +Emscripten's memory model is known as :term:`Typed Arrays Mode 2`. It represents memory using a single `typed array `_, with different *views* providing access to different types (:js:data:`HEAPU32` for 32-bit unsigned integers, etc.) -.. note:: *Typed Arrays Mode 2* is the *only* memory model supported by the :ref:`Fastcomp ` compiler, and it is the *default* memory model for the :ref:`old compiler `. +.. note:: *Typed Arrays Mode 2* is the *only* memory model supported by the :ref:`Fastcomp ` compiler, and it is the *default* memory model for the :ref:`old compiler `. - Compared to other models tried by the project, it can be used for a broad range of arbitrary compiled code, and is relatively fast. + Compared to other models tried by the project, it can be used for a broad range of arbitrary compiled code, and is relatively fast. -The model lays out items in memory in the same way as with normal C and C++, and as a result it uses the same amount of memory. +The model lays out items in memory in the same way as with normal C and C++, and as a result it uses the same amount of memory. This model allows you to use code that violates the :term:`load-store consistency` assumption. Since the different views show the same data, you can (say) write a 32-bit integer, then read a byte from the middle, and it will work just like in a native build of C or C++ on most platforms. diff --git a/site/source/docs/porting/files/Synchronous-Virtual-XHR-Backed-File-System-Usage.rst b/site/source/docs/porting/files/Synchronous-Virtual-XHR-Backed-File-System-Usage.rst index 9c7d93dac0dfc..d6e21e0364234 100644 --- a/site/source/docs/porting/files/Synchronous-Virtual-XHR-Backed-File-System-Usage.rst +++ b/site/source/docs/porting/files/Synchronous-Virtual-XHR-Backed-File-System-Usage.rst @@ -6,7 +6,7 @@ Synchronous Virtual XHR Backed File System Usage Emscripten supports lazy loading of binary data from HTTP servers using :term:`XHR`. This functionality can be used to create a backend for synchronous file access from compiled code. -The backend can improve start up time as the whole file system does not need to be preloaded before compiled code is run. It can also be very efficient if the web server supports `byte serving `_ — in this case Emscripten can just read the parts of files that are actually needed. +The backend can improve start up time as the whole file system does not need to be preloaded before compiled code is run. It can also be very efficient if the web server supports `byte serving `_ — in this case Emscripten can just read the parts of files that are actually needed. .. warning:: This mechanism is only possible in `Web Workers `_ (due to browser limitations). @@ -20,31 +20,31 @@ An example of how to implement a synchronous virtual XHR backed file system is p The tests use `checksummer.c `_ as the Emscripten-compiled program. This is simply a vanilla C program using synchronous *libc* file system calls like ``fopen()``, ``fread()``, ``fclose()`` etc. -JavaScript code is added (using *emcc*'s :ref:`pre-js ` option) to map the file system calls in **checksummer.c** to a file in the virtual file system. This file is *created* early in Emscripten initialisation using :js:func:`FS.createLazyFile`, but only loaded with content from the server when the file is first accessed by compiled code. The added JavaScript code also sets up communication between the web worker and the main thread. +JavaScript code is added (using *emcc*'s :ref:`pre-js ` option) to map the file system calls in **checksummer.c** to a file in the virtual file system. This file is *created* early in Emscripten initialisation using :js:func:`FS.createLazyFile`, but only loaded with content from the server when the file is first accessed by compiled code. The added JavaScript code also sets up communication between the web worker and the main thread. Instructions ============ -#. - You will need to add JavaScript to the generated code to map the file accessed by your compiled native code and the server. - +#. + You will need to add JavaScript to the generated code to map the file accessed by your compiled native code and the server. + The test code simply creates a file in the virtual file system using :js:func:`FS.createLazyFile` and sets the compiled code to use the same file (**/bigfile**): .. include:: ../../../../../tests/test_browser.py :literal: :start-after: prejs_file.write(r""" :end-before: var doTrace = true; - :code: javascript + :code: javascript .. note:: - + - The compiled test code (in this case) gets the file name from command line arguments — these are set in Emscripten using :js:attr:`Module.arguments`. - The call to create the file is added to :js:attr:`Module.preInit`. This ensures that it is run before any compiled code. - The additional JavaScript is added using *emcc*'s :ref:`prejs ` option. -#. - The added JavaScript should also include code to allow the web worker to communicate with the original thread. +#. + The added JavaScript should also include code to allow the web worker to communicate with the original thread. The test code adds the following JavaScript to the web worker for this purpose. It uses ``postMessage()`` to send its ``stdout`` back to the main thread. @@ -52,13 +52,13 @@ Instructions :literal: :start-after: var doTrace = true; :end-before: """) - :code: javascript - + :code: javascript + .. note:: If you use the above solution, the parent page should probably contain handwritten glue code to handle the ``stdout`` data. - -#. - You will need a page that spawns the web worker. - + +#. + You will need a page that spawns the web worker. + The `test code `_ that does this is shown below: .. include:: ../../../../../tests/test_browser.py @@ -72,4 +72,4 @@ Instructions - + diff --git a/site/source/docs/porting/files/file_systems_overview.rst b/site/source/docs/porting/files/file_systems_overview.rst index 3f3ef99c8fd71..cc69c4826d348 100644 --- a/site/source/docs/porting/files/file_systems_overview.rst +++ b/site/source/docs/porting/files/file_systems_overview.rst @@ -13,7 +13,7 @@ Emscripten file system runtime environment Native code and "normal" JavaScript use quite different file-access paradigms. Portable native code usually calls *synchronous* file APIs in **libc** and **libcxx**, while JavaScript allows only *asynchronous* file access (except in web workers). In addition, JavaScript does not have direct access to the host file system when run inside the sandbox environment provided by a web browser. -Emscripten provides a virtual file system that simulates the local file system, so that native code using synchronous file APIs can be compiled and run with little or no change. +Emscripten provides a virtual file system that simulates the local file system, so that native code using synchronous file APIs can be compiled and run with little or no change. :ref:`packaging-files` explains how you can use *emcc* to specify which files you need to include in the file system. For many developers, that may be all you need to do. @@ -22,7 +22,7 @@ Emscripten provides a virtual file system that simulates the local file system, Emscripten file system architecture =================================== -The main elements of the Emscripten File System architecture are shown below. Most native code will call the *synchronous* file APIs in **libc** and **libcxx**. These in turn call the underlying :ref:`File System API `, which by default uses the :ref:`MEMFS ` virtual file system. +The main elements of the Emscripten File System architecture are shown below. Most native code will call the *synchronous* file APIs in **libc** and **libcxx**. These in turn call the underlying :ref:`File System API `, which by default uses the :ref:`MEMFS ` virtual file system. .. figure:: FileSystemArchitecture.png :alt: File System Architecture @@ -32,6 +32,6 @@ The main elements of the Emscripten File System architecture are shown below. Mo With ``MEMFS`` all files exist strictly in-memory, and any data written to them is lost when the page is reloaded. If persistent data is required you can mount the :ref:`IDBFS ` file system in a browser or :ref:`NODEFS ` on *node.js*. :ref:`NODEFS ` provides direct access to the local file system, but only when run inside *node.js*. You can call the :ref:`File System API ` directly from your own JavaScript to mount new file systems, and to perform other synchronous file system operations that might be required. There is more information on this topic in :ref:`filesystem-api-filesystems`. -If you need to fetch other files from the network to the file system then use :c:func:`emscripten_wget` and the other methods in the :ref:`emscripten-h-asynchronous-file-system-api`. These methods are asynchronous and the application must wait until the registered callback completes before trying to read them. - +If you need to fetch other files from the network to the file system then use :c:func:`emscripten_wget` and the other methods in the :ref:`emscripten-h-asynchronous-file-system-api`. These methods are asynchronous and the application must wait until the registered callback completes before trying to read them. + diff --git a/site/source/docs/porting/files/index.rst b/site/source/docs/porting/files/index.rst index dd889e383dc53..afb70b53a4cab 100644 --- a/site/source/docs/porting/files/index.rst +++ b/site/source/docs/porting/files/index.rst @@ -6,8 +6,8 @@ Files and File Systems This section contains articles related to using files in Emscripten-compiled code. -- The :ref:`file-system-overview` provides a high level overview of how file operations are supported by Emscripten. -- :ref:`packaging-files` shows how to use :ref:`emcc ` to package the files needed by compiled code. +- The :ref:`file-system-overview` provides a high level overview of how file operations are supported by Emscripten. +- :ref:`packaging-files` shows how to use :ref:`emcc ` to package the files needed by compiled code. - :ref:`Synchronous-Virtual-XHR-Backed-File-System-Usage` explains how to setup lazy loading of binary data from HTTP servers using XHR’s. .. seealso:: API Reference: @@ -17,7 +17,7 @@ This section contains articles related to using files in Emscripten-compiled cod .. toctree:: :hidden: - + file_systems_overview packaging_files Synchronous-Virtual-XHR-Backed-File-System-Usage diff --git a/site/source/docs/porting/files/packaging_files.rst b/site/source/docs/porting/files/packaging_files.rst index d640db8c9a488..2d5dc2bfab064 100644 --- a/site/source/docs/porting/files/packaging_files.rst +++ b/site/source/docs/porting/files/packaging_files.rst @@ -4,10 +4,10 @@ Packaging Files =============== -This topic shows how to package the files that will be used to populate :ref:`Emscripten's virtual file system ` when the page is loaded. +This topic shows how to package the files that will be used to populate :ref:`Emscripten's virtual file system ` when the page is loaded. There are two alternatives for how files are packaged: *preloading* and *embedding*. Embedding puts the specified files inside the generated JavaScript, while preloading packages the files separately. Embedding files is much less efficient than preloading and should only be used when packaging small numbers of small files. Preloading also enables the option to separately host the data. - + *Emcc* uses the *file packager* to package the files and generate the :ref:`File System API ` calls that create and load the file system at run time. While *Emcc* is the recommended tool for packaging, there are cases where it can make sense to run the *file packager* manually. @@ -21,9 +21,9 @@ The command below shows how to package files for preloading: .. code-block:: bash ./emcc file.cpp -o file.html --preload-file asset_dir - + The command generates **file.html**, **file.js** and **file.data**. The **.data** file contains all the files in **asset_dir/**, and is loaded by **file.js**. - + .. note:: The :ref:`Tutorial ` demonstrates preloading using the **hello_world_file.cpp** test code. @@ -34,7 +34,7 @@ The command for embedding is shown below. In this case *emcc* generates **file.h ./emcc file.cpp -o file.html --embed-file asset_dir -By default, the files to be packaged should be nested in or below the compile-time command prompt directory. At runtime the same nested file structure is mapped to the virtual file system, with the root corresponding to the command prompt directory. +By default, the files to be packaged should be nested in or below the compile-time command prompt directory. At runtime the same nested file structure is mapped to the virtual file system, with the root corresponding to the command prompt directory. For example, consider a file structure **dir1/dir2/dir3/asset_dir/** where the project is compiled from **dir2**. When we package **asset_dir**, we specify its relative location **dir3/asset_dir/**: @@ -49,25 +49,25 @@ The ``@`` symbol can be used to map packaged files from any location in the loca .. _packaging-files-file-packager: -Packaging using the file packager tool +Packaging using the file packager tool ====================================== -You can also run the *file packager* manually using the instructions at the top of `file_packager.py `_. +You can also run the *file packager* manually using the instructions at the top of `file_packager.py `_. The file packager generates a **.data** file and **.js** file. The **.js** file contains the code to use the data file, and must be loaded *before* loading your main compiled code. .. note:: - - Using the *file packager* allows you to run file packaging separately from compiling the code. + - Using the *file packager* allows you to run file packaging separately from compiling the code. - You can load multiple datafiles by running the file packager on each and loading the **.js** outputs. See `BananaBread `_ for an example of this (`cube2/js/game-setup.js `_). - + .. _packaging-files-data-file-location: Changing the data file location =============================== -By default, the **.data** file containing all the preloaded files is loaded from the same URL as your **.js** file. In some cases it may be useful to have the data file in a different location from the other files — for example if your **.html** and **.js** change a lot you may want to keep the data file on a fast CDN somewhere else. +By default, the **.data** file containing all the preloaded files is loaded from the same URL as your **.js** file. In some cases it may be useful to have the data file in a different location from the other files — for example if your **.html** and **.js** change a lot you may want to keep the data file on a fast CDN somewhere else. This model is supported by changing the :js:attr:`Module.filePackagePrefixURL` to be the URL where the data file is stored (this is a prefix, so should include the full path before the data's file name). The attribute must be specified in a ``