Quantcast
Channel: Intermediate
Viewing all 664 articles
Browse latest View live

Understanding the Intel® XDK Cordova Build Options

$
0
0

NOTE: the beta release of the Intel XDK Cordova build system (versions 0876 and earlier of the Intel XDK) required that you create a special build config file (aka intelxdk.config.xml) and include it with your HTML5 mobile app sources before submitting your application to the Cordova build system. That build config file is described by this document. In the production release of the Intel XDK Cordova build system, this build config file is generated automatically, based on information you provide about your app in the Projects tab. This document describes many of the directives you will see in the automatically generated build config files. It can also be used to help you create an intelxdk.config.additions.xml file to control special build options that are not handled by the Projects tab GUI.

The Intel® XDK Cordova build system uses special configuration files in your project directory to control the build process. The Cordova build option is based on the open source Apache* Cordova CLI build system. When using the Cordova build option your application project files are submitted to a Cordova CLI system that is hosted and maintained on the Intel XDK build server, there is no need to install the open source Cordova CLI system on your workstation.

NOTE: the Adobe* PhoneGap* CLI system and the Google* Mobile Chrome Apps project (aka cca) are based on the same Apache Cordova CLI open source project.

Because this build system is derived directly from the Cordova CLI open source project, the build control files share many options with the Cordova CLI config.xml file(s) you will find in a local Cordova CLI (or PhoneGap CLI) build environment. The options used in the Intel XDK build configuration file are a superset of those used in the Cordova CLI config.xml file.

NOTE: The config.xml file used to direct the cloud-based Adobe* PhoneGap Build* environment is unique to PhoneGap Build; it is also a superset of the Cordova CLI config.xml file. You may find similarities between the Intel XDK configuration file and that used by PhoneGap Build, but they are neither compatible nor interchangeable. If you have an existing PhoneGap project you will need to create an Intel XDK configuration file first before you build your project with the Intel XDK.

At the time this document was written the build system was using Cordova 3.3.1-0.1.2.

The intelxdk.config.<platform>.xml File

The intelxdk.config.<platform>.xml file controls the behavior and application specific properties of the Intel XDK Cordova and Crosswalk build targets. This file follows the W3C Packaged Web Apps (Widgets) specification. The name space used for settings unique to the Intel XDK build system are still under development and; therefore, are subject to change.

NOTE: intelxdk.config.<platform>.xml files are automatically generated by a GUI interface on the Projects tab (beginning with release 1199 of the Intel XDK). A user-editable intelxdk.config.additions.xml configuration file is provided as a way to handle special case configuration options that are not dealt with by the build GUI interface. The features described in this document can be used within that intelxdk.config.additions.xml configuration file.

A reference intelxdk.config.xml file is maintained on github to show you most of the preferences that can be included in a build configuration file. Since the Intel XDK Projects tab generates the intelxdk.config.<platform>.xml files automatically, this file should be considered as a reference for understanding what options can be added to your intelxdk.config.additions.xml configuration file.

The intelxdk Namespace

A namespace is required to designate this file for use by the Intel XDK. The following namespace entry (which is subject to change) must be present in the intelxdk.config.xml file if any intelxdk namespace entries are used in the configuration file.

xmlns:intelxdk="http://xdk.intel.com/ns/v1"

Options Common to All Cordova Platforms

For a full list of Cordova supported settings see the Apache Cordova config.xml File Documentation.  The settings described below are either modifications of or additions to the standard Cordova settings designed for use with the Intel XDK build system.

Standard Cordova Plugins

The plugin package names listed below represent the available "core" Cordova APIs. These plugins can be selected via the Projects tab GUI and automatically included in the respective platform build config files.

Plugin NamePlugin ValueNotes
Accelerometerorg.apache.cordova.device-motion 
Cameraorg.apache.cordova.camera 
Captureorg.apache.cordova.media-capture 
Compass org.apache.cordova.device-orientation 
Connectionorg.apache.cordova.network-information 
Contactsorg.apache.cordova.contacts 
Deviceorg.apache.cordova.device 
Events (battery status)org.apache.cordova.battery-status 
Fileorg.apache.cordova.file 
Geolocationorg.apache.cordova.geolocation 
Globalizationorg.apache.cordova.globalization 
InAppBrowserorg.apache.cordova.inappbrowser Plugin version 0.3.0 is recommended.
Media org.apache.cordova.mediaRequires the Cordova File plugin.
Dialogs (notification)org.apache.cordova.dialogs 
Vibration (notification) org.apache.cordova.vibration 
Splash Screen org.apache.cordova.splashscreen 


See the Cordova API Reference Documentation for API and platform details regarding the "core" Cordova API plugins.

If you do not specify a plugin version the latest available version will be included by the build system. In some cases, this may result in problems or incompatibilities. The notes section indicates a recommended version where problems are known to exist and a known good version should be specified, instead of using the latest version of the plugin.

Intel XDK Plugins

The plugin package names listed below represent the available Intel XDK APIs. These plugins can be selected via the Projects tab GUI and automatically included in the respective platform build config files.

Plugin NamePlugin ValueNotes
Baseintel.xdk.base 
Accelerometerintel.xdk.accelerometer 
Audiointel.xdk.audio 
Cacheintel.xdk.cache 
Cameraintel.xdk.camera 
Contactsintel.xdk.contacts 
Deviceintel.xdk.deviceAndroid and Crosswalk, only. Other platforms under development.
Displayintel.xdk.display 
Facebookintel.xdk.facebookRequires the FBAPPID parameter == Facebook Application ID.
Android, only. Other platforms under development.
Fileintel.xdk.file 
Geolocationintel.xdk.geolocation 
Notificationintel.xdk.notification 
Playerintel.xdk.player 

See the Intel XDK API Reference Documentation for API and platform details about the Intel XDK API plugins.

NOTE: Some plugins (Cordova, Intel XDK and third-party) include device permissions that will automatically be added to your application, and must be acknowledged by the end user of your application during installation on their mobile device, or when they run your application (specific behavior is platform-dependent). Including unneeded plugins may result in an inappropriate list of permissions for your app. The specific permissions associated with a plugin, if any, vary as a function of the platform.

Build Config Directives Specific to the Intel XDK

See Adding Plugins to Your Intel® XDK Cordova App for instructions on how to use third-party Cordova plugins as a way of extending your app's JavaScript API for access to unique device and platform features.

Including Cordova Plugins
The Plugin tag allows you to add predefined plugins to your application at build time. It is constructed as follows:
<intelxdk:plugin intelxdk:name="<NAME>" intelxdk:value="<VALUE>" intelxdk:version=”<VERSION>” />
where:
  • <NAME> is the description of the plugin.
  • <VALUE> is the package name or git repository representing the plugin.
  • <VERSION> is the [optional] version of the plugin (see next section for more info regarding plugin versions).
Some plugins may require, or optionally allow, parameters as part of their installation. Any parameters required by a plugin are specific to that plugin and are documented in that plugin’s documentation. Plugin parameters are added by using the <param> tag:
<intelxdk:plugin intelxdk:name="<NAME>" intelxdk:value="<VALUE>" >
    <intelxdk:param intelxdk:name="<PARMNAME>" intelxdk:value="<PARMVALUE>" />
    .....
    <intelxdk:param intelxdk:name="<PARMNAME>" intelxdk:value="<PARMVALUE>" />
</intelxdk:plugin>
Specifying Custom Icons
The icon tag provides a mechanism to add launch (home screen) icons to your application.
<icon platform="<PLATFORM>" src="<SRC>" density="<DENSITY>" height="<HEIGHT>" width="<WIDTH>" />
where:
  • <PLATFORM> indicates for which platform the launch icon will be applied. Valid platforms are android, ios, windows8 and wp8. If this property is not supplied, a default icon is provided by the build system.
  • <SRC> indicates the path of the icon image file relative to the SOURCE DIRECTORY in your project (see the Projects tab in the Intel XDK).
  • <DENSITY> indicates the resolution of the icon image file. This property is required for and only used by Android. Valid values are xhdpi,hdpi, mdpi, and ldpi.
  • <HEIGHT> indicates the height of the icon image file in pixels. This property is required for iOS and optional for other platforms.
  • <WIDTH> indicates the width of the icon image file in pixels. This property is required for iOS and optional for other platforms.
Details regarding icon dimensions, sizes and image types can be found on the respective platform-specific pages (links provided below, in the next section).
Including Custom Splash Screens
The splash tag gives you a way to add a custom splash screen to your application. This static image will be displayed during app initialization for a preset period of time following initialization, or until your application calls the navigator.splashscreen.hide() function, whichever comes first.
<splash platform="<PLATFORM>" src="<SRC>" density="<DENSITY>" width="<WIDTH>" height="<HEIGHT>" orientation="<ORIENTATION>" />
where:
  • <PLATFORM> indicates for which platform the splash screen image will be applied. Valid platforms are android, ios, windows8, and wp8. If this property is not supplied, a default image is provided by the build system.
  • <SRC> indicates the path of the splash screen image file relative to the SOURCE DIRECTORY in your project (see the Projects tab in the Intel XDK).
  • <DENSITY> indicates the resolution of the splash screen image file. This property is required for and only used by Android. Valid values are xhdpi, hdpi, mdpi, and ldpi.
  • <WIDTH> indicates the width of the splash screen image file in pixels. This property is required for iOS and optional for other platforms.
  • <HEIGHT> indicates the height of the splash screen image file in pixels. This property is required for iOS and optional for other platforms.
  • <ORIENTATION> indicates the orientation of the splash screen image. Valid values are "portrait" and "landscape." This property is currently only used by Android platforms.
Details regarding splash screen image dimensions, sizes and file types can be found on the respective platform-specific pages (links provided below, in the next section).

Platform Specific Options

Each Cordova build platform may have additional build options that can be added to the config file. These options are specific to that platform and have no impact on other target platforms.

Follow these links for details regarding platform-specific build options:


Ads for Crosswalk and Construct 2*

$
0
0

Ads for Construct 2 and Crosswalk


Here we will show you how to add AdMob* ads to your Construct 2 application exported for Crosswalk.  These steps will build your application with the Intel® XDK.  

First, sign up for an AdMob account.  Before you can serve any AdMob ads you must sign up for an AdMob account at www.admob.com. There is no cost associated with creating an account, or for serving up AdMob ads within your mobile app. If you already have an AdMob account all you need to do, to use the AdMob plugin, is create the appropriate Ad Unit IDs that identify your ad impressions and provide them as part of the AdMob API initialization sequence within your app. A screenshot of the online AdMob tool you use to create the Ad Unit ID is shown below.

Inside Construct 2, add a new object called "Crosswalk Ads", which will display on Android* builds.   Here you will configure your "Android ID" - which is the ID for your Android banner id.  If you are showing interstitial ads, you will also configure "Android Interstitial" with the id from AdMob.  You can set the banner position to top or bottom, and finally set AdMob into Test Mode.

There are three event actions you can interact with.

  • Show banner ad - will show a banner ad
  • Hide banner ad - will hide/remove the banner ad
  • Show fullscreen add - will show the interstitial ad

 

Exporting

When you are ready to export your application, make sure you export for Crosswalk.  You can then bring this project into the Intel® XDK to build.  Here, we will need to configure a Cordova plugin that will enable the native AdMob ads.  To add the plugin, follow the directions below.

  1. Go to the projects tab
  2. Under "CORDOVA 3.X HYBRID MOBILE APP SETTINGS " click Plugins and Permissions
  3. Click "Third Party Plugins"
  4. Click "Add a Third-Party Plugin"
  5. Click "Get Plugin from the Web"
  6. Enter the following
Name: AdMobPluginPro
Plugin ID: com.google.cordova.admob
[x] Plugin is located in the Apache Cordova Plugins Registry

 

Now you can build your app and test it!  Before you publish, make sure you disable Test Mode in Construct 2.

 

  • Construct 2
  • admob
  • monitiziation
  • Sviluppatori
  • Android*
  • HTML5
  • HTML5
  • Avanzato
  • Principiante
  • Intermedio
  • Intel XDK
  • Strumenti di sviluppo
  • URL
  • Area tema: 

    HTML5

    Improve Intel MKL Performance for Small Problems: The Use of MKL_DIRECT_CALL

    $
    0
    0

    One of the big new features introduced in the Intel MKL 11.2 is the greatly improved performance for small problem sizes. In 11.2, this improvement focuses on xGEMM functions (matrix multiplication). Out of the box, there is already a version-to-version improvement (from Intel MKL 11.1 to Intel MKL 11.2). But on top of it, Intel MKL introduces a new control that can lead to further significant performance boost for small matrices. Users can enable this control when linking with Intel MKL by specifying "-DMKL_DIRECT_CALL" or "-DMKL_DIRECT_CALL_SEQ". At the run time, the execution will be dispatched to a fast path for small input matrices. The fast path skips error checking and multiple layers of function calls, therefore improves performance by reducing associated overhead. The matrix sizes have to be small, for example, only a few dozens of rows and columns. For larger matrices the regular execution path is taken. MKL_DIRECT_CALL and MKL_DIRECT_CALL_SEQ do not help, but do not do any harm either. 

    The chart below is a comparison between 4 scenarios of computing double-precision matrix-matrix multiplication for small matrices (range from 4x4 to 20x20).

    • A naive implementation using triple-nested loops, compiled with flags "-O3 -xCORE-AVX2" using Intel C++ Compiler 15.0.
    • Using DGEMM from Intel MKL 11.1.1.
    • Using DGEMM from Intel MKL 11.2.
    • Using DGEMM from Intel MKL 11.2 and with "-DMKL_DIRECT_CALL" enabled.

    The matrices used in this chart are all square. The version-to-version improvement of Intel MKL 11.2 over 11.1.1, as well as the additional benefit brought by MKL_DIRECT_CALL, are evident.

    How to use MKL_DIRECT_CALL and MKL_DIRECT_CALL_SEQ

    These are the macros to be defined at link time to instruct Intel MKL to pick the fast path for small matrices. The first macro, MKL_DIRECT_CALL, is used when you link to the parallel Intel MKL library. The second, MKL_DIRECT_CALL_SEQ, is used when you link to the sequential Intel MKL library. These macros do not have effects on larger matrices.

    For a program in the C language on Linux system, simply add -DMKL_DIRECT_CALL or -DMKL_DIRECT_CALL_SEQ to the link line. On Windows, the syntax is /DMKL_DIRECT_CALL or /DMKL_DIRECT_CALL_SEQ. Usually, the flag -std=c99 (/Qstd=c99 on Windows) is also needed. This has been tested on mainstream C and C++ compilers such as Intel C++ Compiler, GCC, Microsoft Visual Studio, etc.

    For a program in Fortran, first inlcude "mkl_direct_call.fi". See below for an example from the "Intel MKL User's Guide". Then, add -DMKL_DIRECT_CALL (/DMKL_DIRECT_CALL on Windows) or -DMKL_DIRECT_CALL_SEQ (/DMKL_DIRECT_CALL_SEQ on Windows) to the link line. If you are using Intel Fortran Compiler then pass -fpp (/fpp on Windows) to enable Fortran pre-processing. If you are using PGI Fortran compiler then pass -Mpreprocess instead. This feature does not work with GNU Fortran compiler.

    #     include "mkl_direct_call.fi"
          program   DGEMM_MAIN
    ....
    *      Call Intel MKL DGEMM
    ....
          call sub1()
          stop 1
          end
    
    *     A subroutine that calls DGEMM
          subroutine sub1
    *      Call Intel MKL DGEMM
    
          end

    Limitations

    There are a few limitations of using this feature.

    • The performance gain is a result of skipping error checking and function inlining. There will be no error reported if incorrect parameters are passed to the function call. For this reason, users should not use this feature during code development and debugging. Users should only enable this feature when the code is ready for deployment.
    • The "verbose mode" (another new feature introduced in Intel MKL 11.2) does not work for functions that take the fast path enabled by this feature.
    • This feature currently does not have effect on C/ZGEMM3 functions.
    • This feature does not work with CBLAS function calls.
    • The performance benefit of this feature on Intel Xeon Phi coprocessors is marginal. Work is in progress to fully extend this feature to cover Intel Xeon Phi coprocessors.
    • CNR (Conditional Numerical Reproducibility) is not supported.
    • For Fortran programs, the GNU Fortran compiler is not supported.
  • small matrix
  • performance
  • Sviluppatori
  • Professori
  • Apple OS X*
  • Linux*
  • Microsoft Windows* (XP, Vista, 7)
  • Microsoft Windows* 8
  • Unix*
  • Server
  • C/C++
  • Fortran
  • Avanzato
  • Principiante
  • Intermedio
  • Intel® Math Kernel Library
  • Ottimizzazione
  • URL
  • Argomenti sui compilatori
  • Miglioramento delle prestazioni
  • Librerie
  • Area tema: 

    IDZone

    XDK alone September

    $
    0
    0
    XDK Developer
    Intel
    ®
    XDK

    The easy and fast way to get your apps to market.

    Intel® XDK provides a simplified workflow to enable developers to easily design, debug, build, and deploy HTML5 web and hybrid apps across multiple app stores, and form factor devices.

    Experience Intel® XDK - the easy and fast way to get your apps to market.

    Get Intel XDK now.
    Download
    GO!
    Zonzo Fox
    Intel XDK is available as a free download

    for Windows* 7 & 8, Apple OS X*, and Ubuntu* Linux

    HTML5 App Development
    Create compelling, content-rich apps using common UI Frameworks, Apache* Cordova* and third-party plugins for advertising and in-app purchasing, as well as a host of backend, authentication, and social media services.
    GO!
    Download
    Integrated HTML5 Workflow
    From your idea to app store.
    Develop
    Start creating the next generation of HTML5 apps for the mobile world.
    Build cross-platform apps easily for many app stores and web platforms

    • Built on Web technologies HTML, CSS, JavaScript*, and Node-Webkit back-end
    • Hosted on Windows*, OS X* and Ubuntu* Linux*
    Jumpstart Development

    • Start with a number of samples or templates for both hybrid and web apps
    • Use the App Designer UI Builder to quickly prototype or refine the UI of your app
    • Start from scratch and edit in the open source BRACKETS* Editor
    Multiple UI Frameworks & APIs

    • jQuery* Mobile, App Framework*, Twitter Bootstrap*, and Topcoat* - all you need to create great, responsive UIs
    • Full support for Apache* Cordova* device APIs for your hybrid app, and the many 3rd-party plugins
    Web Services & Plugins for Content-rich, Interactive apps

    • Easily add web services, such as datafeeds, backend datastores, authentication from a number of providers
    • Add in ads and in-app purchasing, and other monetization services from Google*, appMobi*
    Development made easy.
    Responsive on any device.
    App Dev User
    Intuitive UI Design with App Designer
    • Drag & Drop UI Builder
    • Round-trip capable: modify in App Designer and the Editor
    Built-in JS editing of UI elements
    • Enables custom JS code editing of the UI element
    • Start with common UI Frameworks: App Framework, JQuery* Mobil, Twitter* Bootstrap, Topcoat*
    Accelerate Code Development
    App Dev User
    Brackets* Editor
    • Efficient Coding - Switch between HTML5 project files with code hints
    • Auto completion - Speeds up coding without knowing the exact syntax
    ...or, use your own favorite editor
    Expanded Device API Support
    App Dev User
    Cordova* 3.X - More device capabilities
    • Android*, iOS* Windows* 8, Windows* Phone 8
    • Supports Cordova plugins
    • Emulation support for Cordova device APIs
    Extends Hybrid Capabilities
    App Dev User
    Crosswalk* Runtime for Android
    • Web Runtime Performance - Web developers can now create applications with native-like performance with WebGL* and WebAudio*
    • Built on Open source Foundation - Enables better performance, flexibility, and ease of deployment to many app stores
    • Standards - Provides native platform and full screen capabilities using HTML5, CSS3, and JavaScript
    GO!
    Download
    Essential Debugging Tools
    Get your app to the stores faster.
    Debug
    Intel® XDK helps decrease your testing and debugging time and get your app to market faster.
    Testing

    • Preview your app while editing in a separate browser window or on your device with Live Preview
    • Use the App Preview app for iOS*, Android*, Windows* 8, and Windows* Phone 8 for full testing on your device
    Emulator

    • Simulate your app running on different phone and tablet skins before deployment
    • Quickly switch to debugger to debug your app inside the device emulator
    JS Remote Debugger and Profiler for Android

    • Efficiently debug apps remotely with JS Remote Debugger for Android
    • View memory, frames, and events profiling results to get the best performance out of your app
    More app reliability.
    Tune App Performance
    App Dev User
    Remote JS Performance Profiler for Android
    • Quickly pinpoints app performance bottlenecks
    • Round-trip capable, modify within the app
    Xlint Platform-Compatibility CSS Checker
    • Xlint* is a Brackets* HTML5 editor extension
    • Reports cross-platform CSS3 compatibility issues
    • Tests against W3C specs for animations, color level, shadings
    Work Efficiently / Stay On Schedule
    App Dev User
    App Preview on-device Testing
    • Enables on-device testing of hybrid apps, without going through app store submission process
    Live Development Side-by-side testing
    • Enables faster testing and editing with real-time side-by-side app preview
    • Allows developers to view changes rendered simultaneously while editing
    GO!
    Download
    Easier Build, Faster Deployment
    Building your application for every platform

    has never been this fast and easy.

    Deploy
    Build cross-platform apps easily for many app stores and web platforms.

    • Select your target store and build! Your app is ready for deployment
    • Hybrid or web apps for Apple* App Store, Google* Play, Windows* 8 and Windows* 8 Phone Stores. Also, Amazon*, Tizen*, Facebook*, Chrome* Stores.
    • For Android* devices, build with Crosswalk*, an open source web-runtime to greatly improve your media and games apps with high-performance WebGL* and WebAudio* support
    Create apps for every need

    and every device.

    Easier Build
    App Dev User
    Build Hybrid and Web Apps
    • Write Hybrid or Web apps once, and deploy to many app stores
    Faster Deployment
    App Dev User
    Reach More App Stores
    • Apple* App Store
    • Google* Play
    • Nook* Store
    • Amazon Store
    • Windows Store
    • Tizen Store
    • Facebook
    • Chrome

    Intel XDK Name Space API Plugin Details for Cordova Build Containers

    $
    0
    0
    The title of each API section below contains a link that will take you directly to the appropriate section of the intel.xdk API documentation.

    Note that the APIs listed below augment the standard Cordova APIs, both APIs can and should be used in your application. In some cases there is overlap between the Cordova APIs and the intel.xdk APIs; in that case, we recommend you use the Cordova API first and then use the intel.xdk API when the Cordova API either does not provide the desired functionality or provides inadequate functionality. Do not mix overlapping APIs within your application; in other words, use only the Cordova accelerometer API or the intel.xdk accelerometer API in your app, do not use both in the same app. This overlap between two similar device APIs exists for historical reasons and is not recommended for normal use.

    APIs marked as "pending" in the notes section are still under development or have not been fully tested. APIs marked as "removed" are not present in the Cordova build system but may still exist in the standard "Intel XDK" build containers and may also be supported by the Emulator tab within the Intel XDK (see this list of APIs that are not supported by the Emulator).

    To include these APIs as part of your application you must include a reference to "cordova.js" in your index.html file. In your Cordova build configuration file you also need to include a reference to each plugin required by the API(s) you are using by "value" and "name" where "value" is the title of each API section below (e.g., intel.xdk.accelerometer) and "name" is the last segment of that title (e.g., accelerometer), unless indicated otherwise. See Using the Intel XDK "Cordova for *" Build Option for detailed information.

    intel.xdk.base

    The properties in this plugin are useful for writing device-dependent code fragments. In addition to the properties provided here, there are two methods and one event included with this plugin, they are the "bare minimum" required to get your Cordova container up and running quickly. Note that the methods and events included in this plugin have equivalents in the core Cordova plugins, which are recommended for new applications. The methods and events are provided here to support existing XDK applications and to minimize application permission requirements (this plugin requires no special permission).

    API ObjectAPI TypeNotes
    intel.xdk.device.hideSplashScreenmethod
    intel.xdk.device.showSplashScreenmethod
    intel.xdk.appproperty
    intel.xdk.isamazonproperty
    intel.xdk.ischromeproperty
    intel.xdk.isfacebookproperty
    intel.xdk.isgoogleproperty
    intel.xdk.isintelproperty
    intel.xdk.ismozillaproperty
    intel.xdk.isnativeproperty
    intel.xdk.isnookproperty
    intel.xdk.isphoneproperty
    intel.xdk.istabletproperty
    intel.xdk.istestproperty
    intel.xdk.iswebproperty
    intel.xdk.iswin8property
    intel.xdk.iswp8property
    intel.xdk.isxdkproperty
    intel.xdk.jsVersionproperty
    intel.xdk.webRootproperty
    intel.xdk.device.readyevent

    intel.xdk.accelerometer

    For reading the device accelerometer.

    API ObjectAPI TypeNotes
    intel.xdk.accelerometer.clearWatchmethod
    intel.xdk.accelerometer.getCurrentAccelerationmethod
    intel.xdk.accelerometer.watchAccelerationmethod

    intel.xdk.audio

    For playing and recording audio elements.

    API ObjectAPI TypeNotes
    intel.xdk.audio.startPlayingmethodundocumented
    intel.xdk.audio.stopPlayingmethodundocumented
    intel.xdk.audio.pausePlayingmethodundocumented
    intel.xdk.audio.continuePlayingmethodundocumented
    intel.xdk.audio.stopRecordingmethodundocumented
    intel.xdk.audio.pauseRecordingmethodundocumented, compatibility placeholder
    intel.xdk.audio.startRecordingmethodundocumented
    intel.xdk.audio.addSoundmethodundocumented, compatibility placeholder
    intel.xdk.audio.continueRecordingmethodundocumented, compatibility placeholder
    intel.xdk.audio.deleteRecordingmethodundocumented
    intel.xdk.audio.clearRecordingsmethodundocumented
    intel.xdk.audio.getRecordingListmethodundocumented
    intel.xdk.audio.getRecordingURLmethodundocumented
    intel.xdk.audio.play.stopeventundocumented
    intel.xdk.audio.play.starteventundocumented
    intel.xdk.audio.play.pauseeventundocumented
    intel.xdk.audio.play.busyeventundocumented
    intel.xdk.audio.play.erroreventundocumented
    intel.xdk.audio.play.continueeventundocumented
    intel.xdk.audio.record.removedeventundocumented
    intel.xdk.audio.record.notRemovedeventundocumented
    intel.xdk.audio.record.cleareventundocumented
    intel.xdk.audio.continue.notsupportedeventundocumented, compatibility placeholder
    intel.xdk.audio.pause.notsupportedeventundocumented, compatibility placeholder
    intel.xdk.audio.record.starteventundocumented
    intel.xdk.audio.record.busyeventundocumented
    intel.xdk.audio.record.erroreventundocumented
    intel.xdk.audio.record.stopeventundocumented

    intel.xdk.cache

    For persistent caching of data between application sessions.

    API ObjectAPI TypeNotes
    intel.xdk.cache.addToMediaCachemethod
    intel.xdk.cache.addToMediaCacheExtmethod
    intel.xdk.cache.clearAllCookiesmethod
    intel.xdk.cache.clearMediaCachemethod
    intel.xdk.cache.getCookiemethod
    intel.xdk.cache.getCookieListmethod
    intel.xdk.cache.getMediaCacheListmethod
    intel.xdk.cache.getMediaCacheLocalURLmethodpending
    intel.xdk.cache.getMediaCacheRelativePathmethodpending, undocumented
    intel.xdk.cache.removeCookiemethod
    intel.xdk.cache.removeFromMediaCachemethod
    intel.xdk.cache.setCookiemethod
    intel.xdk.cache.media.addevent
    intel.xdk.cache.media.clearevent
    intel.xdk.cache.media.removeevent
    intel.xdk.cache.media.updateevent

    intel.xdk.camera

    For capturing images with the camera and accessing those images.

    API ObjectAPI TypeNotes
    intel.xdk.camera.clearPicturesmethod
    intel.xdk.camera.deletePicturemethod
    intel.xdk.camera.getPictureListmethod
    intel.xdk.camera.getPictureURLmethod
    intel.xdk.camera.importPicturemethod
    intel.xdk.camera.takeFrontPicturemethodpending, undocumented, identical to takePicture
    intel.xdk.camera.takePicturemethod
    intel.xdk.camera.picture.addevent
    intel.xdk.camera.picture.busyevent
    intel.xdk.camera.picture.cancelevent
    intel.xdk.camera.picture.clearevent
    intel.xdk.camera.picture.removeevent

    intel.xdk.contacts

    For access to the on-device contacts database.

    API ObjectAPI TypeNotes
    intel.xdk.contacts.addContactmethod
    intel.xdk.contacts.chooseContactmethod
    intel.xdk.contacts.editContactmethod
    intel.xdk.contacts.getContactDatamethod
    intel.xdk.contacts.getContactListmethod
    intel.xdk.contacts.getContactsmethod
    intel.xdk.contacts.removeContactmethod
    intel.xdk.contacts.addevent
    intel.xdk.contacts.busyevent
    intel.xdk.contacts.chooseevent
    intel.xdk.contacts.editevent
    intel.xdk.contacts.getevent
    intel.xdk.contacts.removeevent

    intel.xdk.device

    Configure the device and/or retrieve information pertinent to the device.

    API ObjectAPI TypeNotes
    intel.xdk.device.addRemoteScriptmethod
    intel.xdk.device.addVirtualPagemethod
    intel.xdk.device.blockRemotePagesmethodremoved
    intel.xdk.device.closeRemoteSitemethod
    intel.xdk.device.copyToClipboardmethod
    intel.xdk.device.getRemoteDatamethod
    intel.xdk.device.getRemoteDataExtmethod
    intel.xdk.device.getRemoteDataWithIDmethod
    intel.xdk.device.hideStatusBarmethod
    intel.xdk.device.launchExternalmethod
    intel.xdk.device.mainViewExecutemethod
    intel.xdk.device.managePowermethod
    intel.xdk.device.removeVirtualPagemethod
    intel.xdk.device.runInstallNativeAppmethodremoved
    intel.xdk.device.scanBarcodemethod
    intel.xdk.device.sendEmailmethod
    intel.xdk.device.sendSMSmethod
    intel.xdk.device.setAutoRotatemethod
    intel.xdk.device.setBasicAuthenticationmethod
    intel.xdk.device.setRotateOrientationmethod
    intel.xdk.device.showRemoteSitemethod
    intel.xdk.device.showRemoteSiteExtmethod
    intel.xdk.device.updateConnectionmethod
    intel.xdk.device.connectionproperty
    intel.xdk.device.hasCachingproperty
    intel.xdk.device.hasStreamingproperty
    intel.xdk.device.initialOrientationproperty
    intel.xdk.device.lastStationproperty
    intel.xdk.device.modelproperty
    intel.xdk.device.orientationproperty
    intel.xdk.device.osversionproperty
    intel.xdk.device.phonegapversionproperty
    intel.xdk.device.platformproperty
    intel.xdk.device.queryStringproperty
    intel.xdk.device.uuidproperty
    intel.xdk.device.barcode.scanevent
    intel.xdk.device.connection.updateevent
    intel.xdk.device.continueevent
    intel.xdk.device.hardware.backevent
    intel.xdk.device.orientation.changeevent
    intel.xdk.device.pauseevent
    intel.xdk.device.remote.blockevent
    intel.xdk.device.remote.closeevent
    intel.xdk.device.remote.dataevent
    intel.xdk.device.resumeevent
    intel.xdk.device.suspendevent

    intel.xdk.display

    For controlling aspects of the device's display.

    API ObjectAPI TypeNotes
    intel.xdk.display.lockViewportWindowmethodpending
    intel.xdk.display.startARmethodpending
    intel.xdk.display.stopARmethodpending
    intel.xdk.display.useViewportmethodpending
    intel.xdk.display.window.landheightpropertypending
    intel.xdk.display.window.landwidthpropertypending
    intel.xdk.display.window.portheightpropertypending
    intel.xdk.display.window.portwidthpropertypending

    intel.xdk.facebook

    For access to an end-user's Facebook account.

    API ObjectAPI TypeNotes
    intel.xdk.facebook.enableFrictionlessRequestsmethod
    intel.xdk.facebook.loginmethod
    intel.xdk.facebook.logoutmethod
    intel.xdk.facebook.requestWithGraphAPImethod
    intel.xdk.facebook.requestWithRestAPImethoddeprecated, performs a null action
    intel.xdk.facebook.showAppRequestDialogmethod
    intel.xdk.facebook.showNewsFeedDialogmethod
    intel.xdk.facebook.busyevent
    intel.xdk.facebook.dialog.completeevent
    intel.xdk.facebook.dialog.failevent
    intel.xdk.facebook.loginevent
    intel.xdk.facebook.logoutevent
    intel.xdk.facebook.request.responseevent
    intel.xdk.facebook.session.invalidateevent

    intel.xdk.file

    For uploading files to an appropriately configured server.

    API ObjectAPI TypeNotes
    intel.xdk.file.cancelUploadmethod
    intel.xdk.file.uploadToServermethod
    intel.xdk.file.uploadevent
    intel.xdk.file.upload.busyevent
    intel.xdk.file.upload.cancelevent

    intel.xdk.geolocation

    For access to the device location tracking hardware.

    API ObjectAPI TypeNotes
    intel.xdk.geolocation.clearWatchmethod
    intel.xdk.geolocation.getCurrentPositionmethod
    intel.xdk.geolocation.watchPositionmethod

    intel.xdk.multitouch

    To enable device multi-touch features on Android devices.

    API ObjectAPI TypeNotes
    intel.xdk.multitouch.enablemethodpending

    intel.xdk.notification

    Provides device-specific alerts.

    API ObjectAPI TypeNotes
    intel.xdk.notification.alertmethod
    intel.xdk.notification.beepmethod
    intel.xdk.notification.confirmmethod
    intel.xdk.notification.hideBusyIndicatormethod
    intel.xdk.notification.showBusyIndicatormethod
    intel.xdk.notification.vibratemethod
    intel.xdk.notification.confirmeventundocumented
    intel.xdk.notification.confirm.busyeventundocumented

    intel.xdk.player

    For playing audio and video media files and streams.

    API ObjectAPI TypeNotes
    intel.xdk.player.setAudioVolumemethodundocumented
    intel.xdk.player.clearAudioCurrentTimeWatchmethod
    intel.xdk.player.ffwdmethodremoved
    intel.xdk.player.hidemethodremoved
    intel.xdk.player.loadSoundmethod
    intel.xdk.player.pausemethodremoved
    intel.xdk.player.playmethodremoved
    intel.xdk.player.playPodcastmethodpending
    intel.xdk.player.playSoundmethod
    intel.xdk.player.rewindmethodremoved
    intel.xdk.player.setAudioCurrentTimemethod
    intel.xdk.player.setColorsmethodremoved
    intel.xdk.player.setPositionmethodremoved
    intel.xdk.player.showmethodremoved
    intel.xdk.player.startAudiomethod
    intel.xdk.player.startShoutcastmethodpending
    intel.xdk.player.startStationmethodremoved
    intel.xdk.player.stopmethodremoved
    intel.xdk.player.stopAudiomethod
    intel.xdk.player.toggleAudiomethod
    intel.xdk.player.unloadAllSoundsmethod
    intel.xdk.player.unloadSoundmethod
    intel.xdk.player.volumemethodpending
    intel.xdk.player.watchAudioCurrentTimemethod
    intel.xdk.player.audioInfo.currentTimeproperty
    intel.xdk.player.audioInfo.durationproperty
    intel.xdk.player.audio.busyevent
    intel.xdk.player.audio.currenttime.setevent
    intel.xdk.player.audio.errorevent
    intel.xdk.player.audio.startevent
    intel.xdk.player.audio.stopevent
    intel.xdk.player.audio.volume.seteventundocumented
    intel.xdk.player.sound.loadeventundocumented
    intel.xdk.player.sound.unloadeventundocumented
    intel.xdk.player.hideeventremoved
    intel.xdk.player.showeventremoved
    intel.xdk.player.podcast.busyeventpending
    intel.xdk.player.podcast.erroreventpending
    intel.xdk.player.podcast.starteventpending
    intel.xdk.player.podcast.stopeventpending
    intel.xdk.player.shoutcast.busyeventpending
    intel.xdk.player.shoutcast.erroreventpending
    intel.xdk.player.shoutcast.pauseeventpending
    intel.xdk.player.shoutcast.playeventpending
    intel.xdk.player.shoutcast.starteventpending
    intel.xdk.player.shoutcast.stopeventpending
    intel.xdk.player.sound.erroreventpending, iOS only
    intel.xdk.player.station.busyeventremoved
    intel.xdk.player.station.erroreventremoved
    intel.xdk.player.station.pauseeventremoved
    intel.xdk.player.station.playeventremoved
    intel.xdk.player.station.starteventremoved
    intel.xdk.player.station.stopeventremoved
    intel.xdk.player.track.changeeventremoved

    Using the Intel® XDK Develop Tab

    $
    0
    0

    Code Editor and UI Designer

    This tab provides a full view of the files in your project directory. You can edit project files with the built-in Brackets* code editor or with your favorite code editor, alongside the Intel XDK. The Intel XDK tools automatically detect when project files are changed (as the result of a save when using your external editor) and will prompt you if additional actions are required due to changes to project files.

    If you are unfamiliar with the Brackets HTML5 code editor read Using the Editor in the Intel® XDK Develop Tab for a tutorial introduction to the built-in editor.

    NOTE: the built-in Brackets editor includes a curated list of Brackets extensions. From the editor menu, choose “File > Extension Manager…” to see the list of editor extensions that are available. There is no mechanism available to include your own custom Brackets extensions.

    A Note about App Designer and App Starter

    If you create your app using either App Starter or App Designer (e.g., using the “(+) Start a New Project” button at the bottom of the Projects tab), you will also have access to these GUI layout editors on the Develop tab (via the “[ CODE | DESIGN ]” buttons).

    • Use App Starter to build a UI using the App Framework mobile-optimized UI library– or, use App Starter to learn how to build App Framework applications by hand (by reviewing the code that App Starter creates).
    • With App Designer you can build a UI based on a responsive grid system and one of several UI widget libraries, including the App Framework UI library.

    App Designer utilizes a media query grid system for creating responsive web UI layouts. This media query grid system enables your app to resize and adapt to portrait and landscape views on phones, tablets and even UltrabookTM devices. To get started see the App Designer Documentation and Tutorial page.

    When you open an HTML file in the Develop tab, if that project was created using either App Designer or App Starter, the “[ CODE | DESIGN ]” buttons appear above the file project tree, allowing you to switch between the Editor and the Design (GUI) views. Use the CODE and DESIGN buttons to switch between these two views of your project (while selecting the index.html file in your project).

    Don’t forget to check out the App Framework UI Components documentation page and the App Framework CSS Style Builder for more information about the App Framework UI library, which has been optimized for use with HTML5 hybrid mobile apps.

    Live Development

    The Live Development Manager panel, on the right side of the Develop tab, is designed to make the process of previewing your code in a browser or on a device more efficient. This feature is currently in a preview state, so many features are still in development and subject to change.

    There are two parts to Live Development: "Live Preview" - which displays your edits in a separate browser window, and "Preview on Devices" for previewing your app on a real device.

    • Live Preview offers the ability to see your edits simultaneously rendered in a Chrome browser window as you edit your app in the built-in Brackets editor.
    • Preview on Devices gives you a way to quickly review changes in your layout code on a connected device that is running App Preview.

    Live Preview

    Live Preview is based directly on the Brackets Live Preview feature. It works best as a means to test static HTML and CSS pages (CSS and HTML layout code). It does not work well with JavaScript libraries or frameworks that actively modify the DOM (see this Brackets blog for a quick intro). Thus, it has not been enabled for use with the Intel XDK UI design tools (App Designer and App Starter). Live Preview requires the Chrome (not Chromium) browser be installed on your development system in order to function. When activated it will automatically start a Chrome browser instance for immediate preview of your application.

    Some Live Preview limitations include:

    • The Chrome browser does not support device APIs (such as Cordova and Intel XDK).
    • Only HTML and CSS that affect layout and appearance should be tested, JavaScript that modifies the DOM will not work well.
    • Device scaling and layout (such as portrait and landscape) are not directly supported (you can use the Chrome "Emulation" tab in the "Console Drawer" to affect preview layout and the size of the viewport, if desired).

    Preview on Devices

    Preview on Devices lets you quickly modify your project and test your app on real devices, with all file types. It requires a real device running App Preview. As you make changes to the files in your project your changed files are automatically pushed to your device so you can see how your app runs on a real device. At this time, this feature only works with Android* devices connected to your development system via a USB cable (see the Debug tab for more information about connecting via USB). App Preview is a free download for Android, iOS* and Windows* 8 devices and is available from their respective app stores.

    Some Preview on Device limitations include:

    • Changed files are only transmitted to the preview device when files are saved.
    • This feature currently requires an Android 4.x device connected via USB.
    • Android App Preview Crosswalk must be installed on your Android 4.x device (see the Debug tab for more information about connecting via USB).
    • Your code runs within the Crosswalk for Android container, not the standard Intel XDK container, so the behavior and appearance may be different when compared to running your application within App Preview via the Test tab.

    Note that the limitations above, are limitations to the preview editions of these features in the current version of the Intel XDK. Future releases of the Intel XDK will address these limitations; in addition, new features may be added and existing features may be removed.

    Using the Build Tab

    $
    0
    0

    In the Intel® XDK development environment, once you have completed debugging and testing your app, you can use the Build tab to make bundles you can submit to a variety of app stores. There are three types of app builds available, two for building mobile apps and one for web apps:

    • Cordova 3.X Hybrid Mobile App Platforms creates a native app bundle suitable for submission to an app store for download and installation onto a mobile device. These apps use Apache Cordova* 3.x APIs. You can build for Google Android* (either the Crosswalk* run-time or standard run-time), Apple iOS*, and Microsoft Windows 8* platforms.
    • Legacy Hybrid Mobile App Platforms creates a native app bundle suitable for submission to an app store for download and installation onto a mobile device. These apps do not use Cordova 3.x plug-ins and APIs, but can use Cordova 2.9 APIs. Build platforms include Android (legacy container run-time), Apple iOS Ad Hoc or iOS Production, Windows 8, Windows Phone 8, Tizen*, Amazon*, or Barnes and Nobles Nook* platforms.
    • Build as a Web App creates an HTML5 bundle suitable for submitting to web app stores or for placement on a web server. Build platforms includes WebApp, Google Chrome*, Facebook*, or Mozilla Firefox*.
    NOTE: The Intel XDK build service will NOT submit your app bundle to a store, but it does provide you with a bundle suitable for store submission. To submit your app to a store, you must do that outside of the Intel XDK.

    How you specify your app settings depends upon which type of app you will build:

    NOTE: HTML5 application bundles are standard ZIP files. If you are curious as to what is added to your app when a build is performed, you can "unzip" the app bundle and inspect its contents. However, if you modify the contents you will invalidate the application bundle signature; modifying a bundle after it has been built is not advised.

    Build a Cordova 3.X Hybrid Mobile App

    After you specify the app settings using the Projects tab, you can choose from a variety of targets when building your app for a native operating system under Cordova 3.X Hybrid Mobile App Platforms, including Crosswalk* for Android, Android, iOS, and Windows 8*.

    The Cordova build targets are based on the standard Cordova CLI 3.x build system. These build targets are compatible with standard Cordova (aka Adobe PhoneGap*) build systems and support the core Cordova 3.x APIs; in addition, this build system also supports a subset of the Intel XDK APIs, via a set of custom intel.xdk Cordova plugins. These build targets do not support the appMobi* services APIs.

    All build targets create a hybrid HTML5 app bundle that can be submitted to an app store and installed on a mobile device. The Crosswalk for Android container includes its own HTML5 runtime engine, based on the Crosswalk project (see Using Crosswalk). All other applications utilize the built-in webview (aka embedded browser) that is part of the target mobile device firmware to execute (render) your hybrid HTML5 web app. For example, Android bundles use the Android browser webview built into the Android device, iOS bundles use the Apple Safari* browser webview built into the iOS device, and so on.

    These targets use a intelxdk.config.xml file included in your project to direct the build process and specify the plugins (APIs) required by your application. Use the Projects tab and Using the Intel XDK “Cordova for *” Build Option for details on how to specify app settings for Cordova 3.x build targets.

    After you specify the app settings using the Projects tab, click the button corresponding to the target you want to build. The Intel XDK uploads your project files to your account on the Intel XDK build server. Once there, the build server may request additional information to complete the build process. Always review the Build log - if needed, fix app settings in the Projects tab and rebuild your app.

    In addition to the overview referenced above, please see these two articles for information regarding the plugin names and the APIs they provide access to when you include them:

    About the Crosswalk for Android Container

    Information on how to build apps for the Crosswalk for Android container are described in Tutorial - Building and Deploying Crosswalk* for Android* Binary Apps. Like other Cordova 3.X build targets, this build target supports the core Cordova 3.x APIs and a subset of the Intel XDK APIs, but it does not support the appMobi services API.

    Unlike Cordova and legacy Intel XDK built apps, the Crosswalk container includes a custom webview for executing your hybrid HTML5 application. For this reason it is significantly larger than bundles built using the other build targets. This build option creates two processor-specific bundles (an x86 APK for use on x86 Android devices and an ARM APK for ARM* Android devices). Follow the instructions in Submitting Multiple Crosswalk APKs to the Google Play Store* to ensure that your Crosswalk application is available to the widest consumer audience. The store automatically delivers the appropriate APK to your customer's device.

    For technical and legal reasons the Crosswalk run-time engine is only available on Android 4.x devices.

    For details regarding which Intel XDK APIs are supported in the Crosswalk webview, and which plugins must be selected to ensure your application has access to the appropriate APIs, please see Intel XDK Name Space API Plugin Details for Cordova Build Containers and the API Reference section of the Apache Cordova API Documentation.

    Build a Legacy Hybrid Mobile App

    You can choose from a variety of targets when building your app for a native operating system under Legacy Hybrid Mobile App Platforms, including Google Android (legacy container run-time), Apple iOS Ad Hoc or iOS Production, Windows 8, Windows Phone 8, Tizen, Amazon, or Nook platforms.

    The legacy Intel XDK container builds are based on the original appMobi* hybrid HTML5 container and support the full Intel XDK API, the appMobi services API, and the standard Cordova 2.9.0 API.

    After you click the button corresponding to the target you will build, the Intel XDK uploads your project files to your account on the Intel XDK build server. Once there, the build server may request additional information to complete the build process. These additional screens typically require an app name, icon and splash screen images, and any certificates needed to sign the app. In some instances, you may be required to have a developer's license to complete the build process. Also, in some cases the build process may ask you to copy files and/or keys from the build server for use with app store submission. If the Build reports errors, you may need to fix app settings in the Build tab and rebuild your app.

    Details regarding how to use the legacy Intel XDK containers are provided in the links below:

    The Windows 8 build refers to applications targeting the Windows 8 "Modern UI" environment. The build named Windows 8 Phone targets Windows Phone devices.

    NOTE: The Nook* and Amazon* build targets are minor variations of the legacy Android build target; use the Android build tutorial as a guide.

    Build a Web App

    There are fewer web app targets because there is less overhead required to put an HTML5 app on the web. These are mostly convenience builds that add manifest files and, in some cases, support libraries to your app bundle. You can "unzip" these bundles to see what has been added and to better understand what these builds do.

    Click the button for your target of choice. This connects you to the build server and uploads your project to your account in the Intel XDK build server. Once the build server has your code, it will request any additional information needed to complete the process and add the internal infrastructure necessary to host your code as a web app on the selected platform.

    See this tutorial for information about building a Google Chrome web app in the Intel XDK.

    See this page for information about building a Firefox* OS web app in the Intel XDK.

    Resources


    Legal Information    *Other names and brands may be claimed as the property of others.
    Visit Support Forums   -   Submit feedback on this page

    Intel® XDK Install Instructions

    $
    0
    0
    Intel
    ®
    XDK Install Instructions
    Below you will find installation instructions for Intel® XDK for the following platforms – Microsoft Windows*, Apple OS* and Linux*/Other OS.
    Microsoft Windows*:
    1
    Open the EXE File
    After download, locate and open the Intel XDK install file.
    2
    First Time User?
    You will see a launch screen followed by a series of install screens. Click next until install is complete
    3
    Run Intel XDK
    After install is complete, locate and launch Intel XDK from your start menu.
    Apple OS X*:
    1
    Open the DMG File
    After download, locate and open the Intel XDK DMG file and run the XDK.PKG install file.
    2
    First Time User?
    You will see a launch screen followed by a series of install screens. Click next until install is complete
    3
    Run Intel XDK
    After install is complete, locate and launch Intel XDK from your applications folder.
    Linux*/Other OS:
    1
    Open the TGZ File
    After download, locate and uncompress the install file. From the uncompressed folder, run install_gui.sh.
    2
    First Time User?
    You will see a launch screen followed by a series of install screens. Click next until install is complete
    3
    Run Intel XDK
    After install is complete, locate and launch Intel XDK from xdk.sh.

    Adding Plugins to Your Intel® XDK Cordova App

    $
    0
    0

    Adding Plugins to Your Intel® XDK Cordova App

    Apache* Cordova* plugins are a very important tool for enhancing the features and functionality of your Intel® XDK HTML5 mobile application. They provide a way to extend your app's JavaScript API, resulting in a much tighter integration of your app with a mobile device's software and hardware. There are hundreds of Cordova (and Adobe* PhoneGap*) plugins available for use with your app. They can be found in the Apache Cordova Plugins Registry and similar plugin registries, as well as many open source github repos. If you work for a large company your IT department might even maintain a set of Cordova plugins they've developed for mobile apps used by your company's employees, for example.

    The Intel XDK references and uses Cordova plugins in a variety of locations throughout the development cycle of your HTML5 mobile application. The most apparent usage is in the Projects and Build tabs. In the Projects tab (described below) you select which Cordova plugins will be included as a part of your app. The Build tab will then automatically add those plugins to your app package when it builds your app, in order to include the "JavaScript extension API" provided by that plugin and used by your application. Less obvious is their use in the Brackets editor (the text editor in the Develop tab) and the Emulate tab.

    In the Develop tab, the plugins are used to implement code hinting (a common editor feature that is frequently referred to as "intelli-sense" or "auto-hinting"). The editor automatically provides API method and property hints for the core Cordova and Intel XDK APIs. At this time code hinting is provided for ALL core plugins, regardless of which you've actually selected to be part of your application on the Projects tab.

    The Emulate tab makes note of which core Cordova plugins you've selected on the Projects tab and will only present to your application those APIs that correspond to the selected core Cordova plugins, when your app runs inside the emulator. The complete set of APIs provided by the Intel XDK plugins are always presented to your app by the emulator, regardless of which have been selected on the Projects tab.

    NOTE: at this time the Test, Debug, Profile and Services tabs are not affected by the plugins you choose on the Projects tab; App Preview and App Preview Crosswalk are also not affected by the plugins settings. These features support only the core Cordova and Intel XDK plugins that are included with the Intel XDK.

    Only the Build tab makes use of any third-party plugins that are specified for inclusion in your app on the Project tab. Future editions of the Intel XDK will expand the use of third-party plugins throughout the development cycle. However, at this time the only way you can test and debug any code that accesses third-party plugins is to build an application and run it on a real device.

    What is a Cordova Plugin?

    Paraphrasing the Cordova Plugin Development Guide:

    A plugin is a package of code that allows your Cordova HTML5 app to communicate with the native platform on which it runs. Plugins provide access to platform functionality that is ordinarily unavailable to browser-based apps. The core Cordova (and Intel XDK) APIs are implemented as plugins. Many other plugins are available that enable features such as barcode scanners, NFC communication and access to local phone and tablet software databases (such as phone contacts and calendar entries).

    Plugins consist of a JavaScript API and native code modules (for each platform supported by the plugin) that support the plugin's JavaScript API. In essence, when your app calls the plugin's JavaScript API, it is redirected to the underlying plugin native code that implements that API on the device. For example, the JavaScript API is redirected to Java code on an Android device or to Objective C code on an iOS device. Plugins can be complex or simple: providing APIs as complex as a persistent database engine or as simple as a method to turn on the camera's flash LED.

    Do I Need to Learn How to Write Native Code in Java and Objective C and C# and ???

    Absolutely not. Most plugins can be pulled directly from a plugin registry or github repo and used as-is, without learning how the plugin operates internally. You do not need to "compile" anything to use a properly structured plugin, most are ready to use without any configuration or internal programming required.

    You will need to learn how to use the plugin's JavaScript API in order to use it within your app; but that is to be expected. You can think of a Cordova plugin as a JavaScript library that extends the device-specific features your app can access, features that you typically are not able to access from a standard browser or webview (the embedded browser that interprets your HTML5 hybrid app). Plugins provide the extra features that distinguish a mobile app from a browser-based web app.

    Some important points to keep in mind regarding Cordova plugins and the Intel XDK:
    Since most plugins are third-party libraries, the Intel XDK may not have explicit knowledge of a specific plugin's internal functionality or code. The debug tools included with the Intel XDK only provide direct support for the "core" Cordova and Intel XDK plugins.
    Not all plugins are created equal, many plugins are available for only the Android and iOS platforms. The "core" Cordova plugins and Intel XDK API plugins support a wide range of Cordova platforms. Be sure to confirm that the plugins you plan to use support the platforms on which you plan to deploy your app, or use platform and feature detection techniques to implement an alternate solution for unsupported platforms.
    Not all plugins support all platforms with identical API behavior. In other words, some aspects of a plugin API may vary as a function of the platform (this is usually due to platform details, not because the plugin is incomplete or deficient). Variations include properties that have no meaning on some platforms or methods that do not exist on other platforms. See the plugin's documentation for these details (some plugins include a "quirks" documentation section), and use platform and feature detection techniques to properly handle these API "quirks."
    The Intel XDK does not include a mechanism to judge the quality of a plugin. There are many resources on the web, including the cordova-plugins and phonegap-plugins tags on StackOverflow that can be used to determine which plugins are the most reliable and how to work around bugs associated with specific plugins. In addition, you can get support directly from the author of many github hosted plugins if you have issues with those plugins.
    Some third-party plugins are written for older versions of Cordova and may not work with Cordova 3.x. If you are unable to find a version of a third-party plugin that works with Cordova 3.x, it may be possible to convert a pre-3.x plugin to work with Cordova 3.x. The Intel XDK requires plugins that have been written for Cordova 3.x.
    The "core" Cordova APIs and the Intel XDK APIs are all written as Cordova 3.x plugins. The "core" Cordova 3.x plugins are maintained by the Cordova CLI development community. The Intel XDK plugins are maintained by the Intel XDK development team.
    Third-party Cordova plugins cannot be used with Intel XDK "legacy" builds (see the Build tab), they can only be used with Cordova and Crosswalk for Android builds. However, "legacy" builds do include a collection of "core" Cordova plugins when you build with the "Gold" option; these "legacy" plugins are based on the Cordova 2.9.0 release and are enabled in your app by including <script src="cordova.js"></script> after the "intelxdk.js" script include.
    The AppMobi services (such as PushMobi) that are included in the "legacy" build system are not (at the time this document was written) available as Cordova plugins. If you are unable to identify an equivalent alternative and require the use of an AppMobi service your only choice is to continue to use the "legacy" build system or request that AppMobi provide you with a Cordova 3.x compatible plugin for the AppMobi service your app requires.
    If you are developing your own Cordova plugin you may need to install and use the Cordova CLI system on your development system. You can share your plugin with others without requiring that they also install the Cordova CLI system, only you (the plugin developer) will need to install Cordova CLI (and only for plugin development, the Intel XDK does not require that the Cordova CLI be installed on your development system as a condition of inclusion in your app).
    The Intel XDK does not provide a mechanism to debug the native code in a Cordova plugin, that must be done using native code development tools that are specific to the native platform. The Emulate tab does not use Cordova native code for simulation of plugin APIs, it relies on code written for the node-webkit environment on which it runs to provide a simulation of the native code component. Thus, for those plugins that the Emulate tab does support, only the JavaScript component of each plugin is used within the Emulate tab.
    The Intel App Preview applications that you downloaded from the respective app stores for quick debug of your HTML5 mobile apps do not include support for third-party Cordova plugins. To debug an app that relies on a non-core Cordova plugin you must either use feature detection to skip over or "fake out" plugin-specific code when it is not present (as will be the case when your app runs inside of App Preview, the Emulate tab or when using the Debug and Test tabs). You can build your app (with the Build tab) so that it includes the third-party plugins and then run and debug your built app on a real device.
    At the time this document was written, the Intel App Preview applications for Android, iOS and Windows 8 were still based on the "legacy" build container and, therefore, do not precisely represent the behavior of your application inside a Cordova build container. You can still use the "legacy" App Preview to debug your Cordova app, but keep in mind that there will be some minor behavior and feature differences. Ultimately, the App Preview apps will be updated so they are built from the Cordova container and more accurately represent a Cordova built app.
    At the time this document was written, the Intel XDK Cordova build system was based on Cordova CLI version 3.3.

    Including a Cordova Plugin in Your Intel XDK App

    Including any of the "core" Cordova plugins and the Intel XDK plugins in your app is very easy. The Projects tab for your app contains a list of "included" plugins that can be added to or removed from your app by simply selecting or clearing the respective check box next to the plugin name. See the following screenshot for an example application.

    Details about which APIs are included with each core Cordova plugin can be found in the API Reference section of the Apache Cordova Documentation pages. See the Intel XDK API Reference Documentation for API and platform details regarding the Intel XDK API plugins.

    In the image above there are four blue buttons at the bottom of the plugin selection panel: "Select All,""Select Minimum,""Select None" and "Reset Plugin Defaults":

    • Select All: enables ALL core Cordova and ALL Intel XDK plugins to be included in your app. This is convenient but not advised for the production version of your app. This is also the default state of the plugins when you either create a new project or import an existing project built using version 0876 or earlier of the Intel XDK. Including ALL plugins is roughly equivalent to the state of the plugins in an app built using the "legacy" build system. Selecting ALL plugins also means you are subjecting your app to a large number of permissions that must be accepted by the end user during the installation of your app (on Android and Windows 8 platforms; iOS requests permission from the end user when the app utilizes an API that requires permission from the end user). Include all plugins also means your app will be much larger than necessary.

    • Select Minimum: enables a very small set of the core Cordova and Intel XDK plugins. This is a recommended minimum and is not a required minimum set of plugins. If you are using the Intel XDK device ready event you will need to include at least the Intel XDK "Base" plugin. If you are using the Cordova device ready event you do not need to include any plugins. Obviously, if you are using either Cordova or Intel XDK APIs (that is, APIs beyond the standard HTML5 APIs) you will have to include the plugin(s) that corresponds to the API that your app requires. See the references above for information about which plugins provide which APIs.

    • Select None: clears all "core" Cordova and Intel XDK plugins from your project. It has no effect on third-party plugins imported using the "Third-Party Plugins" panel.

    • Reset Plugin Defaults: resets the version level for each of the core Cordova plugins to match the versions that are supplied with the Intel XDK. This button will appear to have no effect if you have never changed the version number of any of the core Cordova plugins. More about plugin versions is provided below. Note that the Intel XDK plugins do not have a selectable version number, so this button has no effect on those plugins.

    About the Core Plugins

    The core Cordova plugins and Intel XDK plugins are included with the Intel XDK; because these plugins are included as part of the Intel XDK, they have a "default version" associated with them. These are the versions that the plugin specifications are reset to when you push the "Reset Plugins Default" button (described above).

    You can change a plugin's version number by selecting the edit button (hover over a plugin as shown in the image below):

    and then entering the desired version number of the plugin (as shown below):

    See the Apache Cordova Documentation pages for details regarding the core Cordova plugins. The git repo where each core Cordova plugin is maintained includes details about plugin versions, etc. You can quickly determine which versions are available for a particular plugin by inspecting it in the Apache Cordova Plugins Registry. At this time, only the Build tab uses the plugin version number, other Intel XDK components use a fixed set of core Cordova plugins.

    In the September, 2014 release of the Intel XDK we added a list of featured plugins as part of the "Core" or "Included" plugins. These plugins are, technically, third-party plugins that may include tighter integration with the Intel XDK than other third-party plugins. For example, in some cases there is direct support for these featured plugin APIs in the Emulate, Test and Debug tabs. Also, some featured plugins may include access to the plugin source via a github repo, and some may incorporate proprietary code. One example of a featured plugin is the APP Security API, which enables non-security experts to take advantage of the security properties and capabilities available on your target mobile platforms.

    Including Third-Party Plugins

    There are two ways third-party plugins can be included as part of your application: via a public repo or a local directory. You select the specific method by selecting "Import Local Plugin" or "Get Plugin from the Web" in the "Third-Party Plugins" section of the "Plugins and Permissions" panel on the Project tab.

    Two public repos are supported: a git repo (such as github) or the Apache Cordova Plugins Registry. When using the Cordova registry you only need the plugin ID, which can be found in the Cordova registry entry (see the image below for an example of referencing the Cordova registry with just a plugin ID). You can also optionally provide a plugin version number (more info below) as part of the Plugin ID field in the "Get Plugin from the Web" dialog box.

    If your third-party plugin is being retrieved from the Cordova registry the Name and Plugin ID are sufficient. In that case, check the "Plugin is located in the Apache Cordova Plugins Registry" box and select the "Import" button.

    Otherwise, if your third-party plugin is located in a git repo you must also include the address of that git repo. The git repo must be publicly accessible on the Internet because the "git pull" used to retrieve the plugin is performed by the cloud-based build server, not the Intel XDK; thus, it must reside in a publicly accessible git repo.

    If you are familiar with the Cordova CLI plugin add command you can use that syntax to include a specific plugin version based on either the version numbers stored in the Cordova registry or a git reference ID. Details can be found in the Advanced Plugin Options section of the Cordova CLI doc pages (about three-quarters down the page). If you do not specify a plugin version or reference ID your app will be built using the most recent version available in the Cordova registry or the default branch when retrieved from a public git repo.

    Importing a third-party plugin that resides in a local directory requires that the plugin be located within your project's "source directory." Normally this directory is named "www" and is located in your application's project directory (see the "Project Info" section of the Project tab for the name and location of your project's "source directory"). A local plugin will be included with the source bundle that is uploaded to the cloud-based build server; the entire contents of your project's "source directory" are included as part of that uploaded bundle.

    References to your third-party plugins, whether imported from a local directory or a public repo, are listed in the "Third-Party Plugins" section of the Projects tab (see the image below for an example). The Name field you specified above is arbitrary and is used strictly as an identifier here and in the build message log. The Plugin ID must match that specified inside the plugin.xml file (see the registry or the plugin's git repo). At this time there is no way to edit or inspect the data you provided during the plugin import process; if you need to change the Name or Plugin ID or other fields you must delete the plugin reference (click the (X) icon) and re-import the plugin with the revised Name, Plugin ID and other fields.

    The following screenshot is typical of what you will find when you inspect a plugin that is located in the Apache Cordova Plugins Registry. Note the plugin ID field, supported platforms, plugin version and supported Cordova CLI version number (aka "Engine Number"). At the time this document was written the Intel XDK build server was based on Cordova CLI version 3.3.

    Building Your Cordova App

    To build an app package, based on the Cordova container and your selected Cordova plugins, go to the Build tab and select the platform for which you want to generate an installable package under the "Cordova 3.x Hybrid Mobile App Platforms" heading.

    The Crosswalk for Android and Android platforms both generate APKs for Android devices. See Using the Intel XDK “Crosswalk for Android” Build Option and the Crosswalk Overview for more details.

    When you initiate a build you'll be asked if you want to "Upload to the build server?" Normally you should choose to "Upload Code" when this question is asked. The usual exception is when you have previously uploaded your code and successfully built for one platform and are now building for a second platform without any changes to your application between builds. In that case there is no need to upload your code to the build server a second time.

    A successful upload of your application source bundle will result in a screen similar to the following. To initiate a build click the "Build App Now" button. Unlike the "legacy" build system, there are no options associated with this step; your options are stored in an intelxdk.config.platform.xml file in your project file. See Adding Build Options to Your Intel® XDK Cordova App Using intelxdk.config.additions.xml for information on how to add build options that are not accessible via the Project tab's user interface.

    iOS builds include one option for supplying your Apple developer certificate. This certificate is stored in the build system under your Intel XDK userid; it is only necessary to provide it once for all applications you build under your login.

    When the build system completes successfully you will see a screen similar to the following. If the build system encounters issues the build log will include an error message indicating the nature of the problem that is preventing a successful build. If you consistently get build errors visit the Intel XDK forum for help (a link to the forum can be found under the (?) pulldown of the Intel XDK).

    A Simple Example Using Cordova Plugins

    The device screenshots below show a simple HTML5 hybrid app running on a real Android device. This application was built using the plugins selected in the screenshots shown in the preceding sections of this document. For example, the core Cordova "Device,""Media,""Accelerometer" and "Compass" plugins were selected from the "Core Cordova Plugins" column of the "Included Plugins" section on the Projects tab and the Intel XDK "Base" plugins was selected from the "Intel XDK Cordova Plugins" column of that same section. Also, the "Cordova StatusBar" third-party plugin was included using the "Get Plugin from the Web" feature.

    The app generates a list of available plugins dynamically, at runtime, by inspecting a special Cordova 3.x JavaScript property. The results are then printed into a <textarea> element at the bottom of the app's index.html page.

    Note that the core Cordova "Device" plugin version number has been changed from the default value of 0.2.5 to 0.2.10. Also note that the Cordova version number reported is 3.3.0, which matches the Cordova CLI used by the Intel XDK Cordova build system. Unlike the Intel XDK "legacy" build system, where all Intel XDK APIs are always available, in the Cordova build system only those APIs associated with Intel XDK plugins that have been selected are present, in this case, only the methods and properties belonging to the Intel XDK "Base" plugin.

    The only difference between the two device screenshots above is the visibility of the status bar at the top of the screen. Touching the "Toggle Status Bar" button calls the StatusBar plugin's StatusBar.hide() or StatusBar.show() method, depending on the visible state of the status bar, which is determined by checking the plugin's StatusBar.isVisible property. Had the plugin not been included these methods and this property would not be available to the app and references to them would result in JavaScript undefined errors.

    Real Devices vs Simulated Devices

    The following screenshot shows the same app running in the Emulate tab of the Intel XDK. There are several differences that are worthy of note and help to illustrate some key differences between running your plugin-enabled app in the emulator (or in App Preview or when using the Debug tab) compared to running your app on a real device.

    Remember that the screenshots shown above were taken on a real device that was running the app built using the Android Cordova build tile on the Intel XDK Build tab.

    What's different?

    • The Cordova versions do not match: the Emulate tab is using Cordova 3.4, whereas the built app running on the real device is using Cordova 3.3 (in practice, this is a minor difference).
    • The core Cordova "Device" plugin is using the default plugin version (0.2.5), whereas the built app running on the real device is using the later version that was specified manually on the Projects tab (0.2.10).
    • The third-party "StatusBar" plugin does not show up in the list of included plugins when the app runs on the Emulate tab. As a result, touching the "Toggle Status Bar" button results in no change to the device status bar when it runs inside the Emulate tab, because the StatusBar API is not present in that runtime environment.

    Running this app inside of App Preview (either indirectly via the Test tab or directly from the App Preview menu) or on the Debug tab (which runs the app in a special preview build of Crosswalk for Android) will show yet another set of results. If you run this app in those environments you will see a very long list of "core" plugins listed, as if you had selected all the plugins on the "Included Plugins" list of the Projects tab. This is normal and is due to the way these preview applications work. You will also not see any third-party plugins listed. Likewise, those third-party plugin APIs will not be accessible from within these app test environments.

    A version of the above app can be retrieved from this Github repo: https://github.com/xmnboy/test-third-party-plugin.

    Intel XDK Documentation Quick Links

    $
    0
    0

    The following links are provided here in case you need quick access to detailed device API documentation. These are useful (but optional) APIs that you can use to build hybrid mobile HTML5 apps with the Intel XDK.

    For support, please visit the Intel XDK forum.

    To manage your online account, and project files that have been pushed to our build and test server, visit the Intel XDK App Center.

    Additional Resources

    Useful Emulator Debug Hints

    The Emulator tab in the Intel XDK simulates a subset of the device APIs that are available to your application. The only way to debug these non-simulated APIs is by using on-device debugging via App Preview or a built application.

    Note that the Emulator is implemented as a Chrome browser embedded inside the Intel XDK. It simulates device viewport sizes, touch events, user agent strings and various device APIs (other than those shown below) for a convenient debugging experience using standard Chrome Dev Tools. It does not emulate an actual device or the underlying operating system. The memory, CPU and HTML5 rendering capabilities of your actual device can be quite different. It is best to think of the devices presented inside the Intel XDK Emulator tab as a collection of "ideal" devices with nearly unlimited memory, CPU and HTML5 features.

    A list of the unimplemented APIs in the Emulator is provided below:

    • device.addRemoteScript: undefined (does not throw an exception)
    • device.blockRemotePages (writes an invisible message and then does nothing)
    • facebook object: unimplemented
    • file object: unimplemented
    • oauth object: unimplemented
    • playingtrack object: unimplemented
    • the player object does not implement the following methods:
      • show
      • hide
      • playPodcast
      • setAudioCurrentTime
      • getAudioCurrentTime
      • clearAudioCurrentTime
      • startStation
      • watchAudioCurrentTime
      • clearAudioCurrentTimeWatch
      • play
      • pause
      • stop
      • volume
      • rewind
      • ffwd
      • setColors
      • setPosition
      • startShoutcast

    Intel® XDK staged

    $
    0
    0
    XDK Developer
    Intel
    ®
    XDK

    The easy and fast way to get your apps to market.

    Intel® XDK provides a simplified workflow to enable developers to easily design, debug, build, and deploy HTML5 web and hybrid apps across multiple app stores, and form factor devices.

    Experience Intel® XDK - the easy and fast way to get your apps to market.

    Get Intel XDK now.
    Download
    GO!
    Zonzo Fox
    Intel XDK is available as a free download

    for Windows* 7 & 8, Apple OS X*, and Ubuntu* Linux

    HTML5 App Development
    Create compelling, content-rich apps using common UI Frameworks, Apache* Cordova* and third-party plugins for advertising and in-app purchasing, as well as a host of backend, authentication, and social media services.
    GO!
    Download
    Integrated HTML5 Workflow
    From your idea to app store.
    Develop
    Start creating the next generation of HTML5 apps for the mobile world.
    Build cross-platform apps easily for many app stores and web platforms

    • Built on Web technologies HTML, CSS, JavaScript*, and Node-Webkit back-end
    • Hosted on Windows*, OS X* and Ubuntu* Linux*
    Jumpstart Development

    • Start with a number of samples or templates for both hybrid and web apps
    • Use the App Designer UI Builder to quickly prototype or refine the UI of your app
    • Start from scratch and edit in the open source BRACKETS* Editor
    Multiple UI Frameworks & APIs

    • jQuery* Mobile, App Framework*, Twitter Bootstrap*, and Topcoat* - all you need to create great, responsive UIs
    • Full support for Apache* Cordova* device APIs for your hybrid app, and the many 3rd-party plugins
    Web Services & Plugins for Content-rich, Interactive apps

    • Easily add web services, such as datafeeds, backend datastores, authentication from a number of providers
    • Add in ads and in-app purchasing, and other monetization services from Google*, appMobi*
    • Deliver immersive surround sound mobile app experiences with Dolby* Audio API
    • Safeguard data and storage for Hybrid Apps with App Security APIs
    Development made easy.
    Responsive on any device.
    App Dev User
    Intuitive UI Design with App Designer
    • Drag & Drop UI Builder
    • Round-trip capable: modify in App Designer and the Editor
    Built-in JS editing of UI elements
    • Enables custom JS code editing of the UI element
    • Start with common UI Frameworks: App Framework, JQuery* Mobil, Twitter* Bootstrap, Topcoat*
    Accelerate Code Development
    App Dev User
    Brackets* Editor
    • Efficient Coding - Switch between HTML5 project files with code hints
    • Auto completion - Speeds up coding without knowing the exact syntax
    ...or, use your own favorite editor
    Expanded Device API Support
    App Dev User
    Cordova* 3.X - More device capabilities
    • Android*, iOS* Windows* 8, Windows* Phone 8
    • Supports Cordova plugins
    • Emulation support for Cordova device APIs
    Extends Hybrid Capabilities
    App Dev User
    Crosswalk* Runtime for Android
    • Web Runtime Performance - Web developers can now create applications with native-like performance with WebGL* and WebAudio*
    • Built on Open source Foundation - Enables better performance, flexibility, and ease of deployment to many app stores
    • Standards - Provides native platform and full screen capabilities using HTML5, CSS3, and JavaScript
    GO!
    Download
    Essential Debugging Tools
    Get your app to the stores faster.
    Debug
    Intel® XDK helps decrease your testing and debugging time and get your app to market faster.
    Testing

    • Preview your app while editing in a separate browser window or on your device with Live Preview
    • Use the App Preview app for iOS*, Android*, Windows* 8, and Windows* Phone 8 for full testing on your device
    Emulator

    • Simulate your app running on different phone and tablet skins before deployment
    • Quickly switch to debugger to debug your app inside the device emulator
    JS Remote Debugger and Profiler for Android

    • Efficiently debug apps remotely with JS Remote Debugger for Android
    • View memory, frames, and events profiling results to get the best performance out of your app
    More app reliability.
    Tune App Performance
    App Dev User
    Remote JS Performance Profiler for Android
    • Quickly pinpoints app performance bottlenecks
    • Round-trip capable, modify within the app
    Xlint Platform-Compatibility CSS Checker
    • Xlint* is a Brackets* HTML5 editor extension
    • Reports cross-platform CSS3 compatibility issues
    • Tests against W3C specs for animations, color level, shadings
    Work Efficiently / Stay On Schedule
    App Dev User
    App Preview on-device Testing
    • Enables on-device testing of hybrid apps, without going through app store submission process
    Live Development Side-by-side testing
    • Run your local project files on your USB-connected testing device with the push of a button in the Intel® XDK
    • Automatically push your files as you save your edits for quick iteration cycles
    • Use live layout viewing to instantly see styling and layout changes you make to your CSS and HTML
    On-device simultaneous testing while creating and editing the app over Wi-Fi or USB, on Android* and iOS* devices
    GO!
    Download
    Easier Build, Faster Deployment
    Building your application for every platform

    has never been this fast and easy.

    Deploy
    Build cross-platform apps easily for many app stores and web platforms.

    • Select your target store and build! Your app is ready for deployment
    • Hybrid or web apps for Apple* App Store, Google* Play, Windows* 8 and Windows* 8 Phone Stores. Also, Amazon*, Tizen*, Facebook*, Chrome* Stores.
    • For Android* devices, build with Crosswalk*, an open source web-runtime to greatly improve your media and games apps with high-performance WebGL* and WebAudio* support
    Create apps for every need

    and every device.

    Easier Build
    App Dev User
    Build Hybrid and Web Apps
    • Write Hybrid or Web apps once, and deploy to many app stores
    Faster Deployment
    App Dev User
    Reach More App Stores
    • Apple* App Store
    • Google* Play
    • Nook* Store
    • Amazon Store
    • Windows Store
    • Tizen Store
    • Facebook
    • Chrome

    How Intel® AVX2 Improves Performance on Server Applications

    $
    0
    0

    The latest Intel® Xeon® processor E5 v3 family includes a feature called Intel® Advanced Vector Extensions 2 (Intel® AVX2), which can potentially improve application performance related to high performance computing, databases, and video processing. Here we will explain the context, and provide an example of how using Intel® AVX2 improved performance for a commonly known benchmark.

    For existing vectorized code that uses floating point operations, you can gain a potential performance boost when running on newer platforms such as the Intel® Xeon® processor E5 v3 family by doing one of the following:

    1. Recompile your code, using the Intel® compiler with the proper AVX2 switch to convert existing SSE code. See the Intel® Compiler Options for Intel® SSE and Intel® AVX generation (SSE2, SSE3, SSSE3, ATOM_SSSE3, SSE4.1, SSE4.2, ATOM_SSE4.2, AVX, AVX2) and processor-specific optimizations for more details. 
    2. Modify your code's function calls to leverage the Intel® Math Kernel Libraries (Intel® MKL) which are already optimized to use AVX2 where supported
    3. Use the AVX2 intrinsic instructions. For high level language (such as C or C++) developers, you can use Intel® Intrinsic instructions to make the call and recompile code. See the Intel® Intrinsic Guide and Intel® 64 and IA-32 Architectures Optimization Reference Manual for more details
    4. Code in assembly instructions directly. For low level language (such as assembly) developers, you can use those equivalent AVX2 instructions from their existing SSE code. See the Intel® 64 and IA-32 Architectures Optimization Reference Manual for more details

    In this article, I will share a simple experiment using the Intel® Optimized LINPACK benchmark to demonstrate the performance gain of three different sized workloads (30K, 40K, and 75K) from Intel AVX2 running on Windows* and Linux* operating systems. I will also share the list of AVX2 instructions that were executed and the equivalent SSE instructions for developers who are interested in direct coding.

    I used the following platform for the experiment:

    CPU & Chipset

    Model/Speed/Cache:  E5-2699 v3 QGN1, 2.3GHz, 45MB Cache, 145W TDP, C-1 Step

    • # of cores per chip: 18
    • # of sockets: 2
    • Chipset: Intel C610 "Wellsburg" series chipset, QS (B-1 step)
    • System bus: 9.6GT/s QPI

    Platform

    Brand/model: Intel EPSD Wildcat Pass

    • Chassis: Intel 2U Rackable
    • Baseboard: codenamed Wildcat Pass, 3 SPC DDR4
    • Board revision: Qual / PBA H30334-200
    • BIOS: SE5C610.86B.01.01.556.061320140714 BMC 0.20.6013 ME 03.00.05.402 SDR 0.10
    • Dimm slots: 24
    • Power supply: 1x 1100W Removable S-1100ADU00-201 (Rev S3)
    • CD ROM: TEAC Slim
    • Network (NIC): Onboard 10GbE

    Memory

    Memory Size: 128GB (8x16GB) DDR4 2133P

    Brand/model: Samsung M393A2G40DB0-CPB

    DIMM info: 16GB 2Rx4 PC4-2133P-RA0-10-DC0

    Mass storage

    Brand & model: Intel SSD S3500 Series (SSDSC2BB240G401)

    Number/size/RPM/Cache:  1ea - 240GB

    Plus Intel SSD P3700 Series (SSDPEDMD400G4)

    Operating system

    Microsoft* Windows Server 2012 R2 / SLES 11 SP3 Linux*

    Procedure for running LINPACK: 

    1. Download and install the following:
      1. Intel® Math Kernel Library – LINPACK Download
      2. Intel® Math Kernel Library (Intel® MKL)
    2. Create input files for 30K, 75K, 100K from the “...\linpack” directory
    3. For optimal performance, make the following Operating System and BIOS setting changes before running LINPACK:
      1. Turn off hyper-threading in the bios
      2. For Windows, set “MKL_CBWR=AVX2” on the command line and update the runme_xeon64.bat file to use the input files you previously created.  For Linux, export the “MKL_CBWR=AVX2” setting on the command line and update the runme_xeon64 shell script file to use the input files you created.
      3. The results will be in Glops similar to Table 2
    4. For Intel AVX runs, you will need to set the “MKL_CBWR=AVX” and repeat above steps.
    5. For Intel SSE runs, you will need to set the “MKL_CBWR=SSE4_2” and repeat above steps.

    What are the equivalent instructions for Intel AVX2, AVX, and SSE that were executed? 

    Table 1 has a list of equivalent instructions for Intel AVX2, AVX and SSE (SSE/SSE2/SSE3/SSE4).  If you are thinking of moving your existing code to Intel AVX2.   

    Intel AVX2 Instructions from the LINPACK Runs

    Equivalent Intel AVX Instructions

     

    Equivalent Intel SSE Instructions

    (SSE/SSE2/SSE3/SSE4)

    Definitions

    VADDPD

    VADDPD

    ADDPD

    Add Packed Double-Precision Floating-Point Values

    VADDSD

    VADDSD

    N/A

    Set the upper half of all YMM registers to zero. Used when switching between 128-bit use and 256-bit use.

    VBROADCASTSD

    VBROADCASTSD

    N/A

    Copy a 32-bit, 64-bit or 128-bit memory operand to all elements of a XMM or YMM vector register.

    VCMPPD

    VCMPPD

    N/A

    Compare packed double-precision floating-point values

    VCOMISD

    VCOMISD

    N/A

    Perform ordered comparison of scalar double-precision floating-point values and set flags in EFLAGS register

    VDIVSD

    VDIVSD

    DIVSD

    Divide low double-precision floating point value in xmm2 by low double-precision floating-point value in xmm3/m64

    VEXTRACTF128

    VEXTRACTF128

    N/A

    Extract 128 bits of float data from ymm2 and store results in xmm1/mem.

    VEXTRACTI128

    N/A

    N/A

    Extract 128 bits of integer data from ymm2 and store results in xmm1/mem.

    VFMADD213PD

    N/A

    N/A

    Multiply packed double-precision floating-point values from xmm0 and xmm1, add to xmm2/mem

    and put result in xmm0.

    VFMADD213SD

    N/A

    N/A

    Multiply scalar double-precision floating-point value from xmm0 and xmm1, add to xmm2/mem

    and put result in xmm0.

    VFMADD231PD

    N/A

    N/A

    Multiply packed double-precision floating-point values from xmm1 and xmm2/mem, add to xmm0 and put result in xmm0.

    VFMADD231SD

    N/A

    N/A

    Multiply scalar double-precision floating-point value in xmm1 and xmm2/mem, add to xmm0 and put result in xmm0.

    VFNMADD213PD

    N/A

    N/A

    Multiply packed double-precision floating-point values from xmm1 and xmm2/mem. -negate the multiplication result and add to xmm0. Put the result in xmm0.

    VFNMADD213SD

    N/A

    N/A

    N/A

    VFNMADD231PD

    N/A

    N/A

    Multiply packed double-precision floating-point

    values from ymm1 and ymm2/mem,  negate the multiplication result and add to ymm0. Put the result in ymm0.

    VINSERTF128

    VINSERTF128

    N/A

    Replaces either the lower half or the upper half of a 256-bit YMM register with the value of a 128-bit source operand. The other half of the destination is unchanged.

    VMAXPD

    N/A

    N/A

    Determines the maximum of float64 vectors. The corresponding Intel® AVX instruction is VMAXPD.

    VMAXSD

    N/A

    N/A

    Determines the maximum of Single-Precision float64 vectors. The corresponding Intel® AVX instruction is VMAXSD

    VMOVAPD

    VMOVAPD

    MOVAPD

    Move Aligned Packed Double-Precision Floating-Point Values

    VMOVAPS

    VMOVAPS

    MOVAPS

    Move Aligned Packed Single-Precision Floating-Point Values

    VMOVD

    VMOVD

    N/A

    Move Double

    VMOVDQU

    VMOVDQU

    MOVDQU

    Move Unaligned Double Quadword

    VMOVHPD

    VMOVHPD

    MOVHPD

    Move High Packed Double-Precision Floating-Point Value

    VMOVQ

    VMOVQ

    N/A

    Move Quadword

    VMOVSD

    VMOVSD

    MOVSD

    Move Data from String to String

    VMOVUPD

    VMOVUPD

    MOVUPD

    Move Unaligned Packed Double-Precision Floating-Point Values

    VMOVUPS

    VMOVUPS

    N/A

    Move Unaligned Packed Single-Precision Floating-Point Values

    VMULPD

    VMULPD

    MULPD

    Multiply Packed Double-Precision Floating-Point Values

    VMULSD

    VMULSD

    N/A

    Multiply Packed Single-Precision Floating-Point Values

    VPADDQ

    N/A

    N/A

    Add packed Quad-precision floating-point values

    VPBLENDVB

    N/A

    N/A 

    Conditionally blends word elements of source vector depending on bits in a mask vector

    VPBROADCASTQ

    N/A

    N/A

    Take qwords from the source operand and broadcast to all elements of the result vector

    VPCMPEQD

    N/A

    N/A

    Compares packed bytes/words/doublewords/quadwords of two source vectors

    VPCMPGTQ

    N/A

    N/A

    Compares packed bytes/words/doublewords/quadwords of two source vectors

    VPERM2F128

    VPERM2F128

    MULPD

    Multiply Packed Double-Precision Floating-Point Values

    VPSHUFD

    VPSHUFD

    N/A

    Permutes 32-bit blocks of an int32 vector

    VPXOR

    VPXOR

    PXOR

    Logical Exclusive OR

    VUCOMISD

    VUCOMISD

    UCOMISD

    Unordered Compare Scalar Double-Precision Floating-Point Values and Set EFLAGS

    VUNPCKHPD

    VUNPCKHPD

    UNPCKHPD

    Unpack and Interleave High Packed Double-Precision Floating-Point Values

    VUNPCKLPD

    VUNPCKLPD

    UNPCKLPD

    Unpack and Interleave Low Packed Double-Precision Floating-Point Values

    VXORPD

    VXORPD

    XORPD

    Bitwise Logical XOR for Double-Precision Floating-Point Values

    VXORPS

    VXORPS

    N/A

    Performs bitwise logical XOR operation on float32 vectors

    VZEROUPPER

    VZEROUPPER

    N/A

    Set the upper half of all YMM registers to zero. Used when switching between 128-bit use and 256-bit use.

    Table 1– Intel AVX2, AVX, and Intel SSE Equivalent Instructions

    The list in Table 1 is just a subset.  The full list can be obtained from the Intel® 64 and IA-32 Architectures Optimization Reference Manual. Intel AVX2 and Intel AVX are complementing each other’s, the instructions will be shared to provide the necessary functionality.    

    What is the performance gain from running the LINPACK benchmark with Intel AVX2 vs. Intel SSE enabled and Intel AVX2 vs. Intel AVX on the Intel Xeon E5-2699 v3 processor-based server?

    Table 2 shows the results from the three different workloads running on Windows* and Linux*.  In the “Ratio Intel AVX2 vs. Intel SSE” column, the numbers show that the LINPACK benchmark produces ~2.2x-2.8x better performance when running with the combination of an Intel AVX2 optimized LINPACK and an Intel AVX2 capable processor. For the Intel AVX2 vs. Intel AVX column, the numbers show that the LINPACK benchmark produces ~1.3x-1.6x better performance. This is just an example of the potential performance boost for LINPACK.  For other applications, the performance gain will vary depending on the optimized code and the hardware environment.

    Windows*

    Intel AVX2 (Gflops)

    Intel AVX (Gflops)

    Intel SSE4 (Gflops)

    Ratio: Intel AVX2 vs. Intel SSE

    Ratio: Intel AVX2 vs. Intel AVX

    LINPACK 30K v11.1.3

    735.59

    562.68

    331.75

    2.2

    1.3

    LINPACK 75K v11.1.3

    952.93

    589.18

    347.99

    2.7

    1.6

    LINPACK 100K v11.1.3

    959.90

    597.66

    350.51

    2.7

    1.6

    Linux*

     

     

     

     

     

    LINPACK 30K v11.1.3

    822.35

    574.78

    335.41

    2.3

    1.4

    LINPACK 75K v11.1.3

    964.23

    610.63

    346.73

    2.8

    1.6

    LINPACK 100K v11.1.3

    985.31

    611.71

    353.34

    2.8

    1.6

    Table2 – Results and Performance Gain from the LINPACK benchmark running on Intel® Xeon E5-2699 v3 two sockets server

    With new AVX2 instructions and the 256 bit registers on Intel E5 processor family, LINPACK was able to take advantage of the new instructions to achieve over 2x performance in comparison to running LINPACK with SSE instructions and over 1.3x performance against LINPACK running with AVX instructions.

    Software and workloads used in performance tests may have been optimized for performance only on Intel microprocessors. Performance tests, such as SYSmark* and MobileMark*, are measured using specific computer systems, components, software, operations and functions. Any change to any of those factors may cause the results to vary. You should consult other information and performance tests to assist you in fully evaluating your contemplated purchases, including the performance of that product when combined with other products.

    Configurations: Intel® Xeon® processor E5-2699 v3 @ 2.30GHz, 45MB L3 cache, 18 core pre-production system. Intel SSD S3500 Series (SSDSC2BB240G401) + Intel® SSD DC P3700 Series @ 400GB, 128GB memory (8x16GB DDR4 -2133Mhz), BIOS by Intel Corporation Version: SE5C610.86B.01.01.556.061320140714 BMC 0.20.6013 ME 03.00.05.402 SDR 0.10, Power supply: 1x 1100W Removable S-1100ADU00-201, running Microsoft* Windows Server 2012 R2 / SLES 11 SP3 Linux*

    For more information go to http://www.intel.com/performance

    Conclusion

    From our LINPACK experiment, we see compelling performance benefits when going to an AVX2-enabled Intel® Xeon® processor; in this specific case, we saw a performance increase of ~2.2x-2.8x for AVX2 vs. SSE and ~1.3x-1.6x for AVX2 vs. AVX in our test environment, which is a strong case for developers who have SSE-enabled code and are weighing the benefit of moving to a newer Intel® Xeon® processor-based system with AVX2. The reference materials below can help developers learn how to migrate existing SSE code to Intel AVX2 code.

    References:

    Notices: 
    INFORMATION IN THIS DOCUMENT IS PROVIDED IN CONNECTION WITH INTEL PRODUCTS. NO LICENSE, EXPRESS OR IMPLIED, BY ESTOPPEL OR OTHERWISE, TO ANY INTELLECTUAL PROPERTY RIGHTS IS GRANTED BY THIS DOCUMENT. EXCEPT AS PROVIDED IN INTEL'S TERMS AND CONDITIONS OF SALE FOR SUCH PRODUCTS, INTEL ASSUMES NO LIABILITY WHATSOEVER AND INTEL DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY, RELATING TO SALE AND/OR USE OF INTEL PRODUCTS INCLUDING LIABILITY OR WARRANTIES RELATING TO FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR INFRINGEMENT OF ANY PATENT, COPYRIGHT OR OTHER INTELLECTUAL PROPERTY RIGHT.

    UNLESS OTHERWISE AGREED IN WRITING BY INTEL, THE INTEL PRODUCTS ARE NOT DESIGNED NOR INTENDED FOR ANY APPLICATION IN WHICH THE FAILURE OF THE INTEL PRODUCT COULD CREATE A SITUATION WHERE PERSONAL INJURY OR DEATH MAY OCCUR.

    Intel may make changes to specifications and product descriptions at any time, without notice. Designers must not rely on the absence or characteristics of any features or instructions marked "reserved" or "undefined." Intel reserves these for future definition and shall have no responsibility whatsoever for conflicts or incompatibilities arising from future changes to them. The information here is subject to change without notice. Do not finalize a design with this information.
     

  • AVX2
  • AVX
  • SSE
  • server
  • High Performance Linpack
  • LINPACK Benchmark
  • Linpack
  • Sviluppatori
  • Partner
  • Studenti
  • Linux*
  • Server
  • Intermedio
  • Compilatore C++ Intel®
  • Azienda
  • Elaborazione parallela
  • Threading
  • Vettorizzazione
  • Server
  • URL
  • Argomenti sui compilatori
  • Miglioramento delle prestazioni
  • Area tema: 

    IDZone
  • Server
  • Release Notes Information - Intel® XDK

    $
    0
    0

    Intel XDK - Release - 2014 September 08 v1332

    Note: Our automatic updater will notify existing Intel XDK users when the update is available within the Intel XDK. The updates will be released to all users within 24 hours. If you would like the update sooner, just download from https://xdk-software.intel.com and the installer will update it as well.

    New Features:

    • Live Development Updates:
      • Live Layout, formerly Live Preview, is accessible on the Develop tab and lets you preview your app in:
        • Browsers (Google Chrome* and Mozilla Firefox*)
        • On Android* and Apple iOS* devices connected to your development system using a WiFi connection for both devices
      • Run My App, previously (“Active Sync”) lets you run your app either in an undocked emulator window or on your Android* device via a USB connection (formerly Preview on Devices).
  • Improvements have been made to the UI for Apache Cordova* plugins:
    • Added a “Featured Plugins” list for plugins that are better integrated into the Intel XDK and tested with the Intel XDK. There are only two in that list right now:
      • App Security APIs mentioned below
      • A plugin from our friends at Dolby Audio* that provides for some amazing audio quality for certain mobile devices.
  • Added an App Security API plugin to our Featured Plugins list which provides new APIs to aid in security for on-device app data and storage.
    • It offers Security Services for HTML5 developers via a JavaScript* API and middleware (in the form of a Cordova plugin)
    • It delivers on-device Secure Data (for data-in-use) and Secure Storage (for data-at-rest). The middleware protects the confidentiality, and integrity of storage elements and data access
    • Secure Data and Storage are the foundation for future enhancements and extension in domains like Transport, Identity, Input and Output
  • App Preview Updates:
    • Intel App Preview is now based on Apache* Cordova 3.5 and Intel XDK APIs (intel.xdk.*) are now supported via Cordova plugins.
    • Previous versions of Intel App Preview were based on the Intel XDK Legacy container, a hybrid application container developed by Intel. Starting with this version, Intel App Preview is based on Cordova in order to provide a better preview experience for Intel XDK projects based on Cordova.
    • The Intel XDK Legacy container is deprecated and will be retired in 2015. In order to support existing projects that use the Intel XDK Legacy container, a new application called Intel App Preview Legacy will be published soon.
    • New Look:
    • New Features:
      • 3-finger tap to stop previewing and return to Intel App Preview
      • 5-finger tap for version info of Intel App Preview and plugins
      • Configuration-based plugin loading

        The set of Cordova plugins loaded for your app running in Intel App Preview is based on your Intel XDK project configuration.

        This gives you a better idea of whether your project is correctly configured - a more valid "preview" experience.

        See this article for more information about configuring your Intel XDK project: https://software.intel.com/en-us/html5/articles/using-the-projects-tab
      • Live Layout Editing allows you to see the effect of edits on your app running in Intel App Preview as you make them in Intel XDK Develop tab.
  • New Feature for Android:
  • App Preview Crosswalk, which is used when working with the debug, profile, and live development features of the Intel XDK has been updated
    • Now uses Crosswalk* version 8.
    • Now contains the new Intel XDK plugins (matching App Preview), and includes the App Security plugin mentioned above.
  • Web Services Updates:
    • The ability to explore and integrate web services APIs is now located as a mini service explorer in the Develop tab (formerly the Services tab). Third party services can be easily integrated into an app by using the mini explorer during the development process. Data bindings created in the explorer can then be used in code via the editor or to exchange data to and from App Designer widgets.
    • A new search feature helps you quickly find the most appropriate services. Services are now tagged with keywords to guide you in finding the right service.
    • OAuth 2.0 authentication is supported.
    • Several new web services were added, such as jambase, tms and soundcloud.
  • App Designer Updates:
    • A new DOM Tree control has been added to browse the DOM tree.
    • The DOM tree entries are paired with a new HTML Preview pane so users can view or edit the HTML of an individual entry.
    • Service method instance now appears directly in App Designer. They can be dragged to widgets to set up data bindings.
    • Text Input widgets can be dragged to service method instances to drive a service request with user input.
    • Search has been added to the Controls pane to help find individual widgets
  • Added new demo applications which help users get started with the implementation of Ads and Monetization in their apps.
  • The build system now supports both Cordova 3.3 and 3.5 versions. You can set the Cordova CLI Version field, under Build Settings on the Projects tab, to specify which version you would like to build your app with.
  • Updated Intel XDK launch icons and splash screens
  • Issues Addressed:

    • Corrected the issue when using the undocked emulator, if you switched between projects or went back and forth between the docked and undocked emulator without letting the emulator fully load first, you may have seen a crash.
    • Fixed an issue where apps built using Crosswalk builds would display an “Unfortunately, <project-name> has stopped.” Message upon using the Android “Back” button.
    • Fixed an issue where the build system was swapping splash screen height and width in the <splash> tag in Cordova for iOS builds.
    • Corrected and issue on the Debug tab where it would not start app on device and a non-ending spinning "prepare" screen was shown.
    • On Apple OS X* systems, fixed a bug where the Intel XDK showed a different version than the About Intel XDK dialog box
    • For improved stability we addressed a number of issues related to logs sent in by users via the error log dialog within the Intel.

    Known issues:

    IssueWorkaround
    On Apple OS X* systems, attempting to start a second Live Layout session on Firefox* will display the following error message: A copy of Firefox is already open. Only one copy of Firefox can be open at a time.None
    Starting Google Chrome or Firefox Live Layout session after closing a previous Live Layout session from the Intel XDK, will display a message that the browser did not shut down properly.Simply dismiss the warning. The functionality of Live Layout should not be affected.
    When working with Services on the Develop tab, a dialog box shown in the service explorer does not get dismissed if the current project is changed without responding to the dialog box.Click the ‘Dismiss’ or ‘Thanks’ button and the dialog will be dismissed and should not affect the services for the new project.
    When using the Updater functionality to get the new version of the Intel XDK, if the download takes more than two minutes, you may see a message stating “"Cannot download an update since one is not available". Despite the message, the download is still continuing in the background and will complete unless internet connection is lost.Allow ample time for the download to complete, exit the Intel XDK and then restart. If the download completed successfully, you should now see the Install Update icon in the upper right hand corner of the Intel XDK toolbar next to the orange (?) icon.

    If the download has not completed successfully and the icon does not appear, you can try the download again or you can download the newest version of the installer from: http://xdk-software.intel.com and install from that.
    If you create an app based on the new blank project AND the following is true:
    • you use the sample init code from the init-app.js file in the blank project for detecting touch or click events
    • you run your app using “Live Layout Editing” in a browser on a machine that does not support touch
    If the above is true, your app may not detect any click events, because it will be looking for non-existent touch events.
    To fix this, in the blank project template code, change this if statement:
    if( navigator.msPointerEnabled )
    to this:
    if( navigator.msPointerEnabled || !('ontouchend' in window))
    in the init-app.js file.



    Intel XDK - Release - 2014 July 29 v1199

    New Features:

    • With this release of the Intel XDK, the HTML5 app project version is being updated to 1.1 from 1.0. Projects with a version of 1.0 will ONLY work with Intel XDK version 0876 and older.

      You will be prompted to upgrade your project to the new version in each of the following conditions:
      • The first time you run this version of the Intel XDK, if you were working on a project when you last used the previous version of the Intel XDK. That is, the Intel XDK will ask you to upgrade your saved “current” project.
      • When you request to open a different project from your list of projects. This will happen one time for each project you open and upgrade. If you choose not to upgrade, you will be prompted each time you attempt to open the project with this new version of the Intel XDK.

        IMPORTANT NOTE: The upgrade process makes changes to the project-name.xdk and project-name.xdke files in your project’s root directory. It does not change any other files. The changes are necessary to support new functionality in this version of the Intel XDK. Once you have upgraded a project, it can no longer be opened in previous versions of the Intel XDK. The upgrade process does create a backup of your project file named project-name.xdk10.bak. If for any reason you need to revert to using a previous version of the Intel XDK, you can delete the project-name.xdk and project-name.xdke files and rename project-name.xdk10.bak to project-name.xdk.

        Projects with a version of 1.0 will ONLY work with Intel XDK version 0876 and older.
    • We now have full support for Cordova APIs and Cordova (aka PhoneGap) plugins on iOS*, Android* and Windows* 8. The main difference between Cordova 2.x and Cordova 3.x is that the monolithic Cordova API has been replaced by a collection of independently selectable “plugins”. To use/test 3rd party plugins you must build your app and install it on device (see details under Known Issues below).

      A new UI on the Projects Tab allows you to select from a list of Cordova plugins that include the core Cordova API and standard Intel XDK APIs, which you can include in the app package you build. There are many consequences to this change that are discussed in detail in these articles:
      Adding Plugins to Your Intel® XDK Cordova App
      Add special build options to your Intel XDK Cordova app
    • Projects Tab Updates:
      • When you have a project selected on the Projects tab, there is a new section with the heading of “CORDOVA 3.x HYBRID MOBILE APP SETTINGS” on the project’s information screen where you can enter/edit build settings for an application that will use the Cordova 3.x architecture. These settings are only used when building with Cordova 3.x; they DO NOT affect building a “Legacy Hybrid Mobile App” or a “Web App”.

        In the previous release of the Intel XDK, you were required to create an intelxdk.config.xml file to specify the settings when building with Cordova 3.x. This is no longer supported and you must enter your settings from the Projects tab. The settings are divided into 3 main sections:
        • PLUGINS AND PERMISSIONS - here you can select from a list of Cordova plugins that include the core Cordova API and standard Intel XDK APIs, add custom (Third Party) plugins, and add any additional permissions that your application requires.

          NOTE: When adding third party plugins the UI only indicates to the build system what to upload, and that upload is only done during build time. If you want to include a custom plugin in the project directory while editing, you will need to manually download it and place in your project.
          Reference the following related article:
          Adding Plugins to Your Intel® XDK Cordova App

        • BUILD SETTINGS – here you enter other settings for your application such as its name and ID.
        • LAUNCH ICONS AND SPLASH SCREENS - here you enter splash screens and icons for your application

        When you select one of the “CORDOVA 3.x HYBRID MOBILE APP PLATFORMS” build tiles and upload your project sources, the Intel XDK will generate intelxdk.config.platform.xml files in your project root directory. These files contain the settings that you have made in the Projects tab and are used by the build server. You CANNOT edit these files as they are re-generated every time that the project’s sources are uploaded to the build server. A mechanism is provided to modify the automatically generated config file by creating an intelxdk.additions.xml file. For Reference:
        Adding Build Options to Your Intel® XDK Cordova App Using intelxdk.config.additions.xml

        Please refer to the following web page for additional information on working with the Projects tab:
        Using the Projects Tab
    • Added sorting options to the Your Intel XDK Projects list while on the projects tab.
      • Name – Sorts your projects alphabetically by name
      • Opened – Sorts your projects by last opened/touched date
        • Note that this sort only works with projects that have been upgraded to the new project version of 1.1 (See above Note)
    • App Preview Crosswalk, which is used when working with the debug, profile, and auto sync features of the Intel XDK, has been updated to use Crosswalk version 6.
    • The Emulator can now run in a separate window as well as in the Emulate tab. To undock the emulator into a separate window, click the up arrow icon in the corner of the Emulate tab. To run docked in the Emulate tab, close the undocked window (if open) either by clicking on the close control or by clicking the down arrow icon on the Emulate tab. You can then click the Emulate tab to run docked.
    • A mechanism to download and install App Preview from the cloud on to a user device if the user so chooses, has been implemented. The guides for the TEST, DEBUG, and PROFILE tabs have been updated to include a link to App Preview on the cloud server or you can email the link.
    • Editor Updates:
      • Brackets has been updated to Release 40
      • XLint extension now includes HTML and Media support – potential incompatibility issues are reported on HTML files and HTML media tags.
    • Services Updates:
      • Many new services have been added (Flickr, Weather Underground, and many more)
      • OAuth2 support has been added (the new FourSquare and Instagram services use it)
    • App Designer Updates:
      • New UI with draggable panels
      • Service Methods (from Services pane) now appear in App Designer and can be drag/dropped onto any control
      • In the Projects pane you can change the UI Framework for App Designer projects
      • A Google Maps data feed has been added
    • Firefox OS builds have been added to the Build a Web App section of the Build Tab

    Known issues:

    IssueWorkaround
    When using the undocked emulator, if you switch between projects or go back and forth between the docked and undocked emulator without letting the emulator fully load first, you may see a crash.Allow the Emulator to fully load before attempting to switch between docked and undocked mode. The Emulator should then work as expected in either mode. The dock/undock icon in the Emulate tab is disabled during Emulator startup, but this does not provide complete protection against the crash.
    The Intel XDK Emulate tab, App Preview, Test tab and Debug tab do not support third-party plugins for test and emulation. Attempting to call a third-party plugin API within the Emulator or App Preview will result in JavaScript errors that will likely result in halting your application.Workaround #1: The build system does allow the use of third-party plugins. Build your app using the Cordova 3.x Hybrid Mobile App Platform from the Build tab to test your app with plugins directly on device (e.g., build and install you test app on device, you can include the weinre script from the Test tab to perform simple console.log debugging, be sure to remove the weinre script tag before you build the production version of your application).

    Workaround #2: Utilize feature detection before calling the third-party plugin APIs to first determine if the third-party APIs are present (they will not be present when running in the Emulate tab or inside of App Preview). If you detect that the API is not present you will have to simply skip that part of your application or substitute an alert or console.log message or perform some other action that is appropriate to your application and debug/test scenario. This will allow you to quickly debug those parts of your application that do not depend on third-party plugins using the Emulate tab or App Preview.
    After you create a new project then work with that project using other tabs, when you return to the Start a New Project screen there will be no default selection for project type selected and text on right side of screen is not correctly shown.Reselect a project type from the left side menu and the right side screen will be properly refreshed to the correct project type.



    Intel XDK - Release - 2014 May 05 v876

    New Features:

    • The “Work with a Demo” panel has been updated to provide a more consistent look with the “Start with a Template” panel, including a banner on apps that are App Designer ready.
    • Editor - Updated to Brackets Sprint 38.
    • App Preview Crosswalk, which is used when working with the debug, profile, and auto sync features of the Intel XDK, is now being distributed to the device from the cloud versus the Intel XDK directly. You will be prompted to install the correct version (0.20) if already using an older version.
    • App Designer - now provides support for App Framework side-menus.
    • App Starter - Custom widgets support has been added.
    • Emulator – A “STOP” button was added which stops the emulation. To restart emulation for the app, you simply need to select the Refresh icon.

    Issues Addressed:

    • Corrected an issue when exiting the Intel XDK either by using CMD+Q or by selecting “Quit XDK” from the Intel XDK Menu on Mac OS X, you would momentarily see an error dialog.
    • Corrected an issue with the Intel XDK updater that caused the user to see the Safe/Normal restart option upon restart of Intel XDK after an install via the updater.
    • Corrected the following issue in the emulator:
      • The container supplies a file named "xhr.js" that is used to enable XMLHttpRequests to work without triggering cross-domain violations. Since this file does not exist in the project directory, the emulator must take steps to avoid a 404 (not found) error during emulation.

        Unfortunately, the solution the emulator applied effectively ignored files named "xhr.js" that did exist in the project directory. This corrupts the behavior of apps that rely on that source being included during emulation.

        Now the emulator correctly supplies its own content for xhr.js ONLY if that file does not exist in the project.
    • Corrected an issue which prevented creating two apps using the same demo back to back.
    • Addressed a number of issues related to logs sent in by users via the error log dialog.

    Known issues:

    IssueWorkaround
    Cannot drag/drop "textarea" element to a page in AppStarter project while working in the Design mode of the Develop tab.You will have to create the textarea manually in your HTML code.

    <div class='textarea_element form_element' style='width:100%;overflow:hidden'>
        <label>Textarea</label>
        <textarea></textarea>
    </div>
    While running the updater from the within the Intel XDK, you may receive the following error message, "Cannot download an update since one is not availble". This message indicates that the download of the update did not successfully complete.After receiving this message, you can exit the Intel XDK, reopen the Intel XDK and try the download again. Or, you can download the installer for the new version at http://xdk-software.intel.com and install from that.
    If updating to this version from our April Release Version (v0714) - While performing the install of the update from within the Intel XDK, when the Intel XDK restarts you will see a Safe/Normal restart dialog.Select the Normal Restart option and the Intel XDK should run normally. This issue has been corrected in the updater for any updates after 0714.



    Intel XDK - Update - 2014 Apr 21 v769

    Issues Addressed:

    • Addressed a number of issues related to logs sent in by users via the error log dialog.
    • Corrected a bad tooltip on the Emulator Back button.
    • Made an update to the Import Project screen to properly reflect the directory the project is stored in. Previously the information you entered in the “Name your project” field appeared to be adding a directory to the “Import From” path on the screen while it actually did not.
    • Corrected an issue with intel.xdk.player.playSound() method where it did not play on Cordova apps.
    • Cleaned up the following App Preview Crosswalk compatibility issues:
      • “Missing file” error due to xhr.js
      • reference to AppMobi in “useViewport” in display plugin
      • AppMobi reference in geolocation plugin
    • Fixed the following issues listed in the Known Issues section of the 2014 Apr 09 v714 release notes.
      • If your project contains any files that are all uppercase in name (i.e. LICENSE) and zero length in size, the bundle created during sync to the test server (Test tab), or sync to the build server (Build tab) may become corrupt when downloaded to your device for test or submitted for build.
      • If your app uses HTML files that don't include a <head> or <html> or <!DOCTYPE> tag the emulator thinks it is not a valid HTML file and won't load it.
      • When trying to test a project using the Test tab and the mobile wifi option (testing over your local wifi with App Preview) you may encounter a blank screen on your device after the app loads into App Preview.

    Known issues:

    IssueWorkaround
    While running the updater from the within the Intel XDK, you may receive the following error message, "Cannot download an update since one is not availble". This message indicates that the download of the update did not successfully complete.After receiving this message, you can exit the Intel XDK, reopen the Intel XDK and try the download again. Or, you can download the installer for the new version at http://xdk-software.intel.com and install from that.
    While performing the install of the update from within the Intel XDK, when the Intel XDK restarts you will see a Safe/Normal restart dialog.Select the Normal Restart option and the Intel XDK should run normally. This issue is being worked and will be corrected in the next version of the updater.
    While testing any of the App Designer created App Framework Templates on an Android 4.4 or higher tablet through the TEST or BUILD tab, you may notice that the entire application may be 80% of the device's width.After noticing this issue, you can edit the afui-header.less file to resolve this issue. In the projectname/css/index/afui-header.less file, change the css rule's selector from #afui header to #afui .header header.



    Intel XDK - Release - 2014 Apr 09 v714

    New Features:

    • Added new “Developer Preview” Cordova* for iOS* and Windows 8* build targets to build system – Android* was released in our February release, Windows Phone 8* is coming soon.
    • Added “Live Preview” support using a desktop Chrome browser window.
      • When using the Brackets editor in the Intel XDK, you can preview an HTML file from your project in a separate Chrome browser window. Modify the HTML and CSS in the editor to see the page modified "live" in this Chrome browser window.
    • Added “Preview on Device” support for Android devices.
      • When using the Brackets editor in the Intel XDK, you can preview an HTML file from your project on your Android device. Modify the static HTML and CSS in the editor, then save and see the page modified on the device.
    • Added a "Start with a Template" option to the Start a New Project pane.
      • Using this option you can start a new project based on an "empty" UI project template.
      • Templates differ from "Demo" projects in that they are not fully functional. They are shell apps, each providing a common UI experience (list, flip, grid view, login page, side menu, etc.).
      • The templates are based on App Framework and are fully compatible with App Designer.
    • Added capability for seamlessly integrating Web Services into your app.
      • The services tab now allows for management, exploration, and embedding web service APIs.
      • Embedded web service APIs are available for use from within all aspects of the XDK: Brackets, App Designer, App Starter, the emulator and App Preview.
      • The list of built-in services include appMobi and several Mashery-managed services (USA Today Census, Klout, and Rotten Tomatoes)
    • Added a “Settings Dialog Box” – this is a Preview Implementation.
      • At this time only a few settings are available on this dialog. Access the settings dialog by clicking the gear symbol near the user login symbol in the top right corner of the Intel XDK window. Two tabs are present in the settings dialog: “general” and “services.”
      • From the “general” settings dialog tab you can suppress the quick tour message after creating a new project and you can specify a list of file and directory names to be ignored by the Intel XDK. Files and directories that match the ignored file list will not be submitted to the cloud when you use the Build or Test tabs. Note that the wildcard (*) character is supported as part of this list. We recommend that you maintain the initial default list, as this covers many of the typical hidden files and directories that could be found in your project folder. (Note that you cannot change this to be ignored list on a per project basis. If that level of control is important to you, we would appreciate receiving your feedback. Please provide feedback via the Intel XDK forum.)
      • On the “services” settings dialog tab you can set or clear whether the services JavaScript helper libraries automatically created by the Services tab should be minified and compressed or left in an easy to read format. Normally this code is minimized, but for debugging and inspection it is useful to turn this feature off. Y1u can also specify the directories used by the Services tab to store services-specific files. These directories are relative to your top-level project directory; you cannot enter an arbitrary absolute directory name. The directory finder will not prevent you from attempting to use an arbitrary path, but only directories located within your project folder will be accepte1. Unlike the “general” settings tab, the “services” settings tab values are set on a per project basis. The values displayed represent the current project (the project selected in the project tab). If you have no current project selected, this tab displays nothing.
      • In a future version of the Intel XDK, the Emulator tab settings will be merged with this dialog. When working from the Emulator tab you will see two “gear” icons: the Emulator settings icon in the upper left corner of the screen and the Settings dialog icon in the upper right corner.
    • Node Webkit updated to version 0.8.5 and all node modules updated.
    • Editor Updates:
      • Updated to Brackets Sprint 37.
      • Fixed git on Linux.
      • Made improvements to editor startup performance.
      • The editor extensions catalog was updated with newer versions of extensions. Post your suggestions on our forums.
    • Emulator Updates:
      • Added a new "Multi-Page Testing" panel. Enter any absolute URL and see that content in the emulator. This is useful for testing web applications that rely on server side support but want to be mobile-friendly. Note that API emulation does not work on pages loaded in this manner.
      • The Back button in the Devices Panel now implements "back" in the program under test, not "back" in the Intel XDK itself.
    • Crosswalk Updates:
      • The version of the Crosswalk build targets available via the Intel XDK’s “Build” tab has been updated. The stable version of Crosswalk has been upgraded to version 4.32.76.6 and the beta version has been updated to 5.34.104.2 Several new features are included in Crosswalk-5 including a new SIMD JavaScript API that takes advantage of SIMD support on Intel processors.
        Crosswalk-4 release notes can be found at: https://crosswalk-project.org/#wiki/Crosswalk-4-release-notes
        Crosswalk-5 release notes can be found at: https://crosswalk-project.org/#wiki/Crosswalk-5-release-notes
      • The version of Crosswalk used to enable the debug and profile features in the Intel XDK has been updated to match the beta version - Crosswalk 5.34.104.
    • App Starter:
      • Updated to App Framework 2.1.
      • UI updates to toggle between widgets and full screen modes.
      • Widget sections can be collapsed/expanded.
      • Added title under each icon in widgets sections.
    • App Designer updated to use App Framework 2.1.
    • Added a Twitter Feed icon to top navbar so you can follow Tweets about the Intel XDK.
    • In conjunction with this release, App Preview has been updated for iOS, Windows, Windows Phone and Android.
      • Updates for all platforms:
        • Bug fixes, branding updates and feature enhancements.
        • LOTS of bugs have been reported and fixed in the build system since the last release - this release fixes all of those bugs in App Preview as well.
        • We have a new icon.
        • The most visible feature change is that you can now filter your list of apps - other usability changes are sprinkled throughout.
      • Additionally, for Android:
        • When previewing an app, you can now use the device back button to exit preview mode and return to App Preview (previously you had to close the app to return to App Preview).
        • Preview mode remote debugging is now enabled for KitKat devices from Chrome (while previewing your app, it will be listed as an inspection target in Chrome).

      Issues Addressed:

      • Based on customer feedback about slowness, we enhanced the performance of the Intel XDK when working with large projects that contain many files.
      • Added path information to projects list and project dropdown for duplicate project names stored in separate locations to provide disambiguation. Note: project names are not disambiguated in the build system.
      • Corrected an issue in App Designer that was causing the user_scripts.js file to be overwritten.
      • Corrected an issue in the emulator where the change orientation icons were acting as a “back” button.
      • Emulator now correctly uses the UserAgent string for the device under test, not the UserAgent string for the host system.
      • Addressed multiple crash items that were reported in the previous release.

      Known issues:

      IssueWorkaround
      If Preview on Devices, the Debug tab, and the Profile tab seem to not be responding, especially when you start the process, it may be that App Preview is not running. The component that makes these function work, App Preview Crosswalk, requires that App Preview be running whenever you start these functions.Look for App Preview in your Android multitasking list or in the "running" list in the apps settings page of your device. If App Preview is not running kill the App Preview Crosswalk task by swiping it to the side (from the multitasking list) or by choosing "Force Stop" from the application manager in the settings section of your device. Re-launch App Preview manually. This process should restore the functionality of those features.
      If your project contains any files that are all uppercase in name (i.e. LICENSE) and zero length in size, the bundle created during sync to the test server (Test tab) or sync to the build server (Build tab) may become corrupt when downloaded to your device for test or submitted for build.Rename any such files to be lower case or remove them if they are not a necessary part of your project.
      The Live Preview feature requires the Chrome browser to work properly. If you are using a Linux system and running Chromium, you will not be able to use Live Preview.Install Google Chrome on your Ubuntu system
      On Mac OS X, if you exit the Intel XDK either by using CMD+Q or by selecting "Quit XDK" from the Intel XDK menu, you will momentarily see an error dialog.This error does not affect the functionality of the Intel XDK and will be fixed in an upcoming release.
      If your app uses HTML files that don't include a <head> or <html> or <!DOCTYPE> tag the emulator thinks it is not a valid HTML file and won't load it. If you are using the Angular framework you may have some of these files in your project, which is normally okay, until you try to run your app in the emulator. (Your app will continue to run in App Preview, from the Test tab and from the Debug tab, it just fails in the Emulator tab.)You can work around the problem by inserting a <!DOCTYPE html> tag at the top of those files that won't load. This issue will be addressed in a future edition of the XDK.
      When you create a new app from a template and then open that app inside of the UI editor (App Designer), you may be unable to select or modify some of the elements on the new app created from that template.Push the "recycle" button (the refresh button) in the toolbar, which will force App Designer to reread the new application. Now the sample elements in your new application should be selectable.
      When trying to test a project using the Test tab and the mobile wifi option (testing over your local wifi with App Preview) you may encounter a blank screen on your device after the app loads into App Preview.The Test tab is not observing the location of the index.html file in your application, as specified by the SOURCE DIRECTORY pathname specified on the Projects tab; the Test tab is looking for your application (e.g., the index.html file) in the PROJECT PATH directory. Move your application files up so they reside in the PROJECT PATH directory and change the SOURCE DIRECTORY so it is blank (points to the same directory as the PROJECT PATH) by pushing the pencil icon to the right of the SOURCE DIRECTORY pathname. Other tools within the XDK will honor the location specified by the SOURCE DIRECTORY, so you must make sure this parameter points to the location of your index.html file.



      Intel XDK - Release - 2014 Feb 24 v505

      The main focus of this release was to address issues reported through testing and by our end users. We added some new features including a developer preview of our new Cordova Build.

      New Features:

      • Added "Developer Preview” of Cordova for Android build target to build system
        • Android only (Windows 8, iOS and Windows Phone 8 will be added in future releases
        • Based on Cordova 3.3.1-0.1.2
        • Features and settings are configurable via "intelxdk.config.xml" in your XDK project
        • All Cordova "base” plugins are supported (version is configurable)
        • A subset of Intel XDK APIs are supported via Cordova plugins
        • The HTML assets for a project may be put into a subdirectory of the project root directory. For example, the Intel XDK ‘blank’ project will put the assets into a ‘www’ subdirectory. You may set/modify this directory in the Projects tab in the Source Directory field by selecting the edit icon.
        • Developer Preview means that this functionality has received minimal QA. Feedback is requested via our forums.
        • Additional details will be made available via forum and/or blog posts soon
      • Editor Updates:
        • Brackets updated to Sprint-36.
        • Editor extensions are enabled in this release. Use File->Extension manager to install and use them.
        • Open files in Editor using Drag and Drop
        • External changes to the project file are automatically reflected in the editor. It includes adding, deleting, moving and changing the content of the files
      • GIT Integration - Git users can use Brackets Git extension to manage the repository directly from the editor.
      • Static Checking - XLint, a compatibility static checker for XDK is available starting this release as an editor extension. For more information, refer to http://software.intel.com/en-us/html5/articles/xlint_intelxdk
      • Emulator Updates:
        • Cordova Audio Recording API functions now work under emulation
        • Cordova Beep notification function actually beeps under emulation
        • There is a "Back” button in the Device Emulator Panel. Currently this functions as a Back button would in a browser.
        • Emulator will work even if the HTML file doesn’t contain any <html> or <head> tag
      • App Starter updated with App Framework 2.0.6
      • App Designer can now create custom CSS classes and edit them directly within App Designer
      • Individual help topics have been added to the help menu for each tab which take you directly to documentation related to the current tab.
      • Added ‘safe’ restart mode on crash recovery.

      Issues Addressed:

      • Issues with the updater on MacOS systems that did not properly update to new version
      • Geolocation details tab issues in emulator
      • Emulator does not properly emulate appMobi pay services
      • Over 100 smaller issues addressed

      Known issues:

      IssueWorkaround
      If selecting Help icon while working with an App Designer project, the Help becomes stuck on App Designer help.There is no known workaround.
      The User Agent string used under emulation does not match that of the selected device. The emulator attempts to set the navigator.userAgent property according with the device being emulated, but node-webkit treats this property as read-only so the emulator cannot modify it.
      This defect means that data returned from servers that sniff the User-Agent header may return inappropriate content. One such server is Google Maps.
      This problem is fixed in node-webkit version 0.9.x, but the XDK currently requires node-webkit 0.8.x. When the user agent fix is back-ported in node-webkit version 0.8.5, upgrading to that version of node-webkit should fix the problem. This will require an XDK update.
      There is no user-level workaround.



      Intel XDK NEW - Update - 2014 Feb 10 v419

      • Intel XDK can now be installed on Windows XP* platform. While it can be installed, XP is not a fully supported platform.
      • Made the Country list for signup a local file so that it is always available to users regardless of connectivity.
      • Emulator - The emulator synthesizes touch events from mouse events. Made improvements to these synthesized events where they did not behave properly for some higher level frameworks like Google Maps, which respond to both touch and mouse events.
      • Corrected an issue that caused an error when attempting to upload large projects to the build system.



      Intel XDK NEW - Update - 2014 Jan 10 v277

      • Updated to Node-webkit version 0.8.4
      • Build tab - corrected an error message thrown when network connection is lost.
      • XDK can now upload a bundle larger than 25 MB to the build system.
      • Prevent hot keys from being triggered by [AltGR] + [number] combo on foreign keyboards as this was overriding normal keys on some of those keyboards.
      • Corrected an issue when pasting text from clipboard into Find within the editor. Previously it would paste the text into the content of the file versus the Find input box.
      • Emulate Tab - corrected an issue (on Mac and Windows versions) where the Chrome Debug Tool window did not always restart in the same position and size when you changed devices. On Linux the size will be retained but the location is not retained. We will continue to work to correct that issue.



      Intel XDK NEW - Release - 2013 Dec 17 v240

      What’s new:

      • Added two new tabs: Debug and Profile. Make use of these tabs to remote debug your app on device or analyze the performance of the JavaScript used in your app using App Analyzer.
      • Remote Debugging allows user to debug on Android 4.x based mobile device connected via USB.
      • App Analyzer allows users to set breakpoints in code, inspect variables, and single step through source code.
      • App Analyzer supports the Crosswalk APIs and provide similar performance as apps built using the Intel XDK Crosswalk target build.
      • Improved Tizen app builds allowing Tizen code-signing to submit apps to Tizen App Store.
      • Added Hot-Keys to Switch between tabs in the XDX:
        • ['Ctrl'] + ['Tab'] = Switch to previous tab (show tab-switcher UI). (or if ['Ctrl'] is held and ['Tab'] pressed cycle trough tabs in switcher UI)
        • ['Ctrl'] + ['Shift'] + ['Tab'] = Show tab-switcher (or if ['Ctrl'] is held and ['Tab'] pressed cycle trough in reverse ordertabs in switcher UI)
        • ['Ctrl'] + [Number Key] = Switch to tab based on order in tab bar
        • Example: ['Ctrl'] + ['1'] = Switch to the first tab in the list (currently develop)
        • ['Ctrl'] + ['0'] = Switch to the projects tab
        • Note: on OS X the shorcuts that do not contain a ['Tab'] key can be used by substituting ['Command'] for ['Ctrl'] (but ['Ctrl'] can still be used if desired)
      • App Designer multiple page support, themes, and interactivity.
      • App Designer allows page and sub-pages creation, button hookup to pages, sidebars, popups or custom scripts.
      • App Designer allows animated transition selection for a link to a page and more.
      • App Designer allows users to “drop in” third party themes for frameworks that support it.
      • App Designer allows basic javascript editing within App Designer.
      • Brackets updated to Sprint 34.1.
      • Editor supports autocompletion for Cordova 2.9.0 and intel.xdk APIs.
      • Better editor integration with the OS:
        • File->Open lets open any file on the filesystem
        • File->Save As allows saving to any location on the local filesystem
        • “Show in OS” context menu in the file tree opens OS file manager (e.g. Explorer, Finder) at the project file location.
        • Editor uses JSHint instead of JSLint as in previous versions. JSHint can be configured using .jshintrc in the project root. For the documentation on configuration options and configuration file format, refer to JSHint Docs.
        • Added copy/cut/paste context menu in the editor.
      • Images can be previewed in the editor. In previous version they appeared as binary content.
      • Code/Design buttons are always displayed when using AppDesigner and AppStarter projects. Design button is only enabled on .html files in these projects.
      • Emulator now supports apps that use the synchronous form of XMLHttpRequest (XHR).
      • Emulator settings now let you choose whether the JavaScript console should be cleared each time the app restarts (default is to clear). App restarts when you click reload, change projects, change devices, or change source when the always reload setting is selected.
      • Emulator automatically restarts debugger if debugger is running when the app restarts. Debugger must still close during the restart operation itself.
      • Emulator correctly initializes Accelerometer panel to +9.81 in z-axis, not -9.81.
      • App Designer gets automatically opened when creating a new project.

      Known issues:

      IssueWorkaround
      Cannot access project files on Windows via a UNC path.Make sure all your files are stored on a local drive.



      Intel XDK NEW - Update - 2013 Nov 07 v154

      • First Time users of Intel XDK NEW are required to either perform an initial login (if they already have an Intel XDK - Original account), or create an account if they don't already have one.
      • The text and link provided within "Email Invitation to Test Your App" on the Projects tab has been updated to use App Preview versus app.lab.
      • The following XDK NEW and XDK original conflict issues identified in the October release have been resolved:
        • Original XDK cannot be started if XDK NEW is already running
        • XDK NEW may not start if Original XDK is already started.
      • Links for downloading App Preview from the various stores are provided on the Test tab for first time users who have not yet installed App Preview.



      Intel XDK NEW - Release - 2013 Oct 20 v115

      What’s new:

      • Brackets Editor updated to version Sprint 32
      • Mac* OS X and Ubuntu* Linux versions are now available as well as Windows*. Windows 8.1 supported.
      • Intel App Preview released to Google* Play Store and Apple* App Store. Intel XDK NEW now uses Intel App Preview for testing on device.
      • Test using Local WiFi is now available in Test Tab
      • App Starter has been integrated into XDK and is an available option when creating a new project
      • App Designer and AppStarter are only available in projects of the corresponding type (see known issues)
      • Improved XDK NEW documentation
      • An XDK Overview Quick Tour has been added. It is available the first time you create a project, or always available from the Help menu
      • Added “Visit the Forums” and “Submit a Bug” items under the Help menu so users can better provide feedback or report issues.
      • Added additional tool tips and Info popups to aid users
      • App Designer now supports Adobe* Topcoat
      • Several new demo apps have been added to the “Work with a Demo” option when creating a new app.
      • Web App builds now work
      • Fixed bug where XDK NEW crashed when switching devices in the Emulator while debug window open.
      • Fixed crash when attempting to select a project no longer on local file system.
      • Build page now closes when switching projects.
      • Script tag to embed for using the Weinre* debugger has been corrected.
      • Links to PDF files from Build screens are now functional
      • Many other bug fixes based on user reports and feedback. Thank You.

      Known issues:

      IssueWorkaround
      Original XDK cannot be started if XDK NEW is already running.Install Intel XDK New version 0154 update.
      - or -
      If using October 2013 release, start original XDK first, then XDK NEW
      Automatic Updates from some previous Mac versions won’t restart XDK NEW after update.Manually start the updated XDK NEW after the update completes.
      Updates from some previous Linux versions won’t work.Download the appropriate Linux version and run the installer manually.
      Old App Designer projects no longer open as App Designer projects.Modify the project-name.xdk file located in the project directory to change the type: field to   “type”: “App Designer”,.

    Анализ производительности Java на устройствах Android с помощью Intel® VTune™ Amplifier 2014 for Systems

    $
    0
    0

    Intel® VTune™ Amplifier 2014 for Systems поддерживает анализ функций Java и доступ к ассемблеру с JIT, Java Source и Dex* для функций, обработанных с помощью JIT на рутованных устройствах Android*, на которых запущена виртуальная машина Java/Dalvik* с оснасткой.  Прочтите эту статью позже, чтобы узнать, как запустить будущую версию VTune Amplifier for Systems для включения анализа Java на ART* JVM.

    Если возникают следующие проблемы:

    • После сбора - time(samples) связано с функцией/модулем: [dalvik-jit-code-cache (удалено)] в "Basic Hotspots"
    • После сбора - time(samples) связано с функцией/модулем: [Вне любых известных модулей] в разделе "Advanced Hotspots"или в любых других типах выборки на основе событий оборудования
    • Функция Java связана с ассемблером (или с чем-то посторонним), —

    то, по всей вероятности, нужно заново настроить устройство Android, чтобы компонент VTune Amplifier мог работать с кодом Java. Необходимы следующие 4 компонента:

    1. Рутованное устройство Android
    2. Dalvik JVM с оснасткой VTune Amplifier
    3. Запустите виртуальную машину Dalvik с включенной оснасткой
    4. Выполните анализ в VTune Amplifier и укажите процессы для просмотра сведений о Java.

    Для получения дополнительных сведений см:

    Руководство пользователя Intel® VTune™ AmplifierЗапуск удаленного анализаПодготовка целевой системы Android* для удаленного анализа

    1) Устройство Android с корневым доступом

    Убедитесь, что возможен рутовый доступ к устройству.  Выполните следующую команду на подключенной системе с adb.

    adb root

    Если вы получите сообщение:

    adbd is already running as root

    или

    restarting adbd as root

    то устройство рутовано. Отладочные и инженерные образы ОС Android обычно с легкостью рутуются.  Рутовый доступ к пользовательским образам обычно не удается получить.  Для получения широкодоступного устройства с возможностью рутования см. http://www.intel.com/mdk или http://01.org/android-ia.

    2) Получение Dalvik JVM с оснасткой VTune Amplifier

    Многие устройства Android с процессорами Intel® Atom поставляются с ядром Dalvik с подключенной оснасткой. Некоторые исключения, заслуживающие упоминания:

    Определение наличия оснастки Dalvik на вашем устройстве

    Выполните команду:

    adb shell dalvikvm -get Help

    найдите –Xjitvtuneinfoв списке возможных параметров.

    Если этот параметр отсутствует, поддержка оснастки для VTune отсутствует в системе Dalvik на устройстве, и его нужно заменить.

    Замена libdvm.so на вашем устройстве

    Intel VTune Amplifier 2014 for Systems, обновление 1, содержит версию libdvm.so с оснасткой в папке <path-to-vtune>/target/android_v3.10/prebuilt//DellVeune8.  Для установки выполните следующие команды:

    1. adb root
    2. adb remount
    3. adb push <path-to-vtune>/target/android_v3.10/prebuilt/DellVeune8/libdvm.so /system/lib
    4. adb reboot

    3) Запустите виртуальную машину Dalvik с включенной оснасткой VTune Amplifier

    VTune Amplfier 2014 for Systems по умолчанию настраивает ВМ Dalvik для оснастки в следующих случаях:

    При создании нового проекта в пользовательском интерфейсе, выбрав в качестве системы назначения устройство Android (ADB), затем в первый раз запустите сбор на этом устройстве. При этом оснастка будет переведена в режим JIT. Это дает вам возможность отслеживать все функции в графическом пользовательском интерфейсе, но при попытке открытия конкретных функций будет открыт ассемблер (а не исходный код Java и не байтовый код Dex).

    Для изменения значений по умолчанию нужно вручную запустить установщик с основного устройства:

    Linux: <путь к vtune>/bin[32|64]/amplxe-androidreg.sh --package-command=install --xjitvtuneinfo=src

    Windows: <путь к vtune>\bin32\amplxe-androidreg.bat --package-command=install --xjitvtuneinfo=src

    Где --xjitvtuneinfo=srcможет иметь одно из следующих значений:

    • Основные сведения о скомпилированной трассировке: -Xjitvtuneinfo=jit
    • Сопоставление от кода JIT к исходному коду Java и базовая информация о скомпилированной трассировке: -Xjitvtuneinfo=src
    • Сопоставление от кода JIT к коду DEX и базовая информация о скомпилированной трассировке: -Xjitvtuneinfo=dex
    • Сбор данных JIT. По умолчанию сбор данных JIT отключен, если не указать никакие параметры: -Xjitvtuneinfo=none

    По умолчанию установщик изменит /data/local.prop следующим образом, чтобы включить JVM для VTune при всех последующих перезагрузках ОС.

    root@android:/ # cat /data/local.prop
    dalvik.vm.extra-opts=-Xjitvtuneinfo:src

    Для Dell Venue 8 и устройств, которые не могут использовать /data/local.prop, следующая процедура сработает с главного устройства.

    adb shell setprop dalvik.vm.extra-opts -Xjitvtuneinfo:src

    Установите для свойства значение src, dex, jit или none

    adb shell stop
    adb shell start

    Не перезагружайте устройство. Убедитесь, что это свойство задано, с помощью adb shell getprop.  Выходные данные должны содержать [dalvik.vm.extra-opts]: [-Xjitvtuneinfo:src]

    4) Выполните анализ в VTune Amplifier и укажите процессы для просмотра сведений о Java

    VTune Amplifier может связывать выборки с кодом JIT с помощью всех доступных типов анализа, но требуется заключительный шаг.  Необходимо запустить анализ для проекта с помощью Attach to Process или Launch Android Package. При этом будут получены только те JIT-файлы, которые были указаны в параметрах проекта.

    Для двух типов анализа в VTune Amplifier может потребоваться вручную поместить JIT-файлы в папку результатов:  если в свойствах проекта вы указали Profile System либо если вы указали Analyze System-Wide для Attach to Process или Launch Android Package в разделе Advanced Settings.  Затем можно просмотреть JIT-файлы для нужных процессов, которые не были указаны.   См.:  Руководство пользователя Intel® VTune™ AmplifierПоддержка интерфейса командной строкиВыполнение анализа из командной строкидля получения дополнительных сведений.

  • VTune Amplifier Java Dalvik Android
  • Sviluppatori
  • Android*
  • Android*
  • C/C++
  • Java*
  • Avanzato
  • Intermedio
  • Intel® System Studio
  • Intel® VTune™ Amplifier
  • Strumenti di sviluppo
  • Dispositivi mobili
  • Ottimizzazione
  • Telefono
  • Tablet
  • URL
  • Miglioramento delle prestazioni
  • Area tema: 

    Android

    Обмен текстурами между Intel Media SDK и OpenGL

    $
    0
    0

    Code Sample

    Краткий обзор

    Обычно в ОС Windows* для обработки видео используется Direct3D. Однако во многих приложениях неизменность графического интерфейса и внешнего вида при работе на разных платформах обеспечивается за счет возможностей OpenGL*. В последних версиях графических драйверов Intel поддерживается расширение NV_DX_interop, что обеспечи-вает возможность обмена поверхностями между D3D и OpenGL для их последующего использования в Intel® Media SDK. В Intel® Media SDK можно настроить использование Direct3D, а благодаря поддержке NV_DX_interop кадровый буфер Intel Media SDK может использоваться в OpenGL. При этом устраняется необходимость в ресурсоемком копировании текстур из графического процессора в ЦП и обратно для обработки. В данном примере кода и техническом документе приведена процедура настройки использования D3D в Intel® Media SDK для кодирования и декодирования видео, преобразования цветов из цветовой схемы NV12 (стандартный цветовой формат Media SDK) в схему RGBA (стандартный цветовой формат OpenGL) и сопоставления наложения поверхности D3D с на текстурой текстуру OpenGL. В данной процедуре отсутствует этап копирования текстур из графического процессора в ЦП для обработки, что всегда представляло большую сложность при использовании OpenGL с Intel® Media SDK.

    Требования к системе

    Пример кода написан с помощью Visual Studio* 2013. Он предназначен (1) для демонст-рации работы Miracast и (2) обмена текстурами между Intel® Media SDK и OpenGL. В процессе обмена декодированные поверхности Intel® Media SDK сопоставляются с текстурами OpenGL без необходимости в выполнении копирования, что значительно повышает эффективность работы. При использовании процессоров Haswell и более поздних версий выполняется аппаратное ускорение декодера MJPEG. При использовании процессоров более ранних версий в Media SDK автоматически применяется программный декодер. Необходимо использовать камеру с поддержкой MJPEG (это может быть как встроенная камера, так и камера с подключением через USB).
    Большая часть процедур, используемых в примере кода и техническом документе, применимы и для Visual Studio 2012 (за исключением идентификации типа подключения Miracast). Пример кода основан на Intel® Media SDK 2014 для клиентских систем. Загрузить пример можно по следующей ссылке: (https://software.intel.com/sites/default/files/MediaSDK2014Clients.zip.) После установки SDK создается набор переменных среды для поиска правильных путей к файлам заголовков и библиотекам в Visual Studio.

    Обзор приложения

    Приложение распознает камеру как устройство ввода MJPEG, выполняет декодирование этого видео, затем кодирование потока в формат H264 и, наконец, его декодирование и завершение обработки. Поток видео формата MJPEG с камеры (после декодирования) и полностью обработанные потоки отображаются в графическом интерфейсе на базе MFC. В системах Haswell для обеспечения удобочитаемости выполняется последовательный запуск двух декодеров и одного кодировщика (с разрешением 1080p). Благодаря аппаратному ускорению эта процедура не занимает много времени. Единственным ограничением количества передаваемых кадров в секунду является скорость работы камеры. В реальных условиях кодировщики и декодеры запускаются в отдельных потоках, поэтому проблем с производительностью возникать не должно.

    При использовании одного монитора в графическом интерфейсе на базе OpenGL потоковое видео с камеры отображается в режиме «картинка в картинке» поверх обработанного видео (рис. 1). При использовании технологии Miracast программа автоматически определяет монитор с поддержкой Miracast , и на нем во весь экран отображается окно с обработанным видео, при этом в основном графическом интерфейсе отображается необработанное видео с камеры. Такой режим позволяет с легкостью сравнить исходное и кодированное видео. Кроме того, в меню View -> Monitor Topology можно отслеживать текущую топологию мониторов, а также изменять ее. К сожалению, запустить подключение Miracast в этом меню невозможно. Это можно сделать только в меню чудо-кнопок ОС (меню чудо-кнопок справа -> «Устройства» -> «Проект»). На настоящий момент API для запуска подключения Miracast не существует. При этом отключить Miracast-монитор можно, изменив топологию мониторов на «только внутренние». При наличии нескольких мониторов, подключенных с помощью проводов, их топологию можно в любой момент изменить в этом меню.

    Рисунок 1. Топология с использованием одного монитора. Видео с камеры MJPEG отображается в правом нижнем углу. Обработанное видео отображается во весь экран. При включении режима использования нескольких мониторов (например, в режиме Miracast) программа обнаруживает данное изменение, в результате чего видео с камеры MJPEG и обработанное видео автоматически выводятся на разные мониторы.

    Главная точка входа для настройки процесса обработки

    Пример кода выполнен на базе MFC. Главная точка входа для настройки процесса обработки — CChildView::OnCreate (). Здесь выполняется инициализация камеры с последующим транскодированием видео из формата MJPEG в H264, декодированием формата H264 и связыванием текстур из транскодера и декодера в модуле визуализации OpenGL. Транскодер представляет собой подкласс декодера с добавлением кодировщика поверх базового декодера. Событие OnCreate запускает поток, в рамках которого осуществляется и упорядочивается потоковое вещание с камеры. При считывании потокового вещания рабочий поток отправляет сообщение функции OnCamRead, которая выполняет декодирование видео в формате MJPEG, кодирование в формат H264, его декодирование и обновление текстур в модуле визуализации OpenGL. На верхнем уровне весь процесс очень прозрачен и прост.

    Инициализация декодера/транскодера

    Для использования D3D9Ex необходимо выполнить инициализацию декодера и транс-кодера. Intel® Media SDK может быть настроен на использование программного метода, D3D9 или D3D11. В этом примере для упрощения преобразования цветов используется D3D9. Стандартным цветовым форматом Intel® Media SDK является NV12. Для преобразования цветовой схемы в формат RGBA можно использовать функцию IDirect3DDevice9::StretchRect или функцию IDirectXVideoProcessor::VideoProcessBlt. В целях упрощения в этом техническом документе используется функция StretchRect, однако на практике рекомендуется использовать функцию VideoProcessBlt, так как в нее включена дополнительная возможность последующей обработки. К сожалению, D3D11 не поддерживает StretchRect, что может усложнить процесс преобразования цветов. Кроме того, в этом документе для выполнения различных опытов (таких как сочетание различных типов программного и аппаратного обеспечения) в декодере и транскодере используются отдельные устройства D3D. Однако для экономии ресурсов памяти в декодере и транскодере может использоваться одно устройство D3D. В результате такой настройки процесса обработки результатам, получаемым на выходе после декодирования, задается тип (mfxFrameSurface1 *). Это оболочка для D3D9. Тип mfxFrameSurface1 -> Data. MemId можно преобразовать в тип (IDirect3DSurface9 *). После декодирования этот тип можно использовать в StretchRect или VideoProcessBlt функции CDecodeD3d9::ColorConvert. Полученные поверхности Media SDK нельзя сделать общими, однако преобразование цветов все равно является обязательным в OpenGL. Для хранения результатов преобразования создаются общие поверхности.

    Инициализация транскодера

    Декодированные транскодером данные направляются непосредственно в кодировщик. Убедитесь, что при выделении поверхностей используется MFX_MEMTYPE_FROM_DECODE.

    Связывание текстур в D3D и OpenGL

    Код для связывания текстуры можно найти в функции CRenderOpenGL::BindTexture. Убедитесь, что расширение WGLEW_NV_DX_interop определено, затем последовательно используйте функции wglDxOpenDeviceNV, wglDXSetResourceShareHandleNV и wglDXRegisterObjectNV. Поверхность D3D связывается с текстурой OpenGL. Текстуры не обновляются автоматически. Их можно обновить, вызвав функции wglDXLockObjectsNV/wglDXUnlockObjectsNV (CRenderOpenGL::UpdateCamTexture и CRenderOpenGL::UpdateDecoderTexture). После обновления текстуру можно использовать, как любую другую текстуру в OpenGL.

    Важные моменты при изменении топологии для нескольких мониторов

    Может показаться, что вывести еще одно окно на внешний монитор и управлять им посредством обнаружения изменений в топологии довольно просто. Однако на деле ОС может потребоваться некоторое время для инициализации переключения между режимами, завершения настройки монитора и отображения содержимого. Учитывая использование кодировщика/декодера/D3D/OpenGL и всех сопутствующих компонентов, отладка этого процесса может быть довольно сложным делом. В примере кода при переключении между режимами повторно используется большая часть процедуры, однако более простым вариантом может быть завершение процесса и его повторная инициализация, так как если процесс добавления монитора занимает более 10 секунд, могут возникнуть различные проблемы — даже при подключении с помощью кабелей HDMI или VGA.

    Задачи на будущее

    Пример кода для этого технического документа написан для D3D9 и не включает поддержку D3D11. Пока трудно с точностью сказать, какой способ преобразования цветовой схемы NV12 в схему RGBA при отсутствии StretchRect или VideoProcessBlt является наиболее эффективным. Документ и пример кода будут обновлены после разрешения вопроса с использованием D3D11.

    Благодарности

    Выражаем благодарность Петеру Ларссону (Petter Larsson), Михелю Джеронимо (Michel Jeronimo), Томасу Итону (Thomas Eaton) и Петру Биалеки (Piotr Bialecki) за их помощь в создании этого документа.



     

    Intel, эмблема Intel и Xeon являются товарными знаками корпорации Intel в США и в других странах.
    *Прочие наименования и товарные знаки могут быть собственностью третьих лиц.
    © Корпорация Intel, 2013. Все права защищены.

  • Dual Screen
  • Intel WiDi
  • Miracast
  • WindowsCodeSample
  • texture sharing
  • Sviluppatori
  • Microsoft Windows* 8
  • Windows*
  • Intermedio
  • Intel® Media SDK
  • OpenGL*
  • URL
  • Area tema: 

    IDZone

    Использование стандартного GUI Unity* 3D в сочетании с ресурсами TouchScript

    $
    0
    0

    Линн Томпсон

    Download PDF

    Виджеты стандартного графического пользовательского интерфейса (GUI) Unity* 3D реагируют на касание так же, как на щелчок мыши c включенной функцией Windows* 8 «Перо и сенсорный ввод». В настоящее время для них невозможно настроить поддержку мультисенсорного ввода и жестов. В этой статье рассказывается о том, как TouchScript расширяет возможности стандартных объектов GUI с помощью функции Pan Gesture. Полученные элементы сохраняют внешний вид и функционал обычных виджетов интерфейса Unity 3D, но при этом поддерживают перетаскивание по экрану (функция Pan Gesture). В приведенном примере Unity 3D работает под управлением ОС Windows 8. Эта платформа обладает множеством средств для создания настраиваемых виджетов графического пользовательского интерфейса.

    Создание примера

    Пример начинается с создания нескольких сфер и кубов в поле обзора основной камеры сцены. Сцена проста и состоит из нескольких трехмерных объектов, которые можно изменять с помощью стандартных виджетов интерфейса Unity 3D. В основном интерфейс состоит из кнопок, горизонтальных ползунков и переключателей. После настройки каждого виджета мы располагаем в том же месте четырехугольник Unity 3D с аналогичными размерами. В настройках этого четырехугольника мы выбираем функцию TouchScript Pan Gesture, которая дает пользователям возможность перемещать данный объект. При перемещении четырехугольника его координаты присваиваются соответствующему виджету интерфейса Unity 3D. В результате мы получаем стандартный виджет интерфейса Unity 3D, который можно перемещать по экрану с помощью жестов TouchScript Pan Gesture. На рис. 1 показан пример такого интерфейса.

    Three Unity* 3D standard GUI widgets
    Рисунок 1. Три стандартных виджета графического интерфейса Unity* 3D

    Добавление стандартного виджета

    Для начала добавим три виджета графического интерфейса с помощью функции OnGUI. Первый виджет состоит из панели и нескольких кнопок, изменяющих масштаб примитивов на сцене. На втором виджете располагаются переключатели, которые присваивают геометрическим объектам фиксированные значения масштаба. Горизонтальные ползунки на третьем виджете вращают объекты на сцене по осям X, Y и Z. Расположим эти виджеты в левой, правой и центральной части верхней области экрана (эти объекты будут размещены с учетом разрешения 1024 x 768).

    Существует множество справочных материалов, посвященных настройке стандартных элементов графического интерфейса в Unity 3D. Исходный код этих виджетов можно найти в прилагаемом проекте Unity 3D.

    Настройка TouchScript

    В данном примере четырехугольники Unity 3D добавляются в качестве целей TouchScript, упрощающих сенсорное управление стандартными виджетами графического интерфейса. Эти примитивы добавляются не через редактор Unity 3D, а программно. Ниже приведен код для создания четырехугольника, перемещающего левый виджет с кнопками:

    Public Class:
    .
    .
    .
    private GameObject buttonQuad;//Создаем ресурс, обрабатывающий жесты
    //Объявляем переменные для обработки жестов, с помощью которых будет изменяться
    //стандартное положение GUI
    private Vector3 buttonQuadStartPosition;
    private float buttonQuadDeltaX;
    private float buttonQuadDeltaY;
    .
    .
    .
    Start Function:
    .
    .
    //Создаем ресурс, обрабатывающий жесты
    buttonQuad = GameObject.CreatePrimitive (PrimitiveType.Quad);
    
    //Приводим вектор положения ресурса в соответствие со стандартным расположением GUI
    buttonQuad.transform.position = new Vector3(-0.7f,2.25f,-10.0f);
    
    //Добавляем компоненты TouchScript, чтобы ресурс мог реагировать на сенсорные команды
    buttonQuad.AddComponent ("PanGesture");
    buttonQuad.AddComponent ("PanScript");
    
    //Задаем начальное положение для ресурса, обрабатывающего сенсорные команды
    buttonQuadStartPosition = buttonQuad.transform.position;
    //Инициализируем переменные изменения положения
    buttonQuadDeltaX = 0.0f;
    buttonQuadDeltaY = 0.0f;
    
    //Делаем ресурс для обработки сенсорных команд невидимым
    MeshRenderer buttonQuadRenderer = (MeshRenderer) buttonQuad.GetComponent ("MeshRenderer");
    buttonQuadRenderer.enabled = false;
    .
    .
    .
    Update function:
    .
    .
    //Задаем переменные смены положения. Значение 235 — фактор масштабирования
    //для разрешения 1024x768. В полноценном приложении этот фактор будет
    //зависеть от разрешения, установленного программой или пользователем.
    buttonQuadDeltaX = -235*(buttonQuadStartPosition.x - 	buttonQuad.transform.localPosition.x);
    buttonQuadDeltaY = 235*(buttonQuadStartPosition.y - buttonQuad.transform.localPosition.y);
    .
    .
    OnGUI function:
    .
    .
    ////////////////////// Меню с кнопками: начало ////////////////////////////////////
    //Создаем стандартное окно GUI, расположение которого будет зависеть от положения //ресурса, обрабатывающего команды сенсорного управления
    		GUI.Box(new Rect(10+buttonQuadDeltaX,10+buttonQuadDeltaY,240,160), "Button Menu");
    
    //Создаем стандартную кнопку, расположение которой будет зависеть от положения //ресурса, обрабатывающего команды сенсорного управления
    
    		if(GUI.Button(new Rect(20+buttonQuadDeltaX,40+buttonQuadDeltaY,220,20), "Increase Scale (4x Maximum)"))
    		{
    			//While increasing the cube scale, limit the cube scaling
    			//to be between 0.25 and 4
    
    			if (scale < 4.0)
    			{
    				scale += 0.1f;
    				cube01.transform.localScale += (new Vector3(0.1f,0.1f,0.1f));
    				cube02.transform.localScale += (new Vector3(0.1f,0.1f,0.1f));
    				sphere01.transform.localScale += (new Vector3(0.1f,0.1f,0.1f));
    				sphere02.transform.localScale += (new Vector3(0.1f,0.1f,0.1f));
    
    			}
    			if (scale == 4.0f)
    			{
    				maxscale = true;
    				minscale = false;
    				defaultscale = false;
    			}
    			else
    			{
    				maxscale = false;
    			}
    			if (scale == 0.25f)
    			{
    				minscale = true;
    				maxscale = false;
    				defaultscale = false;
    			}
    			else
    			{
    				minscale = false;
    			}
    			if (scale == 1.0f)
    			{
    				defaultscale = true;
    				maxscale = false;
    				minscale = false;
    			}
    			else
    			{
    				defaultscale = false;
    			}
    		}
    
    		if(GUI.Button(new Rect(20+buttonQuadDeltaX,80+buttonQuadDeltaY,220,20), "Decrease Scale (0.25x Minimum)"))
    		{
    			if (scale > 0.25)
    			{
    			//While decreasing the cube scale, limit the cube scaling
    			//to be between 0.25 and 4
    
    				scale -= 0.1f;
    
    				cube01.transform.localScale -= (new Vector3(0.1f,0.1f,0.1f));
    				cube02.transform.localScale -= (new Vector3(0.1f,0.1f,0.1f));
    				sphere01.transform.localScale -= (new Vector3(0.1f,0.1f,0.1f));
    				sphere02.transform.localScale -= (new Vector3(0.1f,0.1f,0.1f));
    			}
    			if (scale == 4.0f)
    			{
    				maxscale = true;
    				minscale = false;
    				defaultscale = false;
    			}
    			else
    			{
    				maxscale = false;
    			}
    			if (scale == 0.25f)
    			{
    				minscale = true;
    				maxscale = false;
    				defaultscale = false;
    			}
    			else
    			{
    				minscale = false;
    			}
    			if (scale == 1.0f)
    			{
    				defaultscale = true;
    				maxscale = false;
    				minscale = false;
    			}
    			else
    			{
    				defaultscale = false;
    			}
    		}
    
    		//Создаем кнопку для выхода из приложения
    		if(GUI.Button(new Rect(20+buttonQuadDeltaX,120+buttonQuadDeltaY,220,20), "Exit Application"))
    		{
    			Application.Quit();
    		}
    
    		GUI.Label (new Rect(20,180,220,20),scale.ToString());
    		////////////////////// Меню с кнопками: конец//////////////////////////////////
    .
    .
    .
    

    Сценарий PanScript программно добавляется к четырехугольникам и позволяет сдвигать или перетаскивать их. Работу этих функций можно увидеть в прилагаемом к данной статье примере или в примере под названием Everything, который поставляется вместе с пакетом TouchScript. Прилагаемое видео SGwTS.wmv демонстрирует работу виджетов интерфейса.

    Возможности усовершенствования

    Самым трудоемким процессом в создании этого примера является размещение четырех-угольника за виджетом GUI. Для этого приходится вручную рассчитывать точные значения x, y, и z и выравнивать положение четырехугольника, совмещая его со стандартным виджетом интерфейса Unity 3D. Кроме того, если пользователь установит разрешение экрана, отличающееся от 1024 x 768, это выравнивание окажется бесполезным. Более совершенным методом будет использование макетов интерфейса и автоматическое размещение четырехугольника с функцией TouchScript Pan Gesture, являющегося целью сенсорной команды.

    Ширина четырехугольника в прилагаемом примере совпадает с шириной стандартного виджета графического интерфейса Unity 3D, а высота несколько отличается от него в большую сторону. В результате над виджетом и под ним появляются «поля», с помощью которых пользователь может перемещать виджет по экрану. Передвинув точку сенсорного управления, можно изменить положение четырехугольника относительно стандартного виджета GUI Unity 3D. Например, габариты четырехугольника можно совместить с виджетом внизу и по бокам, тем самым переместив предполагаемую точку управления в верхнюю часть виджета.

    В приведенном примере пользователь может перемещать четырехугольник и связанный с ним виджет за любую точку (даже если она находится в габаритах виджета). Чтобы сделать активными только те области, которые выходят за пределы виджета, можно добавить еще один «блокирующий» четырехугольник. Размеры и положение этого четырехугольника должны совпадать с габаритами стандартного виджета графического интерфейса Unity 3D. Размещение блокирующего четырехугольника будет определяться другим четырехугольником, который изменяет положение стандартного виджета. Сама блокировка производится с помощью функции поведения TouchScript Untouchable. Такое поведения можно увидеть в примере Hit. Также это поможет избежать ошибки, при которой ползунок виджета двигется, когда передвигается горизонтальный ползунок.

    С помощью сочетания блокирующих и активных четырехугольников можно добиться перемещения настраиваемых виджетов. В совокупности эти два вида четырехугольников позволяют перемещать отдельные компоненты графического интерфейса без изменения позиции самого виджета. Например, пользователь сможет по отдельности независимо перемещать горизонтальные ползунки, находящиеся на одной неподвижной базе. Также с помощью настраива¬емой функции Pan Gesture можно ограничить перемещение компонентов виджета рамками самого элемента интерфейса.

    Порядок касания

    Напомним, что один из настроенных нами виджетов GUI позволяет масштабировать геометрические примитивы, расположенные на сцене. Левый куб и правую сферу можно свободно перемещать по сцене, так как они были настроены с помощью функции Pan Gesture. В то же время куб и сфера, расположенные в центре сцены, не связаны с TouchScript и не реагируют на сенсорное управление. Из-за этого масштабируемые примитивы могут закрыть собой четырехугольники, предназначенные для перемещения виджетов интер¬фейса. Если пользователь увеличит размер примитива, а затем перетащит на него виджет, следующая сенсорная команда в этой области экрана затронет не виджет, а примитив. Разумеется, можно использовать ту же команду-жест, чтобы вывести примитив из области виджета и снова сделать этот элемент интерфейса доступным для сенсорного управления.

    Тем не менее, если пользователь перетащит виджет на один из центральных примитивов, которые не поддерживают сенсорное управление, этот виджет будет заблокирован. Эту проблему можно решить, назначив через TouchScript примитиву поведение Untouchable с помощью кнопки Add Component («Добавить компонент») (см. рис. 2). Такая конфигурация позволит виджетам GUI, настроенным с помощью функции Pan Gesture, считывать сенсорные команды даже через геометрические примитивы. Эту схему можно наблюдать в прилагаемом видео: при перемещении виджета интерфейса на левый куб или правую сферу следующий жест передвигает соответствующий примитив. В то же время после переноса виджета на среднюю сферу (которой назначено поведение Untouchable) следующая команда перемещает сам виджет. Если из-за фактора масштабирования средний куб закроет собой не прошедшие рендеринг четырехугольники, перенесенный на этот куб виджет окажется заблокированным.

    Во всех случаях, когда один из ресурсов сцены может помешать элементу интерфейса, следует назначить этому элементу поведение Untouchable. Для шутеров от первого лица (FPS), в которых используются виджеты интерфейса, описанные в этой статье, следует настраивать в TouchScript поведение Untouchable для каждого ресурса, с которым может войти в контакт главная камера.

    Configuring a Unity* 3D scene asset to allow touch gestures
    Рисунок 2. Настройка сенсорного управления для объектов, находящихся за ресурсом Unity* 3D

    Последовательность рендеринга

    Видимые компоненты виджетов GUI, упоминающихся в этой статье, созданы с помощью встроенной функции Unity 3D OnGUI. Они будут отображаться всегда, и настраивать отдельную камеру для рендеринга отдельного слоя виджетов не требуется.

    Заключение

    Функции пакета TouchScript хорошо подходят для совместной работы со стандартными интерфейсными виджетами Unity 3D. Сочетание этих функций позволяет создавать традиционные элементы интерфейса, которые можно перемещать по экрану с помощью стандартного управления. При этом нет необходимости разрабатывать виджеты с нуля и создавать геометрические объекты для работы с жестами TouchScript. Полученный в результате код отличается стабильностью работы на платформе Unity 3D для Windows 8. Описанный метод идеально подходит для быстрой разработки стандартных виджетов графического интерфейса с поддержкой перетаскивания.

    Другие материалы по этой теме:

    Об авторе

    Линн Томпсон — специалист в области ИТ, более 20 лет проработавший в области компьютеризации предпринимательской и производственной сферы. Одной из первых его работ стало использование САПР для создания и редактирования чертежей контрольных приборов для энергосистем. Тогда же он получил степень бакалавра электротехники в Университете Небраски (г. Линкольн). В эпоху бума доткомов Линн занимался системным администрированием операционных систем, баз данных и приложений на различных платформах в одном из ИТ-интеграторов. Позже, после «краха доткомов», он участвовал во множестве проектов в роли ИТ-консультанта. Линн работал с компаниями, работающими в сфере легкой промышленности, а также нефтегазовой и оборонной индустрии. Сейчас он вновь вернулся к своей специальности и работает инженером-энергетиком. Линн получил магистерскую степень инженера со специализацией в области управления техническими системами (также в Университете Небраски).

    Intel, эмблема Intel и Xeon являются товарными знаками корпорации Intel в США и в других странах.
    *Прочие наименования и товарные знаки могут быть собственностью третьих лиц.
    © Корпорация Intel, 2013. Все права защищены.

  • multi touch
  • Unity 3D
  • TouchScript
  • Sviluppatori
  • Microsoft Windows* 8
  • Windows*
  • Unity
  • Intermedio
  • Interfacce touchscreen
  • URL
  • Area tema: 

    IDZone

    Реализация последовательностей жестов в Unity* 3D с помощью библиотеки TouchScript

    $
    0
    0

    Download PDF

    Линн Томпсон

    Если вы настраиваете цели касания, которые управляют элементами на сцене, важно уменьшить область управления, насколько это возможно. Так вы сможете максимально расширить область экрана на устройстве Ultrabook™, предназначенную для отображения привлекательного контента. Для этого можно настроить цели касания так, чтобы они обрабатывали различные комбинации жестов. Таким образом, количество целей касания на экране сократится до минимума. Например, два элемента интерфейса, один из которых заставляет пушку стрелять, а второй — вращаться, можно заменить на один, позволяющий выполнять оба действия одним непрерывным касанием.

    В этой статье я расскажу о том, как настроить сцену для управления контроллером от первого лица при помощи целей касания. Прежде всего необходимо настроить цели касания для базовой позиции контроллера и вращения, а затем расширить набор их функций. Послед¬него можно достичь за счет существующих элементов интерфейса, не добавляя новые объекты. Сцена, которая у нас получится, продемонстрирует широкие возможности Unity 3D в ОС Windows* 8 как платформы для обработки различных последовательностей жестов.

    Настройка сцены в Unity* 3D

    Для начала необходимо настроить сцену. Для этого импортируем в Unity* 3D ресурс ландшафта в формате .fbx с горами и деревьями, экспортированный из Autodesk 3D Studio Max*. Поместим контроллер в центре ландшафта.

    Установим показатель глубины основной камеры (она входит в состав контроллера) на уровень -1. Создадим отдельный элемент интерфейса камеры с поддержкой ортогональной проекции, шириной 1 и высотой 0,5, а также флагами Don’t Clear. Затем создадим слой GUIWidget и сделаем его маской интерфейса камеры.

    Расположим основные элементы интерфейса, управляющие контроллером, на сцене в поле обзора ортогональной камеры. Добавим сферу для каждого пальца левой руки. Сфера мизинца заставляет контроллер двигаться влево, сфера безымянного пальца — вперед, среднего пальца — вправо, а указательного пальца — назад. Сфера большого пальца позво-ляет прыгать и запускать сферические снаряды под углом 30 градусов по часовой стрелке.

    Для элемента интерфейса правой руки создадим куб (квадрат в ортогональной проекции). Настроим для этого куба поддержку жеста сдвига и привяжем его к скрипту MouseLook.cs. Этот элемент интерфейса обеспечивает такие же возможности, как и сенсорная панель устройства Ultrabook.

    Эти элементы интерфейса расположим вне поля обзора основной камеры, а в качестве слоя установим GUIWidget. На рис. 1 можно увидеть, как элементы интерфейса позволяют запускать снаряды и управлять позицией контроллера на сцене.


    Рисунок 1. Сцена контроллера от первого лица с ландшафтом и запущенными сферическими снарядами.

    На этой сцене снаряды, запущенные из контроллера, пролетают сквозь деревья. Чтобы это исправить, необходимо добавить сетку или коллайдер к каждому дереву. Другая проблема на этой сцене — низкая скорость движения вперед — возникает при попытке посмотреть вниз с помощью сенсорной панели одновременно с движением вперед с помощью сферы безымянного пальца. Чтобы устранить эту неполадку, можно ограничить угол обзора при взгляде вниз, когда удерживается кнопка движения вперед.

    Множественные касания

    На базовой сцене находится контроллер от первого лица, который запускает снаряды под определенным углом по направлению от центра (см. Рисунок 1). По умолчанию установлен угол в 30 градусов по часовой стрелке.

    Настроим сцену для поддержки множественных касаний, выполняемых чаще, чем установленный период, изменим угол запуска снарядов и попробуем запустить снаряд. В этом случае можно настроить угол на возрастание в геометрической прогрессии в зависимости от числа касаний при помощи переменных типа float в скрипте для сферы большого пальца слева. Эти переменные регулируют угол и время с момента запуска последнего снаряда:

    	private float timeSinceFire = 0.0f;
    	private float firingAngle = 30.0f;

    Далее настроим цикл Update в скрипте для сферы большого пальца так, чтобы угол запуска снарядов снижался, если касания сферы большого пальца выполняются чаще, чем раз в полсекунды. В том случае, если касания последуют реже, чем раз в полсекунды, или угол запуска снарядов снизится до 0 градусов, величина угла запуска снарядов вернется к показателю 30 градусов. Получится следующий код:

    		timeSinceFire += Time.deltaTime;
    
    			if(timeSinceFire <= 0.5f)
    			{
    				firingAngle += -1.0f;
    
    			}
    			else
    			{
    				firingAngle = 30.0f;
    			}
    
    			timeSinceFire = 0.0f;
    
    			if(firingAngle <= 0)
    			{
    				firingAngle = 30;
    			}
    
    
    			projectileSpawnRotation = Quaternion.AngleAxis(firingAngle,CH.transform.up);

    Такой код произведет эффект обстрела, при котором непрерывные касания приведут к запуску снарядов под постоянно уменьшающимся углом (см. рис. 2). Этот эффект можно позволить настраивать пользователям либо сделать доступным при соблюдении определенных условий в игре или режиме симуляции.


    Рисунок 2. Непрерывные касания приводят к изменению направления запуска снарядов.

    Масштабирование прокруткой

    Мы настроили квадрат в правой нижней части экрана на рис. 1 на работу в режиме, аналогичном сенсорной панели на клавиатуре. При жесте сдвига квадрат не двигается, а поворачивает основную камеру сцены вверх, вниз, влево и вправо с помощью скрипта контроллера MouseLook. Аналогичным образом жест масштабирования (схожий со растягиванием/сжатием на других платформах) приводит не к масштабированию квадрата, а к изменению поля зрения основной камеры, благодаря которому пользователь может приблизить или отдалить объект на основной камере (см. Рисунок 3). Настроим контроллер таким образом, чтобы жест сдвига сразу после масштабирования возвращал поле зрения камеры к значению по умолчанию 60 градусов.

    Для этого нужно запрограммировать логическую переменную (panned) и переменную типа float, чтобы они отмечали время, прошедшее от последнего жеста масштабирования:

    	private float timeSinceScale;
    	private float timeSincePan;
    	private bool panned;

    Установим для переменной timeSinceScale значение 0.0f при выполнении жеста масштабирования, а для переменной panned — значение True при выполнении жеста сдвига. Поле зрения основной камеры сцены настраивается в цикле Update, как можно увидеть в скрипте для прямоугольника-сенсорной панели:

    		timeSinceScale += Time.deltaTime;
    		timeSincePan += Time.deltaTime;
    
    		if(panned && timeSinceScale >= 0.5f && timeSincePan >= 0.5f)
    		{
    			fieldOfView += 5.0f;
    			panned = false;
    		}
    
    		if(panned && timeSinceScale <= 0.5f)
    		{
    			fieldOfView = 60.0f;
    			panned = false;
    		}
    
    		Camera.main.fieldOfView = fieldOfView;

    Установим для переменной timeSinceScale значение 0.0f при выполнении жеста масштабирования, а для переменной panned — значение True при выполнении жеста сдвига. Поле зрения основной камеры сцены настраивается в цикле Update, как можно увидеть в скрипте для прямоугольника-сенсорной панели:

    	private void onPanStateChanged(object sender, GestureStateChangeEventArgs e)
        {
            switch (e.State)
            {
                case Gesture.GestureState.Began:
                case Gesture.GestureState.Changed:
                    var target = sender as PanGesture;
                    Debug.DrawRay(transform.position, target.WorldTransformPlane.normal);
                    Debug.DrawRay(transform.position, target.WorldDeltaPosition.normalized);
    
                    var local = new Vector3(transform.InverseTransformDirection(target.WorldDeltaPosition).x, transform.InverseTransformDirection(target.WorldDeltaPosition).y, 0);
                    targetPan += transform.InverseTransformDirection(transform.TransformDirection(local));
    
                    //if (transform.InverseTransformDirection(transform.parent.TransformDirection(targetPan - startPos)).y < 0) targetPan = startPos;
                    timeSincePan = 0.0f;
    				panned = true;
    				break;
    
            }
    
        }
    
    	private void onScaleStateChanged(object sender, GestureStateChangeEventArgs e)
        {
            switch (e.State)
            {
                case Gesture.GestureState.Began:
                case Gesture.GestureState.Changed:
                    var gesture = (ScaleGesture)sender;
    
                    if (Math.Abs(gesture.LocalDeltaScale) > 0.01 )
                    {
    					fieldOfView *= gesture.LocalDeltaScale;
    
    					if(fieldOfView >= 170){fieldOfView = 170;}
    					if(fieldOfView <= 1){fieldOfView = 1;}
    
    					timeSinceScale = 0.0f;
    
    
                    }
                    break;
            }
        }


    Рисунок 3. Основная камера сцены с изображением, приближенным при помощи прямоугольника сенсорной панели справа

    Нажатие, отпускание с щелчком

    Если нажать и отпустить сферу мизинца, а затем в течение полсекунды провести по ней, можно увеличить горизонтальную скорость контроллера.

    Для поддержки этой функции добавим переменную типа float и логическую переменную, которые позволят отмечать время с жестов отпускания сферы мизинца и жеста щелчка по ней:

    	private float timeSinceRelease;
    	private bool flicked;

    При первоначальной установке сцены я предоставил скрипту сферы мизинца доступ к скрипту контроллера InputController, чтобы сфера мизинца слева могла заставлять контроллер двигаться влево. Переменная, управляющая горизонтальной скоростью контроллера, находится не в скрипте InputController, а в скрипте CharacterMotor. Передать скрипт сферы левого мизинца скрипту CharacterMotor можно аналогичным образом:

    		CH = GameObject.Find("First Person Controller");
    		CHFPSInputController = (FPSInputController)CH.GetComponent("FPSInputController");
    		CHCharacterMotor = (CharacterMotor)CH.GetComponent ("CharacterMotor");

    Функция onFlick в нашем скрипте лишь позволяет установить для логической переменной flicked значение, равное True.

    Функция Update в скрипте вызывается один раз за кадр и изменяет движение контроллера по горизонтали следующим образом:

    		if(flicked && timeSinceRelease <= 0.5f)
    		{
    			CHCharacterMotor.movement.maxSidewaysSpeed += 2.0f;
    			flicked = false;
    		}
    
    		timeSinceRelease += Time.deltaTime;
    	}

    Благодаря этому коду можно увеличивать скорость движения по горизонтали. Для этого нужно нажать и отпустить сферу мизинца, а затем провести по ней в течение полсекунды. Настроить замедление движения по горизонтали можно различными способами. Например, для этого можно использовать нажатие и отпускание сферы указательного пальца, а затем щелчок по ней. Обратите внимание на то, что способ CHCharacterMotor.movement содержит не только параметр maxSidewaysSpeed, но также gravity, maxForwardsSpeed, maxBackwardsSpeed, и другие. Использование разнообразных жестов библиотеки TouchScript и объектов, которые обрабатывают жесты, в сочетании с этими параметрами обеспечивает широкие возможности и различные стратегии разработки сенсорных интерфейсов в сценах Unity 3D. При создании сенсорных интерфейсов для таких приложений можно пробовать различные варианты и выбирать наиболее эффективные и эргономичные.

    Проблемы с последовательностями жестов

    Последовательности жестов, которые мы использовали в этой статье, существенно зависят от функции Time.deltaTime. Я применяю эту функцию в сочетании с разными жестами до и после того, как функция определит действие. Две основные проблемы, с которыми я столкнулся при настройке этих случаев, заключаются в величине временного интервала и характере жестов.

    Временной интервал

    При написании этой статьи я использовал интервал в полсекунды. Если я выбирал интервал равный одной десятой секунды, устройство не могло распознать последовательности жестов. Хотя мне казалось, что темп касаний был достаточно высок, это не приводило к нужным действиям на экране. Возможно, это связано с задержками в работе устройства и ПО, поэтому рекомендую при разработке последовательностей жестов учитывать производительность целевой платформы.

    Жесты

    При работе над этим примером я изначально собирался использовать жесты масштаби-рования и сдвига, а затем касания и щелчка. Масштабирование и сдвиг работали правильно, но перестали, как только я добавил жест касания. Хотя мне удалось настроить последовательности из жестов масштабирования и сдвига, она не очень удобна для пользователя. Более удачным вариантом будет настроить другую цель касания в элементе интерфейса на обработку жестов касания и проведения после масштабирования и сдвига.

    В этом примере я использую интервал времени в полсекунды, чтобы определять, выпол-нено действие или нет. Также можно настроить несколько временных интервалов, хотя это и приведет к усложнению интерфейса. Например, последовательность жестов нажатия и отпускания и следующего в течение полсекунды за ними проведения может увеличивать скорость движения по горизонтали, а аналогичная последовательность с интервалом от полсекунды до секунды — снижать скорость. Используя временные интервалы таким образом, можно не только более гибко настроить пользовательский интерфейс, но и добавить на сцену скрытые секреты.

    Заключение

    В этой статье я настроил сцену с различными последовательностями жестов в Unity* 3D с помощью библиотеки TouchScript на устройстве Ultrabook с ОС Windows 8. Цель реализа-ции этих последовательностей — сократить область экрана, с помощью которой пользова-тель управляет приложением. В этом случае можно выделить большую площадь экрана для показа привлекательного контента.

    В тех случаях, когда последовательности жестов не работали правильно, нам удавалось найти подходящее альтернативное решение. Одной из задач настройки было добиться правильной работы последовательности действий с помощью функции Time.deltaTime на имеющемся устройстве. Таким образом, сцена, которую мы создали в Unity 3D для этой статьи, подтверждает жизнеспособность ОС Windows 8 на устройствах Ultrabook как платформы для разработки приложений с использованием последовательностей жестов.

    Другие материалы по данной теме

    Об авторе

    Линн Томпсон — специалист в области ИТ, более 20 лет проработавший в области компьютеризации предпринимательской и производственной сферы. Одной из первых его работ стало использование САПР для создания и редактирования чертежей контрольных приборов для энергосистем. Тогда же он получил степень бакалавра электротехники в Университете Небраски (г. Линкольн). В эпоху бума доткомов Линн занимался системным администрированием операционных систем, баз данных и приложений на различных платформах в одном из ИТ-интеграторов. Позже, после «краха доткомов», он участвовал во множестве проектов в роли ИТ-консультанта. Линн сотрудничал с компаниями, работающими в легкой промышленности, а также нефтегазовой и оборонной индустрии. Сейчас он вернулся к своей специальности и работает инженером-энергетиком. Линн получил магистерскую степень инженера со специализацией в области управления техническими системами (также в Университете Небраски).



     

    Intel, эмблема Intel, Ultrabook и VTune являются товарными знаками корпорации Intel в США и в других странах.
    *Прочие наименования и товарные знаки могут быть собственностью третьих лиц
    © Корпорация Intel, 2014. Все права защищены.

  • Sviluppatori
  • Microsoft Windows* 8
  • Windows*
  • Unity
  • Intermedio
  • Computing percettivo
  • Sviluppo giochi
  • Interfacce touchscreen
  • Laptop
  • Tablet
  • URL
  • Area tema: 

    IDZone

    Оптимизация игр для Ultrabook™

    $
    0
    0

    Download as PDF

    Автор: Ли Бэмбер (Lee Bamber)

    1. Введение

    Недавно я занимался подготовкой игрового движка, над которым я работал для конференции Games Developer Conference. Учитывая значимость этого мероприятия, было важно, чтобы игра достаточно быстро работала на трех устройствах, которые были у меня под рукой: от современного Ultrabook™до системы на два поколения старше.

    В этой статье вы узнаете, как увеличить скорость трехмерной игры, и поймете, на что нужно обращать внимание при переносе своих приложений на Ultrabook. Будь вы опытным разработчиком игр, или же программирование для вас просто хобби — в любом случае вы наверняка понимаете важность высокой производительности. Игра, идущая плавно и с высокой кадровой скоростью, будет восприниматься как намного более качественная и профессиональная, нежели игра, спотыкающаяся на несчастных пяти кадрах в секунду. Никакая сколь угодно захватывающая графика не скроет тот факт, что игра просто тормозит, дергается на экране (из-за постоянного рассогласования с вертикальной разверткой монитора), а о сколько-нибудь приемлемой реализации физики и говорить нечего. В этом примере с настоящим игровым проектом я постараюсь рассказать о возможных проблемах при переносе игры на разные платформы и способах решения таких проблем.


    Рисунок 1. Если у вашей игры красивые снимки экрана, это поможет поднять продажи, но за низкую кадровую скорость расплачиваться придется уже вам!

    В этой статье описывается несколько распространенных причин потери производительности. Разработчикам игр предлагается полезная информация по переносу высококачественных трехмерных игр высшего уровня на Ultrabook с нужным уровнем производительности. Для работы таких игр с комфортной скоростью зачастую требуется мощный дискретный видеоадаптер, а нагрузка на GPU весьма высока. Здесь может пригодиться понимание архитектурных различий между выделенными и интегрированными GPU, но лучший способ повышения производитель¬ности графической подсистемы — анализ конвейера обработки графики для выявления узких мест с дальнейшей оптимизацией этих областей без снижения качества изображения.

    Требуется базовое понимание вызовов графических API в целом, знание компонентов, образую¬щих типичные трехмерные игры, а также некоторое знание или опыт использования Ultrabook.

    2. Почему важна производительность?

    Число игроков на рынке приложений и игр постоянно растет, поэтому уникальные полезные особенности ваших продуктов становятся все более важными для коммерческого успеха, а хорошая производительность сейчас рассматривается не как некий желаемый результат, а как строго необходимый атрибут любой программы или игры. Современные пользователи даже не будут считать вашу игру законченной, если она не будет работать достаточно гладко и комфортно на их устройстве, и не будут возвращаться к игре, если с самого начала о ней сложится отрицательное впечатление.

    Это обстоятельство крайне важно. Если же учесть еще и быстрый рост рынка мобильных телефонов, планшетов и ноутбуков, окажется, что производительность имеет первостепенное значение. Вы можете удовольствоваться адаптацией игры к Ultrabook, учитывая высокую вычислительную мощность этих устройств по сравнению с остальными, но пользователи всегда будут требовать высших стандартов и ожидать максимального удобства.


    Рисунок 2. Ultrabook раскрывает немалую мощь в умелых руках.

    С точки зрения выработки полезных навыков все, что вы сейчас можете сделать для оптимиза¬ции и улучшения кода игры, вы сможете применять и во всех дальнейших проектах, повысив свою квалификацию разработчика.

    3. Зачем оптимизировать?

    Многие разработчики используют для создания и тестирования трехмерных игр настольные ПК. Из-за наличия выделенного графического адаптера иногда возникает ощущение безграничности вычислительных ресурсов, а это приводит к появлению в коде игр таких алгоритмов и шейдеров, которые работают на самом пределе возможностей GPU. Если же запустить такую игру на менее мощной платформе, она может работать гораздо медленнее. Ultrabook — это исключительно мощные мобильные устройства, но по «грубой силе» обработки графики они все же немало уступают мощным современным графическим процессорам. Кроме того, Ultrabook предназначены для мобильного использования, поэтому может оказаться, что в процессе игры Ultrabook будет работать от аккумулятора: конвейер отрисовки должен быть очень эффективным, чтобы избежать быстрого израсходования всей электроэнергии. Все эти факты необходимо учитывать при создании игровой графики.


    Рисунок 3. Варианты использования успешного приложения.

    При разработке приложений программисты обычно двигаются «сверху вниз»: сначала создают приложение, а потом стараются адаптировать его для как можно большего количества устройств в рамках отведенного на разработку времени.

    Простейший подход — разрабатывать игру на Ultrabook, а затем переносить ее на настольный компьютер с выделенным графическим адаптером: при этом для переноса игры не требуется практически никаких действий. Тем не менее, вашими конкурентами могут стать игры, для которых планка качества установлена гораздо выше. Преимущество у такого подхода только одно: вы с самого начала учитываете время работы системы от аккумулятора и с большей вероятностью разработаете игру, которая будет снижать потребление ресурсов в определенные моменты, например во время заставок или на экранах настроек. Более распространенный подход — разработка на настольном ПК с последующей оптимизацией для Ultrabook: в этом случае, как правило, достигается более высокое качество, поскольку изначально концепция разработки нацелена именно на это.

    4. С настольного компьютера на Ultrabook: пример битвы за производительность.

    Мой рассказ начинается за много недель до крупного мероприятия — конференции GDC. Моя игра работает на достаточно современном графическом адаптере стоимостью около двухсот долларов с интерфейсом PCI Express* 3.0. При наивысшем качестве графики моя игра выдавала порядка 60 кадров в секунду. Это был вовсе не сверхмощный игровой компьютер, но я мог запускать любые трехмерные игры с самым высоким качеством графики без сколько-нибудь ощутимых проблем с производительностью. В моем распоряжении было шесть ядер, 6 гигабайт системной памяти и массив крайне быстрых твердотельных дисков. Я знал, что на конфе¬ренции в моем распоряжении не будет настольных компьютеров, и не собирался везти с собой через полмира здоровенный стационарный компьютер. Следующим по мощности устройством был мой Ultrabook, который вполне годился для поездки: именно его я и решил взять с собой.


    Рисунок 4. GDC 2014 — одна из крупнейших конференций разработчиков.

    Мой Ultrabook оснащен процессором Intel® Core™ 4-го поколения с графикой Intel® HD Graphics 4000™: это мое любимое устройство, когда я не на работе. Результаты первого теста оказались, прямо скажем, катастрофическими: кадровая скорость упала настолько, что вообще вся затея начала казаться мне чересчур смелой. Используемая сборка трехмерного игрового движка широко использовала шейдеры и отрисовку множества объектов одновременно. Игра просто глотала циклы CPU, как конфетки, стараясь дотянуться до всех доступных ресурсов. Разумеется, с таким подходом моей игре было крайне далеко до экономных и дружественных приложений, подходящих мобильным устройствам.

    Несмотря на очевидную наглость моего плана, я все же знал, что современные Ultrabook — это вполне мощные игровые системы, при правильном подходе они не отстают от настольных компьютеров по производительности, существенно опережая их в удобстве. Кроме того, мне приходилось играть во множество игр на Ultrabook, поэтому я знал, что моя задача вполне выполнима: я решил добиться от игры 60 кадров в секунду.

    Написанием кодов я занимаюсь очень давно: я научился программировать задолго до появле-ния анализаторов производительности и графических отладчиков, поэтому основной способ обнаружения узких мест состоял в том, чтобы удалять огромные фрагменты движка до тех пор, пока производительность не повысилась бы. Затем, возвращая по очереди важные фрагменты кода обратно в игру, я мог определить, какие части движка работали медленнее всего. После определения узких мест (а просто взять и удалить их было невозможно) начинался осторожный процесс снижения ресурсоемкости компонентов. Примеры такого подхода: исключение обычного расчета карты в шейдерах для пикселей за пределом определенного расстояния от игрока; пропуск вызовов обновления искусственного интеллекта в каждом втором цикле, чтобы снизить издержки на эти процессы. Это незначительные улучшения, но в сумме они дают весомый эффект, и уже довольно скоро игровой движок стал работать намного быстрее практически без потерь в качестве изображения.

    Программистам, для которых отладка производительности является относительно новой областью, я искренне рекомендую не прибегать к такому способу обнаружения узких мест. Можно исполь¬зовать множество инструментов, помогающих выявлять проблемы производитель¬ности вашего приложения, причем эти средства не только выявляют узкие места, но и указывают на природу проблемы. Один из таких бесплатных инструментов — пакет Intel® Graphics Performance Analyzers. Это решение профилирует ваше приложения в ходе его работы и предоставляет снимок всей деятельности программы: что именно она делает и сколько времени это занимает. При демонстрации игры на конференции я обнаружил несколько проблем, которые я впослед¬ствии исправил, чтобы повысить производительность и плавность игры.


    Рисунок 5. До и после: снимки экрана игры до и после оптимизации.

    Как видно на рисунке 5, мне удалось повысить скорость с 20 до 62 кадров в секунду при крайне незначительных различиях в качестве графики. На снимке экрана «после» удалено мощное динамическое освещение вокруг игрока, а также применен менее агрессивный шейдер фрагментов.

    «Голодные» шейдеры

    Мы быстро определили, что наибольшее снижение производительности было на этапе отрисовки графики.


    Рисунок 6. Панель метрики производительности из начальной версии с низкой кадровой скоростью.

    Как видно на рисунке 6, горизонтальная строка, отмеченная как «Отрисовка», потребляла большую часть доступных циклов. При более подробном анализе выяснилось, что крайне много ресурсов расходовалось на отрисовку объектов на экране. После этого стало понятно, что сцена, состоящая из сотен тысяч полигонов (причем для каждого используется ресурсо-емкий шейдер фрагментов), резко снижает производительность. Но насколько именно? Добавив к шейдерам параметры MEDIUM и LOWEST, а также несколько ограничив «аппетит» отрисовки пикселей, нам удалось добиться шестикратного повышения производительности.

    Чтобы определить, как на самом деле работают параметры LOWEST и MEDIUM, сначала нужно было определить «наименьший общий знаменатель» для компонентов игры. Определив, какие компоненты для игры совершенно необходимы, и убрав все остальное, я создал в шейдере новый параметр LOWEST. Были удалены почти все элементы: все тени, обычные карты, динамическое освещение, перекрытие текстур, зеркальное отображение и т. п. Поскольку я «обрубил все под корень», можно было запустить игру и понять, какой производительности можно добиться на Ultrabook в наилучшем для этого шейдера случае. Сравнив снимки экрана с параметром HIGHEST и с параметром LOWEST, я обнаружил самый важный отсутствующий компонент, который вызвал бы отрицательную реакцию пользователей при снижении качества графики. Шейдер содержал тени и перекрытия текстур. При отсутствии каждого из этих элементов качество изображения резко снижалось. Вернуть перекрытие текстур можно было без особых затрат. Чтобы протестировать, насколько больше ресурсов будет потреблять игра, я просто вернул код шейдера для этого элемента и снова запустил игру. С тенями все было гораздо сложнее: это касалось и их создания в другой части игрового движка, и их использования в самом шейдере. Учитывая важность этого аспекта для сохранения высокого качества изображения, я потратил достаточное количество времени на изучение различных подходов и наконец, обнаружил достаточно быстрое решение, которое я описываю ниже.

    Создать параметр MEDIUM для шейдера было довольно просто: нужно было написать шейдер, промежуточный по качеству между самым высоким и самым низким качеством графики, но всегда склоняясь в пользу производительности. Цель этого параметра — достижение всех преимуществ по скорости, присущих параметру LOWEST, но с добавлением наименее ресурсоемких эффектов, таких как фонарик игрока, динамическое освещение и чуть более высокое качество теней.

    Если бы я просто снизил качество всех графических элементов до минимума в режиме LOWEST, мне бы за один прием удалось добиться наибольшей производительности, но игроки относятся к плохой графике столь же отрицательно, как к плохой производительности. Я постарался сохранить 90 % качества изображения на самых высоких настройках и выделить элементы, которые можно было бы исключить или ограничить. Так мне удалось добиться значительного повышения скорости с минимальными потерями качества. С 5 кадров в секунду мне удалось перешагнуть за 40 — неплохое достижение.

    Чтобы узнать, почему ваша игра для настольного ПК так медленно работает на Ultrabook, я настоятельно рекомендую разложить по полочкам весь ваш конвейер отрисовки графики и постараться понять, на что тратится время. Для этого можно использовать мой «хирурги-ческий» метод и удалять целые уровни функциональности до тех пор, пока не повысится скорость, или же применить более современный подход и задействовать средства анализа производительности. Какой бы метод вы ни выбрали, после обнаружения проблемы следующая задача — придумать такое решение, при котором возрастает скорость работы, но не снижается качество изображения.

    Вот некоторые методики, которые я применил для устранения обнаруженных узких мест производительности.

    Тени без затрат

    Чтобы решить упомянутую выше проблему с тенями, мне пришлось найти альтернативные решения методики так называемых «каскадных карт теней». Я не стану подробно описывать эту методику, но дополнительные сведения о ней вы найдете здесь: http://msdn.microsoft.com/en-gb/library/windows/desktop/ee416307(v=vs.85).aspx. Работает она примерно так: в поле зрения камеры игрока немедленно рисуются четыре цели отрисовки с тенями всех объектов, каждая с разным уровнем детализации.


    Рисунок 7. Каскадные карты теней — представление отладчика игрового движка.

    Затем шейдер получает инструкции изменить цвет того или иного пикселя на экране на основании того, попадает ли этот пиксель в область предварительно вычисленной тени. Проблема в том, что это очень ресурсоемкий эффект шейдера, потребляющий много видеопамяти. Ниже приведен код шейдера фрагментов. Обратите внимание, что несколько раз используется ветвление IF, а производительность некоторых графических процессоров ощутимо падает для каждой новой ветви IF. В крайних случаях некоторые системы вычисляют все изменения каждого выходного пикселя, то есть ветвление кода не дает вообще никаких преимуществ.

    fPercentLit = 0.0f;
    if ( iCurrentCascadeIndex==0 )
    {
    fPercentLit += vShadowTexCoord.z > tex2D(DepthMap1,float2(vShadowTexCoord.x,vShadowTexCoord.y)).x ? 1.0f : 0.0f;
    }
    else
    {
    	if ( iCurrentCascadeIndex==1 )
    	{
    		fPercentLit += vShadowTexCoord.z > tex2D(DepthMap2,float2(vShadowTexCoord.x,vShadowTexCoord.y)).x ? 1.0f : 0.0f;
    	}
    	else
    	{
    		if ( iCurrentCascadeIndex==2 )
    		{
    			fPercentLit += vShadowTexCoord.z > tex2D(DepthMap3,float2(vShadowTexCoord.x,vShadowTexCoord.y)).x ? 1.0f : 0.0f;
    		}
    		else
    		{
    			if ( iCurrentCascadeIndex==3 && vShadowTexCoord.z<1.0 )
    			{
    				fPercentLit += vShadowTexCoord.z > tex2D(DepthMap4,float2(vShadowTexCoord.x,vShadowTexCoord.y)).x ? 1.0f : 0.0f;
    			}
    		}
    	}
    }

    Необходимо снизить нагрузку на видеопамять и зависимость от ветвей IF. Решение (одно из возможных) — создать единую очень большую текстуру теней и поместить в эту цель отрисовки результаты самого низкого уровня детализации.

    Я написал новую, менее ресурсоемкую методику, которая просто считывала данные из этой большой текстуры без всяких ветвлений. Особенности такого подхода выходят за рамки этой статьи, но общий смысл в том, что сначала нужно выявить причину снижения производительности, а затем придумать такое решение, которое работало бы быстрее, но давало бы изображение такого же качества.

    Поддержание качества изображения

    При оптимизации игрового движка необходимо следить за сохранением качества изображения на всех этапах разработки игры. Нетрудно просто вырезать все красивые, но ресурсоемкие эффекты ради прироста производительности, но лучше рассматривать каждую проблему как возможность повышения производительности с сохранением требуемого качества картинки. При этом вы не только добьетесь желаемых результатов, но и игра будет еще лучше работать на мощных компьютерах, что дает вам возможность добавлять новые компоненты и элементы при дальнейшем развитии игры.


    Рисунок 8. Сравнение игровой сцены при чрезмерном снижении качества изображения.

    Разрабатывая игру на настольном ПК, вы наверняка захотите использовать сложные шейдеры фрагментов для создания разнообразных эффектов поверхностей. Если просто удалить их из игры, изображение ухудшится настолько, что станет совсем не похоже на исходное. Для сохранения целостности игры важно поддерживать однородный визуальный стиль для всех методик работы шейдеров. Новые пользователи могут сначала впечатлиться великолепным снимком экрана в интернет-обзоре игры, но будут разочарованы, когда запустят вашу игру и увидят на экране что-то совсем иное.

    Во всех возможных случаях старайтесь применять методики, воспроизводящие эффекты ресурсоемких шейдеров с меньшими затратами. Например, можно использовать заранее наложенные текстуры или применять ресурсоемкие пиксельные эффекты только в самой близкой к игроку области.

    Уделяйте больше внимания своим близким.

    Звучит как хороший жизненный совет, но это еще и неплохая стратегия для оптимизации шейдеров на Ultrabook. Одной инструкции ветвления IF достаточно, чтобы определить, насколько близко к игроку находится вычисляемый пиксель. Если близко, то можно, как и ранее, использовать ресурсоемкий эффект пиксельного шейдера, но если далеко, можно использовать намного менее затратную имитацию или заранее просчитанные эффекты.


    Рисунок 9. Эффект смешения в действии: обратите внимание на эффекты карты нормалей вблизи.

    Вместе с описанной выше методикой также можно использовать смешение, а если добавить одну дополнительную ветвь IF, можно проверять, на каком расстоянии между двумя точками удаления от игрока находится каждый пиксель. Вблизи игрока (ближе первой точки) можно использовать ресурсоемкие эффекты, а за пределами второй точки можно применять эффекты попроще. Между первой и второй точками следует вычислять смешанный эффект, промежуточный между первым и вторым подходами. Важно, чтобы расстояние между этими двумя точками было сравнительно небольшим, чтобы избежать удвоенного расхода вычислительных ресурсов. Расстояние смешения должно быть настолько большим, чтобы переход остался не замеченным игроком. В приведенном ниже фрагменте кода каждый пиксель обрабатывается в зависимости от его расстояния от камеры обзора: если расстояние составляет от 400 до 600 единиц, вычисляются обе ветви кода.

    float4 lighting = float4(0,0,0,0);
    float4 viewspacePos = mul(IN.WPos, View);
    if ( viewspacePos.z < 600.0f )
    {
    	// work out surface normal per pixel
    	lighting = lit(pow(0.5*(dot(Ln,Nb))+0.5,2),dot(Hn,Nb),24);
    }
    if ( viewspacePos.z > 400.0f )
    {
    	// cheapest directional lighting
    	lighting = lerp ( lighting, cheaplighting, min((viewspacePos.z-400.0f)/200.0f,1.0f) );
    }

    Результат получается на удивление хороший, а переход очень плавный и совершенно незаметный при отрисовке. При этом в 90 % сцены теперь используется весьма экономный с точки зрения нагрузки эффект, поэтому скорость игры значительно повышается.

    Обработка на лету и предварительная обработка

    На оптимизацию игры было затрачено немало времени и усилий, но все равно скорость пока еще отставала от заветных 60 кадров в секунду. Баланс между качеством изображения и возможным повышением производительности был достигнут, но другие части игрового движка, помимо системы шейдеров, образовывали немалый объем вычислительных издержек и снижали скорость игры.

    В игровом движке была внутренняя система оценки производительности, которая грубо измеряла каждый крупный сегмент всего конвейера отрисовки. В дополнение к графике, движок также измеряет ресурсы, затрачиваемые на вычисление искусственного интеллекта, физики, оружия, отладки, объемного света и т. п. Один из счетчиков следил за отрисовкой травы в реальном времени: такая методика использовалась в игре для формирования иллюзии бесконечного травяного поля. Снизив ресурсоемкость обработки графики, мы обнаружили, что относительная ресурсоемкость процесса отрисовки травы резко возросла и стала следующей по величине во всем конвейере. При оптимизации нужно всегда следить за такими пиками, а если обнаружится, что они используют слишком много игровых циклов, нужно повнимательнее их изучить. Следует знать, какой уровень потребления ресурсов для того или иного компонента графики является разумным, а какой — явно чрезмерным. В данном случае трава явно не должна была расходовать свыше 10 % всех циклов, особенно с учетом крайнего их дефицита. На настольном ПК это было не столь заметно, но на Ultrabook это существенно повлияло на скорость. Помимо роста потребления ресурсов было замечено, что при игре, всякий раз, когда перед игроком происходила отрисовка новой травы, кадровая скорость резко падала, поскольку пиковая нагрузка мешала обычному плавному выполнению игры.


    Рисунок 10. Зеленая, зеленая трава: отрисовка травы в реальном времени может оказаться чрезвычайно ресурсоемкой.

    Решение состояло в том, чтобы перенести всю систему отрисовки травы на этап предвари-тельной обработки, происходящий еще до запуска самой игры. Вместо формирования травы «на лету» ее просто переместили перед игроком, причем на глаз практически никакой разницы не было заметно. Теперь ничего не требовалось создавать на лету: траву нужно было всего лишь передвигать. Мой Ultrabook вздохнул с облегчением, поскольку удалось высвободить очень много драгоценных циклов CPU для всего остального игрового движка. Я, в свою очередь, тоже вздохнул с облегчением, поскольку удалось достичь волшебных 60 кадров в секунду, игра пошла с нужной скоростью.

    Загадочное дело таинственной неравномерности

    Добившись идеальной скорости игры и проехав через полмира, чтобы представить игру и ее движок на конференции, я обнаружил, что на демонстрационных устройствах игра работает неравно¬мерно: то и дело происходят рывки, игра словно спотыкается. На настольных компьютерах этих рывков не было, как не было их и на Ultrabook, который я использовал для тестирования. Рывки возникали только на этих устройствах, причем, что интересно, они были мощнее, чем те устройства, на которых я вполне успешно тестировал игру.

    После длительных обсуждений и изучения эту проблему удалось связать с так называемым «разрешением внутреннего таймера». Коротко говоря, во всех играх, скорость действия в которых не зависит от компьютера (то есть, к примеру, персонажу игры нужно одинаковое количество времени, чтобы пробежать из точки А в точку Б вне зависимости от того, на каком компьютере запущена игра), так вот, во всех таких играх требуется доступ к команде GetTime(). Существует несколько команд этого семейства, но самой популярной является команда timeGetTime(), возвращающая количество миллисекунд с момента включения компьютера. При этом предполагается, что результат дается с разрешением в 1 миллисекунду, и действи¬тельно, на многих настольных компьютерах время передается именно с такой точностью. Оказывается, на Ultrabook и других мобильных устройствах, где во главу угла ставится экономия электроэнергии, это разрешение не фиксировано, оно может составлять не 1 миллисекунду, а 10—15. Если вы используете этот таймер для управления физикой в игре, как это было в нашем игровом движке, игра начнет «дергаться» и «спотыкаться» совершенно произвольным образом, поскольку вызовы обновления физики будут хаотично перепрыгивать с одного полученного времени к другому.

    Причина перехода от разрешения в 1 мс к 10—15 мс в том, что некоторые системы могут сократить потребление электроэнергии, снизив частоту работы процессора, а из-за этого и частота тактовых импульсов может непредсказуемо измениться. Для этой проблемы существует несколько решений. Мы рекомендуем использовать команду QueryPerformanceTimer(), гарантирующую точность возвращаемого значения времени за счет второй команды, возвращающей частоту работы таймера.

    5. Подсказки и советы

    Что нужно сделать

    • Дополняйте шейдеры добавочными технологиями, а не заменяйте их при оптимизации для Ultrabook. Ваша игра должна работать и на настольных компьютерах, и на Ultrabook; процесс распространения игры намного проще, если вся игра упакована в один двоичный файл. Шейдеры DirectX* и OpenGL* позволяют создавать разные технологии в рамках одного шейдера. Поскольку ваша игра содержит все необходимое, код игры может определять, на какой платформе игра запущена в данный момент, и выбирать оптимальную процедуру отрисовки, которая на этой платформе даст наибольшую скорость и наивысшее возможное качество.
    • Предложите пользователям экран настроек, где можно выбрать нужный уровень производительности и качества. В подавляющем большинстве случаев компьютерные игроки рассчитывают на наличие таких настроек. Всегда хорошо определять и заранее устанавливать настройки, оптимальные для данной конкретной системы, но у пользователя должна быть возможность изменять эти настройки; кроме того, выбранные вами настройки по умолчанию должны всегда быть работоспособными в системе пользователя.

    Чего не стоит делать

    • Не исходите из того, что ваша игра обязана работать со скоростью 60 кадров в секунду. На большинстве современных устройств можно настроить интервал обновления экрана, чтобы пропускать один или даже три сигнала вертикальной развертки: при этом сохранится нужная плавность игры, но при скорости в 30 кадров в секунду. Разумеется, все будет не настолько чудесно, как при 60 кадрах в секунду, но если правильно отрегули¬ровать синхронизацию, игра все же будет восприниматься очень хорошо.
    • При разработке игры не следует недооценивать ресурсоемкость шейдеров фрагментов, особенно если предполагается использовать не самое мощное графическое оборудование. Если скорость игры недопустимо низка, откажитесь от использования шейдеров или ограничьте их использование, действуя методом исключения.
    • Не следует заранее выбирать разрешение экрана вместо пользователя: выбранное вами разрешение может не поддерживаться экраном устройства. Используйте API Windows* API для опроса устройства и получения совместимого разрешения по умолчанию.
    • • Не полагайтесь на то, что timeGetTime() возвращает время с интервалами в 1 милли-секунду. На Ultrabook при включенных технологиях экономии электроэнергии интервалы могут составлять 10—15 мс!

    6. Краткие советы по работе с Ultrabook

    Дальнейший текст может показаться цитированием очевидного, но тем не менее: предлагаю краткое и полезное руководство по тестированию, запуску и демонстрации ваших игр и трехмерных приложений на Ultrabook.

    Экономия электроэнергии

    При демонстрации для большой аудитории, если вы хотите показать свою игру в лучшем виде, обязательно подключите Ultrabook к электросети. Не работайте от аккумулятора: для экономии электроэнергии система будет ограничивать производительность оборудования, тогда как вам требуется полная мощность.


    Рисунок 11. Управление электропитанием на Ultrabook.

    На всякий случай найдите «Управление электропитанием» на панели управления и убедитесь, что при питании компьютера от сети все меры экономии электроэнергии отключены, а все возможные параметры установлены на максимум.

    Графика

    На панели управления есть еще один раздел, где вы можете управлять ускорением графичес-кого адаптера устройства. Вы найдете параметры, отвечающие за работу GPU и драйвера в режиме экономии электроэнергии. Нужно выбрать режим наибольшей производительности (или эквивалентный ему), чтобы гарантировать наиболее быструю работу графического процессора.


    Рисунок 12. :Параметры ускорения обработки графики на Ultrabook™

    Необходимость таких действий может вызвать недоумение, но помните, что во главу угла при разработке Ultrabook ставится экономия электроэнергии везде и всегда, где это возможно, что позволяет таким устройствам подолгу работать без подзарядки. Самый простой и действен¬ный способ достижения максимальной производительности Ultrabook — включить его в розетку и выставить все настройки на максимум.

    Фоновые задачи

    Опытные разработчики, да и опытные пользователи согласятся с этим простым, но эффектив-ным советом: нужно посмотреть, какие фоновые задачи запускаются на Ultrabook при загрузке Windows. Предполагалось, что фоновые программы будут полезными, и при этом не будут потреблять слишком много ресурсов, но когда их много, они имеют нехорошую тенденцию довольно серьезно загружать CPU.

    Сколь бы важными ни были эти задачи, когда вы демонстрируете, насколько быстро ваша трехмерная игра может работать на Ultrabook, разумно отключить вообще все задачи, которые не нужны непосредственно для этой цели. За фоновые задачи не беспокойтесь, при следующей загрузке Ultrabook они снова появятся, но зато сейчас в течение всего оставшегося сеанса Windows все ресурсы устройства будут предоставлены одному-единственному приложению — вашему!

    7. Выводы

    Тема оптимизации игр весьма обширна. Разработчики должны рассматривать оптимизацию как неотъемлемую часть своей повседневной работы. Цель в том, чтобы вашу игру можно было запускать на как можно более широком наборе оборудования. Для достижения этой цели потребуется весь ваш опыт, все знания и умения. Применяя такие средства Intel®, как VTune™ Analyzer и Intel Graphics Performance Analyzers, можно ускорить решение этой задачи. Статьи, подобные этой, подскажут возможные решения, но в конечном итоге все зависит от вашей сообразительности. Как можно добиться этого же результата другим способом? Можно ли сделать это быстрее? Можно ли сделать это умнее? Вот с таких вопросов следует начинать, и чем чаще вы станете их задавать, тем эффективнее сможете оптимизировать свои игры и приложения. Как я предположил в начале этой статьи, вы не только станете выпускать более качественный код, но и расширите свои позиции на стремительно растущем рынке!

    Другие материалы по теме

    Codemasters GRID 2* on 4th Generation Intel® Core™ Processors - Game development case study
    Not built in a day - lessons learned on Total War: ROME II
    Developer's Guide for Intel® Processor Graphics for 4th Generation Intel® Core™ Processors
    PERCEPTUAL COMPUTING: Augmenting the FPS Experience

    Об авторе

    Во время, свободное от написания статей, Ли Бэмбер руководит британской компанией The Game Creators (http://www.thegamecreators.com)), которая специализируется на разработке и распространении средств создания компьютерных игр. Эта компания ведет свою историю с 1999 года. Среди плодов работы этой компании вместе с окружающим ее разработчиком игр — множество популярных брендов, в том числе Dark Basic, FPS Creator, а также App Game Kit (AGK). Ли также ведет хронику своей повседневной работы разработчика вместе со снимками экрана и видеороликами: http://fpscreloaded.blogspot.co.uk




     

    Intel®Developer Zone offers tools and how-to information for cross-platform app development, platform and technology information, code samples, and peer expertise to help developers innovate and succeed.  Join our communities for the Internet of Things, Android*, Intel® RealSense™ Technology and Windows* to download tools, access dev kits, share ideas with like-minded developers, and participate in hackathons, contests, roadshows, and local events.

    Any software source code reprinted in this document is furnished under a software license and may only be used or copied in accordance with the terms of that license.
    Intel, the Intel logo, Ultrabook, and VTune are trademarks of Intel Corporation in the U.S. and/or other countries.
    Copyright © 2014 Intel Corporation. All rights reserved.
    *Other names and brands may be claimed as the property of others.

  • ultrabook
  • game optimization
  • Shader
  • Shadow Mapping
  • performance optimization
  • Sviluppatori
  • Microsoft Windows* 8
  • Windows*
  • Intermedio
  • Sviluppo giochi
  • Laptop
  • URL
  • Area tema: 

    IDZone

    How to analyze OpenMP* applications using Intel® VTune™ Amplifie XE 2015

    $
    0
    0

     

    Introduction

     

    Intel® VTune™ Amplifier XE 2015 now includes extensive capabilities for analyzing OpenMP applications. This article will step through this analysis on an Intel® Xeon Phi™ coprocessor.

     

    Compiling and running the application

     

    The application we will be using is one of the samples included in VTune Amplifier. It is located in /opt/intel/vtune_amplifier_xe_2015/samples/en/C++/matrix_vtune_amp_xe.tgz. To build the application on Linux*:

    1. Source the environment for the Intel® Compiler you are using for example.
      1. source /opt/intel/composer_xe_2015/compilervars.sh intel64
    2. Untar the sample in a directory where you have permission
      1. tar xvzf matrix_vtune_amp_xe.tgz
    3. By default the sample does not use OpenMP. You will need to modify the Makefile
      1. cd matrix/linux
      2. Edit the Makefile and comment the default PARAMODEL and uncomment the OpenMP PARAMODEL.
    4. Build the application to run native on the Xeon Phi
      1. cd matrix/linux
      2. make mic
    5. The make command from step #4 will create a Xeon Phi copressor native matrix.mic executable. It will also copy the file to mic0:/tmp.
    6. Verify the libiomp5.so library is available on your Xeon Phi coprocessor.
      1. Either in /tmp or lib64.
    7. Run the application
      1. /tmp/matrix.mic

    Addr of buf1 = 0x7fec2b054010

    Offs of buf1 = 0x7fec2b054180

    Addr of buf2 = 0x7fec23fd3010

    Offs of buf2 = 0x7fec23fd31c0

    Addr of buf3 = 0x7fec1cf52010

    Offs of buf3 = 0x7fec1cf52100

    Addr of buf4 = 0x7fec15ed1010

    Offs of buf4 = 0x7fec15ed1140

    Threads #: 240 OpenMP threads

    Matrix size: 3840

    Using multiply kernel: multiply1

    Freq = 1.090908 GHz

    Execution time = 23.866 seconds

     

    Running the application using VTune Amplifier

     

    1. Source /opt/intel/vtune_amplifier_xe_2015/amplxe-vars.sh
    2. Start the VTune Amplifier GUI
      1. amplxe-gui
    3. Create a VTune Amplifier project
      1. File->New->Project
      2. Specify a project name and also select Intel Xeon Phi coprocessor native
      3. Click Ok
    4. Click on "New Analysis"
    5. Click on "Advanced Hotspots"
    6. Click "Start"
    7. VTune Amplifier will launch the application and then finalize the result

    Analyzing an OpenMP application using VTune Amplifier

    1. After your analysis has completed VTune Amplifier will show a summary view of your collected run.
    2. Two new sections have been added to the summary for OpenMP
      1. OpenMP Analysis. Collection Time
        1. Parallel Region Time
          1. Note the serial time. You should investigate if this serial time could be done in parallel.
        2. Estimated Ideal Time
        3. Potential Gain
          1. Several factors can affect potential gains such as load balance, work scheduling and if your region has enough work.
      2. Top OpenMP Regions by Potential Gain
        1. This section lists the OpenMP regions, you should investigate each region in the order of potential gain.

    Bottom-Up Analysis

    Click on the Bottom-up tab and you can see a list of top OpenMP regions.

     

     

    Summary

    VTune Amplifier has made some significant improvements in the analysis of OpenMP applications. VTune Amplifier now lists the top OpenMP regions in your program and also estimates potential performance gains you can possibly achieve by optimizing them. VTune Amplifier also points specifically at how much time you are running serially versus in parallel, this is one of the most critical insights in gaining performance on a parallel application.

     

     

  • Sviluppatori
  • Linux*
  • C/C++
  • Fortran
  • Intermedio
  • URL
  • Miglioramento delle prestazioni
  • Area tema: 

    IDZone

    General Matrix Multiply Sample

    $
    0
    0

    Download for WindowsDownload for LinuxDownload Documentation

    Description

    General Matrix Multiply (GEMM) sample demonstrates how to efficiently utilize an OpenCL™ device to perform general matrix multiply operation on two dense square matrices. The primary target devices that are suitable for this sample are the devices with cache memory: Intel® Xeon Phi™ and Intel® Architecture CPU devices.

    The sample:

    • Optimizes trivial matrix multiplication nested loop to utilize the memory cache more efficiently
    • Supports single-precision and double-precision data types
    • Demonstrates how to use different storage methods for matrices
    • Demonstrates how to utilize the automatic vectorizer efficiently and avoid gathers

    Supported Devices: CPU, Intel® Xeon Phi™ coprocessor
    Supported OS: Windows* and Linux* OS
    Complexity Level: Intermediate

    Refer to the sample release notes for information on system requirements.
    For more information about the sample refer to the sample User's Guide inside the sample package.

    ZIP sample package contains sample files for Windows* OS
    TAR.GZ sample package contains sample files for Linux* OS.

    * OpenCL and the OpenCL logo are trademarks of Apple Inc. used by permission by Khronos.

  • visual computing
  • Sviluppatori
  • Linux*
  • Microsoft Windows* (XP, Vista, 7)
  • Microsoft Windows* 8
  • Windows*
  • C/C++
  • Intermedio
  • Intel® SDK per applicazioni OpenCL™
  • OpenCL*
  • Strumenti di sviluppo
  • Architettura Intel® Many Integrated Core
  • Laptop
  • Server
  • Desktop
  • URL
  • Esempio di codice
  • OpenCL-SDK-Code-Samples
  • Area tema: 

    IDZone

    Ultimo aggiornamento: 

    Martedì, 9 Settembre, 2014
    Viewing all 664 articles
    Browse latest View live


    <script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>