Cardboard VR Projects for Android
By Jonathan Linowes and Matt Schoen
()
About this ebook
- Learn how to build practical applications for Google's popular DIY VR headset
- Build a reusable VR graphics engine on top of the Cardboard Java SDK and OpenGL ES graphics libraries
- The projects in this book will showcase a different aspect of Cardboard development—from 3D rendering to handling user input
The book is for established Android developers with a good knowledge of Java. No prior OpenGL or graphics knowledge is required. No prior experience with Google Cardboard is expected, but those who are familiar with Cardboard and are looking for projects to expand their knowledge can also benefit from this book.
Jonathan Linowes
Jonathan Linowes is the owner of Parkerhill Reality Labs, a start-up VR/AR consultancy firm. He is a veritable VR and 3D graphics enthusiast, full-stack web developer, software engineer, successful entrepreneur, and teacher. He has a fine arts degree from Syracuse University and a master's degree from the MIT Media Lab. He has founded several successful start-ups and held technical leadership positions at major corporations, including Autodesk Inc.
Read more from Jonathan Linowes
Augmented Reality for Developers: Build practical augmented reality applications with Unity, ARCore, ARKit, and Vuforia Rating: 0 out of 5 stars0 ratingsUnity Virtual Reality Projects Rating: 0 out of 5 stars0 ratingsUnity Virtual Reality Projects: Learn Virtual Reality by developing more than 10 engaging projects with Unity 2018, 2nd Edition Rating: 0 out of 5 stars0 ratingsAugmented Reality with Unity AR Foundation: A practical guide to cross-platform AR development with Unity 2020 and later versions Rating: 0 out of 5 stars0 ratings
Related to Cardboard VR Projects for Android
Related ebooks
OpenCV Android Programming By Example Rating: 0 out of 5 stars0 ratingsC++ Game Animation Programming: Learn modern animation techniques from theory to implementation using C++, OpenGL, and Vulkan Rating: 0 out of 5 stars0 ratingsAugmented and Virtual Reality The Ultimate Step-By-Step Guide Rating: 0 out of 5 stars0 ratingsPython for Machine Learning: From Fundamentals to Real-World Applications Rating: 0 out of 5 stars0 ratingsHaxe Game Development Essentials Rating: 0 out of 5 stars0 ratingsHoloLens Blueprints Rating: 0 out of 5 stars0 ratingsMastering Adobe Captivate 6 Rating: 5 out of 5 stars5/5Network Automation Cookbook: Proven and actionable recipes to automate and manage network devices using Ansible Rating: 0 out of 5 stars0 ratingsThree Dimensional Computer Graphics: Exploring the Intersection of Vision and Virtual Worlds Rating: 0 out of 5 stars0 ratingsRapid Prototyping A Complete Guide - 2020 Edition Rating: 0 out of 5 stars0 ratingsTeaching the Game: A collection of syllabi for game design, development, and implementation, Vol. 1 Rating: 0 out of 5 stars0 ratings3D NAND Complete Self-Assessment Guide Rating: 0 out of 5 stars0 ratingsThinking about Digital Accessibility: Stumbling Blocks and Steppingstones in Design and Development Rating: 0 out of 5 stars0 ratingsThinking about Digital Accessibility: The Enterprise Journey Rating: 0 out of 5 stars0 ratingsUnreal Development Kit Beginner’s Guide Rating: 1 out of 5 stars1/5Digital Culture & Society (DCS): Vol. 1, Issue 1 – Digital Material/ism Rating: 0 out of 5 stars0 ratingsEmergence and Innovation in Digital Learning: Foundations and Applications Rating: 0 out of 5 stars0 ratingsAlgorithmic and Aesthetic Literacy: Emerging Transdisciplinary Explorations for the Digital Age Rating: 0 out of 5 stars0 ratingsPanda3D 1.6 Game Engine Beginner's Guide Rating: 0 out of 5 stars0 ratingsAll about Coding Functions Rating: 0 out of 5 stars0 ratingsOpenCL in Action: How to accelerate graphics and computations Rating: 0 out of 5 stars0 ratingsWebflow by Example.: Design, build, and publish modern websites without writing code Rating: 0 out of 5 stars0 ratingsGamification with Unity 5.x Rating: 0 out of 5 stars0 ratingsLua Essentials: A Journey Through Code and Creativity Rating: 0 out of 5 stars0 ratingsMastering the 3D Photography Cha-Cha Rating: 0 out of 5 stars0 ratingsLearning AWS Lumberyard Game Development Rating: 0 out of 5 stars0 ratingsSTEAM Jobs in Social Media Rating: 0 out of 5 stars0 ratingsTackling Wicked Problems in Complex Ecologies: The Role of Evaluation Rating: 0 out of 5 stars0 ratings
Hardware For You
Samsung Galaxy S21 For Dummies Rating: 0 out of 5 stars0 ratingsChip War: The Fight for the World's Most Critical Technology Rating: 4 out of 5 stars4/5IPhone 14 Pro Max Camera Mastering: Smart Phone Photography Taking Pictures Like A Pro Even As A Beginner Rating: 0 out of 5 stars0 ratingsiPhone 11 Quick User Starter Guide: Get a Fast Understanding on Your iPhone Features and Essential Apps Rating: 0 out of 5 stars0 ratingsDancing with Qubits: How quantum computing works and how it can change the world Rating: 5 out of 5 stars5/5Mastering Embedded Linux Programming Rating: 5 out of 5 stars5/5iPhone 11 User Guide: The Simple Manual to Understand Your iPhone 11 with Tips and Tricks Rating: 0 out of 5 stars0 ratingsElectrical Engineering | Step by Step Rating: 0 out of 5 stars0 ratingsThe Geeky Kids Guide! To Building Your Own Gaming PC Rating: 3 out of 5 stars3/5iPhone Photography: A Ridiculously Simple Guide To Taking Photos With Your iPhone Rating: 0 out of 5 stars0 ratingsTI-89 Graphing Calculator For Dummies Rating: 3 out of 5 stars3/5Build Your Own PC Do-It-Yourself For Dummies Rating: 4 out of 5 stars4/5The First Superapp: Inside China's WeChat and the new digital revolution Rating: 5 out of 5 stars5/5Arduino | Step by Step Rating: 0 out of 5 stars0 ratingsCompTIA A+ Complete Review Guide: Exam Core 1 220-1001 and Exam Core 2 220-1002 Rating: 5 out of 5 stars5/5After Steve: How Apple Became a Trillion-Dollar Company and Lost Its Soul Rating: 4 out of 5 stars4/5Arduino by Example Rating: 4 out of 5 stars4/5MacOS Mastery: The Ultimate Guide to 250 Powerful Shortcuts Rating: 0 out of 5 stars0 ratingsPractical Digital Forensics Rating: 0 out of 5 stars0 ratingsInside Nvidia: Jensen Huang's Vision for Artificial Intelligence Rating: 0 out of 5 stars0 ratingsiPhone For Seniors For Dummies Rating: 4 out of 5 stars4/5Exploring BeagleBone: Tools and Techniques for Building with Embedded Linux Rating: 4 out of 5 stars4/5Adventures in Minecraft Rating: 4 out of 5 stars4/53D Printing For Dummies Rating: 4 out of 5 stars4/5
Reviews for Cardboard VR Projects for Android
0 ratings0 reviews
Book preview
Cardboard VR Projects for Android - Jonathan Linowes
Table of Contents
Cardboard VR Projects for Android
Credits
About the Authors
About the Reviewers
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. Virtual Reality for Everyone
Why is it called Cardboard?
The spectrum of VR devices
Old fashioned stereoscopes
Cardboard is mobile VR
Desktop VR and beyond
A gateway to VR
The value of low-end VR
Cardware!
Configuring your Cardboard viewer
Developing apps for Cardboard
Using Unity
Going native
An overview to VR best practices
Summary
2. The Skeleton Cardboard Project
What's in an Android app?
APK files
A Gradle build process
A Java compiler
The Android project structure
Getting started with Android Studio
Installing Android Studio
The Android Studio user interface
Creating a new Cardboard project
Adding the Cardboard Java SDK
The AndroidManifest.xml file
The activity_main.xml file
The MainActivity class
Default onCreate
Building and running
Summary
3. Cardboard Box
Creating a new project
Hello, triangle!
Introducing geometry
Triangle variables
onSurfaceCreated
Introducing OpenGL ES 2.0
Simple shaders
The compileShaders method
The prepareRenderingTriangle method
onDrawEye
Building and running
3D camera, perspective, and head rotation
Welcome to the matrix
The MVP vertex shader
Setting up the perspective viewing matrices
Render in perspective
Building and running
Repositioning the triangle
Hello, cube!
The cube model data
Cube code
Lighting and shading
Adding shaders
Cube normals and colors
Preparing the vertex buffers
Preparing the shaders
Adding a light source
Building and running the app
Spinning the cube
Hello, floor!
Shaders
Floor model data
Variables
onCreate
onSurfaceCreated
initializeScene
prepareRenderingFloor
onDrawEye
drawFloor
Hey, look at this!
The isLookingAtObject method
Summary
4. Launcher Lobby
Creating a new project
Adding Hello Virtual World text overlay
A simple text overlay
Center the text using a child view
Create stereoscopic views for each eye
Controlling the overlay view from MainActivity
Using a virtual screen
Responding to head look
Adding an icon to the view
Listing installed Cardboard apps
Queries for Cardboard apps
Create the Shortcut class for apps
Add shortcuts to OverlayView
Using view lists in OverlayEye
Highlighting the current shortcut
Using the trigger to pick and launch the app
Further enhancements
Summary
5. RenderBox Engine
Introducing RenderBox – a graphics engine
Creating a new project
Creating the RenderBox package folder
Creating an empty RenderBox class
Adding the IRenderBox interface
Materials, textures, and shaders
Abstract material
The Math package
MathUtils
Matrix4
Quaternion
Vector2
Vector3
The Transform class
Parent methods
Position methods
Rotation methods
Scale methods
Transform to matrix and draw
The Component class
The RenderObject component
The Cube RenderObject component
Vertex color material and shaders
Vertex color shaders
VertexColorMaterial
The Camera component
RenderBox methods
A simple box scene
Cube with face normals
The Light component
Vertex color lighting material and shaders
Time for animation
Detect looking at objects
Exporting the RenderBox package
Building the RenderBoxLib module
The RenderBox test app
Using RenderBox in future projects
Summary
6. Solar System
Setting up a new project
Creating a Sphere component
A solid color lighted sphere
Solid color lighting shaders
Solid color lighting material
Adding a Material to a Sphere
Viewing the Sphere
Adding the Earth texture material
Loading a texture file
Diffuse lighting shaders
Diffuse lighting material
Adding diffuse lighting texture to a Sphere component
Viewing the Earth
Changing the camera position
Day and night material
Day/night shader
The DayNightMaterial class
Rendering with day/night
Creating the Sun
Unlit texture shaders
Unlit texture material
Rendering with an unlit texture
Adding the Sun
Creating a Planet class
Formation of the Solar System
Setting up planets in MainActivity
Camera's planet view
Animating the heavenly bodies
A starry sky dome
Fine tuning the Earth
The night texture
Axis tilt and wobble
Changing the camera location
Possible enhancements
Updating the RenderBox library
Summary
7. 360-Degree Gallery
Setting up the new project
Viewing a 360-degree photo
Viewing a sample photosphere
Using the background image
Viewing a regular photo
Defining the Plane component and allocating buffers
Adding materials to the Plane component
Adding an image screen to the scene
Putting a border frame on the image
Border shaders
The border material
Using the border material
Loading and displaying a photo image
Defining the image class
Reading images into the app
Image load texture
Showing an image on the screen
Rotating to the correct orientation
Dimensions to correct the width and height
Sample image down to size
Loading and displaying a photosphere image
The image gallery user interface
Positioning the photo screen on the left
Displaying thumbnails in a grid
The thumbnail image
The Thumbnail class
The thumbnail grid
Gaze to load
Gaze-based highlights
Selecting and showing photos
Queue events
Using a vibrator
Enable scrolling
Creating the Triangle component
Adding triangles to the UI
Interacting with the scroll buttons
Implementing the scrolling method
Stay responsive and use threads
An explanation of threading and virtual reality
Launch with an intent
Showing/hiding the grid with tilt-up gestures
Spherical thumbnails
Add a sphere to the Thumbnail class
Updating the RenderBox library
Further possible enhancements
Summary
8. 3D Model Viewer
Setting up a new project
Understanding the OBJ file format
Creating the ModelObject class
Parse OBJ models
buildBuffers
Model extents, scaling, and center
I'm a little teapot
I'm a little rotating teapot
Thread safe
Launch with intent
Practical and production ready
Summary
9. Music Visualizer
Setting up a new project
Capturing audio data
A VisualizerBox architecture
Waveform data capture
A basic geometric visualization
2D texture-based visualization
Texture generator and loader
Waveform shaders
Basic waveform material
Waveform visualization
FFT visualization
Capture the FFT audio data
FFT shaders
Basic FFT material
FFT visualization
Trippy trails mode
Multiple simultaneous visualizations
Random visualizations
Further enhancements
A community invite
Summary
Onward to the future
Index
Cardboard VR Projects for Android
Cardboard VR Projects for Android
Copyright © 2016 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: May 2016
Production reference: 1120516
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78588-787-1
www.packtpub.com
Credits for the Cover Image:
Custom Illustration designed by eLearning Mind, LLC., www.eLearningMind.com, ELM creates interactive learning experiences using modern brain science and intuitively stunning design.
The DIY Virtual Reality article: http://elearningmind.com/diy-virtual-reality-world-of-warcraft-thinks-inside-the-box-at-comic-con-2015/
Credits
Authors
Jonathan Linowes
Matt Schoen
Reviewers
Scott Dolim
Oleksandr Popov
Commissioning Editor
Edward Gordon
Acquisition Editor
Reshma Raman
Content Development Editor
Sachin Karnani
Technical Editor
Siddhi Rane
Copy Editor
Rashmi Sawant
Project Coordinator
Nikhil Nair
Proofreader
Safis Editing
Indexer
Hemangini Bari
Graphics
Kirk D'Penha
Production Coordinator
Shantanu N. Zagade
Cover Work
Shantanu N. Zagade
About the Authors
Jonathan Linowes is the owner of Parkerhill Reality Labs, a start-up VR/AR consultancy firm. He is a VR and 3D graphics enthusiast, full-stack web developer, software engineer, successful entrepreneur, and teacher. He has a fine arts degree from Syracuse University and a master's degree from the MIT Media Lab. He has founded several successful start-ups and held technical leadership positions at major corporations, including Autodesk Inc. He is also the author of the Unity Virtual Reality Projects book by Packt Publishing.
Matt Schoen is the cofounder of Defective Studios and has been making VR apps since the early DK1 days. Still in the early stages of his career, he spent most of his time working on Unity apps and games, some for hire and some of his own design. He studied computer engineering at Boston University and graduated with a BS in 2010, at which point he founded Defective with Jono Forbes, a high-school friend. He has been making games and apps ever since. Matt was the technical lead on Defective's debut game, CosmoKnots, and remains involved in Jono's pet project, Archean. This is his first foray into authorship, but he brings with him his experience as an instructor and curriculum designer for Digital Media Academy. Jono and Matt have recently joined Unity's VR Labs division, where they will be helping to create experimental new features which will shape the VR landscape for years to come.
About the Reviewers
Scott Dolim has worked on and off in 3D computer graphics for over 20 years, including a 5-year stint at Walt Disney Feature Animation in the 1990s. More recently, for the last 5 years, he has been actively involved in virtual reality development, mostly with Unity 3D. Scott currently works at Google where he is the lead engineer of the Cardboard SDK for Unity.
Oleksandr Popov is a developer of numerous 3D apps, mainly live wallpapers, for Android devices. His first experience with 3D for Android started in 2012 when with the release of Android 2.2, it became possible to create live wallpapers. Since then, he has released about 15 of them in collaboration with his brother, Dmytro, who is responsible for creating 3D scenes. After releasing each app, he gained more and more experience in OpenGL ES. Basically, he tried almost every new feature of Android where 3D and OpenGL can be applied. He started with live wallpapers in Android 2.2, then he added support of the daydream mode for them in 4.2. He started using some of the features of OpenGL ES 3.0 introduced in Android 4.3. And as soon as Google added support of custom watch faces for Android Wear 5.0, he and his brother created a set of 3D watch faces for smart watches too. Of course, after Google announced Cardboard, he immediately decided to create VR apps for this platform as well.
He and his brother are also coauthors of the Deconstructing Google Cardboard Apps book by Bleeding Edge Press.
www.PacktPub.com
eBooks, discount offers, and more
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Preface
Google Cardboard is a low-cost, entry-level medium used for experiencing virtual 3D environments. Its applications are as broad and varied as mobile smartphone applications themselves. This book gives you the opportunity to implement a variety of interesting projects for Google Cardboard using the native Java SDK. The idea is to educate you with best practices and methodologies to make Cardboard-compatible mobile VR apps and guide you through making quality content appropriate for the device and its intended users.
What this book covers
Chapter 1, Virtual Reality for Everyone, defines Google Cardboard, explores it, and discusses how it's used and how it fits in the spectrum of VR devices.
Chapter 2, The Skeleton Cardboard Project, examines the structure of a Cardboard app for Android, takes a tour of Android Studio, and helps you build a starter Cardboard project by introducing the Cardboard Java SDK.
Chapter 3, Cardboard Box, discusses how to build a Cardboard Android app from scratch (based on Google's Treasure Hunt sample) with a 3D cube model, transformations, stereoscopic camera views, and head rotations. This chapter also includes discussions of 3D geometry, Open GL ES, shaders, matrix math, and the rendering pipeline.
Chapter 4, Launcher Lobby, helps you build an app to launch other Cardboard apps on your phone. Rather than using 3D graphics, this project simulates stereoscopic views in screen space and implements gaze-based selections.
Chapter 5, RenderBox Engine, shows you how to create a small graphics engine used to build new Cardboard VR apps by abstracting the low-level OpenGL ES API calls into a suite of the Material, RenderObject, Component, and Transform classes. The library will be used and further developed in subsequent projects.
Chapter 6, Solar System, builds a Solar System simulation science project by adding a sunlight source, spherical planets with texture mapped materials and shaders, animating in their solar orbits, and a Milky Way star field.
Chapter 7, 360-Degree Gallery, helps you build a media viewer for regular and 360-degree photos, and helps you load the phone's camera folder pictures into a grid of thumbnail images and use gaze-based selections to choose the ones to view. It also discusses how to add process threading for improved user experience and support Android intents to view images from other apps.
Chapter 8, 3D Model Viewer, helps you build a viewer for 3D models in the OBJ file format, rendered using our RenderBox library. It also shows you how to interactively control the view of the model as you move your head.
Chapter 9, Music Visualizer, builds a VR music visualizer that animates based on waveform and FFT data from the phone's current audio player. We implement a general architecture used to add new visualizations, including geometric animations and dynamic texture shaders. Then, we add a trippy trails mode and multiple concurrent visualizations that transition in and out randomly.
What you need for this book
Throughout the book, we use the Android Studio IDE development environment to write and build Android applications. You can download Android Studio for free, as explained in Chapter 2, The Skeleton Cardboard Project. You will need an Android phone to run and test your projects. And it's strongly recommended that you have a Google Cardboard viewer to experience your apps in stereoscopic virtual reality.
Who this book is for
This book is for Android developers who are interested in learning about and developing Google Cardboard apps using the Google Cardboard native SDK. We assume that the reader has some knowledge of Android development and the Java language, but may be new to 3D graphics, virtual reality, and Google Cardboard. Novice developers, or those unfamiliar with the Android SDK, may find it hard to get started with this book. Those who aren't coming from an Android background may be better served by creating cardboard apps with a game engine like Unity.
Conventions
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: Edit the MainActivity Java class so that it extends CardboardActivity and implements CardboardView.StereoRenderer.
A block of code is set as follows:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CardboardView cardboardView = (CardboardView) findViewById(R.id.cardboard_view);
cardboardView.setRenderer(this);
setCardboardView(cardboardView);
}
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CardboardView cardboardView = (CardboardView) findViewById(R.id.cardboard_view);
cardboardView.setRenderer(this); setCardboardView(cardboardView);
}
Any command-line input or output is written as follows:
git clone https://github.com/googlesamples/cardboard-java.git
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: In Android Studio, select File | New | New Module…. Select Import .JAR/.AAR Package.
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <feedback@packtpub.com>, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading the example code
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the SUPPORT tab at the top.
Click on Code Downloads & Errata.
Enter the name of the book in the Search box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on Code Download.
You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
You can also download the code fles from GitHub at https://github.com/cardbookvr.
Downloading the color images of this book
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/CardboardVRProjectsforAndroid_ColorImages.pdf.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <copyright@packtpub.com> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
Questions
If you have a problem with any aspect of this book, you can contact us at <questions@packtpub.com>, and we will do our best to address the problem.
Chapter 1. Virtual Reality for Everyone
Welcome to the exciting new world of virtual reality! We're sure that, as an Android developer, you want to jump right in and start building cool stuff that can be viewed using Google Cardboard. Your users can then just slip their smartphone into a viewer and step into your virtual creations. Before we get up to our elbows in the code and tech stuff throughout the rest of this book, let's take an outside-in tour of VR, Google Cardboard, and its Android SDK to see how they all fit together. We will discuss the following topics in this chapter:
Why is it called Cardboard?
The spectrum of virtual reality devices
A gateway to VR
The value of low-end VR
Cardware
Configuring your Cardboard viewer
Developing apps for Cardboard
An overview of VR best practices
Why is it called Cardboard?
It all started in early 2014 when Google employees, David Coz and Damien Henry, in their spare time, built a simple and cheap stereoscopic viewer for the Android smartphones. They designed a device that can be constructed from ordinary cardboard, plus a couple of lenses for your eyes, and a mechanism to trigger a button click.
The viewer is literally made from cardboard. They wrote software that renders a 3D scene with a split screen: one view for the left eye, and another view, with offset, for the right eye. Peering through the device, you get a real sense of 3D immersion into the computer generated scene. It worked! The project was then proposed and approved as a 20% project
(where employees may dedicate one day a week for innovations), funded, and joined by other employees.
Note
Two sources of canonical
facts about the story behind how Cardboard came into existence are as follows:
http://www.wired.com/2015/06/inside-story-googles-unlikely-leap-cardboard-vr/
https://en.wikipedia.org/wiki/Google_Cardboard
In fact, Cardboard worked so well that Google decided to go forward, taking the project to the next level and releasing it to the public a few months later at Google I/O 2014. The following figure shows a typical unassembled Google Cardboard kit:
Since its inception, Google Cardboard has been accessible to hackers, hobbyists, and professional developers alike. Google open sourced the viewer design for anyone to download the schematics and make their own, from a pizza box or from whatever they had lying around. One can even go into business selling precut kits directly to consumers. An assembled Cardboard viewer is shown in the following image:
The Cardboard project also includes a software development kit (SDK) that makes it easy to build VR apps. Google has released continuous improvements to the software, including both a native Java SDK as well as a plugin for the Unity 3D game engine (https://unity3d.com/).
Since the release of Cardboard, a huge number of applications have been developed and made available on the Google Play Store. At Google I/O 2015, Version 2.0 introduced an upgraded design, improved software, and support for Apple iOS.
Google Cardboard has rapidly evolved in the eye of the market from an almost laughable toy into a serious new media device for certain types of 3D content and VR experiences. Google's own Cardboard demo app has been downloaded millions of times from the Google Play Store. The New York Times distributed about a million cardboard viewers with its November 8, Sunday issue back in 2015.
Cardboard is useful for viewing 360-degree photos and playing low-fidelity 3D VR games. It is universally accessible to almost anyone because it runs on any Android or iOS smartphone.
Developers are now integrating 3D VR content directly into Android apps. Google Cardboard is a way of experiencing virtual reality that is here to stay.
The spectrum of VR devices
As with most technologies, there is a spectrum of products for virtual reality ranging from the simplest and least expensive to the very advanced.
Old fashioned stereoscopes
Cardboard is at the low end of the VR device spectrum. Well, you could even go lower if you consider the ViewMaster that you may have played with as a child, or even the historic stereoscope viewer from 1876 (B.W. Kilborn & Co, Littleton, New Hampshire), as shown in the following image:
In these old fashioned viewers, a pair of photographs display two separate views for the left and right eyes that are slightly offset to create parallax. This fools the brain into thinking that it's seeing a truly three-dimensional view. The device contains separate lenses for each eye that allow you to easily focus on the photo close up.
Similarly, rendering these side-by-side stereo views is the first job of a Google Cardboard application. (Leveraging their legacy, Mattel recently released a Cardboard-compatible ViewMaster brand VR viewer that uses a smartphone, which can be found at http://www.view-master.com/).
Cardboard is mobile VR
Cardboard's obvious advantages over stereoscopic viewers are like the advantages of digital photographs over traditional ones. Digital media can be dynamically stored, loaded, and manipulated right within our smartphones. That's a powerful leap on its own.
On top of that, Cardboard uses the motion sensors in the phone in such a way that when you turn your head left-right or up-down, the image is adjusted accordingly, effectively obliterating the traditional frame edges of the image. Framing the image is a very important part of traditional visual media, such as painting, photography, and cinematography. For centuries, artists and directors have established a visual language using this rectangular frame.
However, not so much in VR. When you move your head in VR your view direction changes, and the scene is updated as if the camera is rotating along with you, providing a fully immersive view. You can rotate it horizontally 360 degrees as you look side to side and 180 degrees up and down. In other words, you can look anywhere you want. There is no frame in VR! (Albeit your peripheral vision might be limited by the optics and display size, which determine the device's field of view or FOV). In this way, the design considerations may be more akin to sculpture, theatre-in-the-round, or even architectural design. We need to think about the whole space that immerses the visitor.
The Google Cardboard device is simply a casing for you to slip your smartphone into. It uses the smartphone's technology, including the following:
Display
CPU (the main processor)
GPU (the graphics processor)
IMU (the motion sensor)
Magnetometer and/or touchscreen (the trigger sensor)
We'll talk more about how all this works a little later.
Using a mobile smartphone for VR means great things, such as ease of use, but also annoying constraints, such as limited battery life, slower graphics processing, and lower accuracy/higher latency motion sensors.
The Samsung Gear VR is a mobile VR headset that is smarter than a simple Cardboard viewer. Android-based but not compatible with Cardboard apps (and only works with specific models of Samsung phones), it has a separate built-in higher precision IMU (motion sensor), which increases the accuracy of the head motion tracking and helps reduce the motion-to-pixel latency when updating the display. It's also ergonomically designed for more extended use and it includes a strap.
Desktop VR and beyond
At the higher end of consumer virtual reality devices are the Oculus Rift, HTC Vive, and Sony PlayStation VR, among others. These products go beyond what Cardboard can do because they're not limited by the capabilities of a smartphone. Sometimes referred to as desktop VR,
these devices are head-mounted displays (HMD) tethered to an external PC or console.
On desktop VR, the desktop's powerful CPU and GPU do the actual computation and graphics rendering and send the results to the HMD. Furthermore, the HMD has higher quality motion sensors and other features that help reduce the latency when updating the display at, say, 90 frames per second (FPS). We'll learn throughout this book that reducing latency and maintaining high FPS are important concerns for all VR development and the comfort of your users on all VR devices, including Cardboard.
Desktop VR devices also add positional tracking. The Cardboard device can detect the rotational movement on any of the X, Y, and Z axes, but it unfortunately cannot detect the positional movement (for example, sliding along any of these axes). The Rift, Vive, and PSVR can. The Rift, for example, uses an external camera to track the position using infrared lights on the HMD (outside-in tracking). The Vive, on the other hand, uses sensors on the HMD to track a pair of laser emitters placed strategically in the room (inside-out tracking). The Vive also uses this system to track the position and rotation of a pair of hand controllers. Both strategies achieve similar results. The user has a greater freedom to move around within the tracked space while experiencing moving around within the virtual space. Cardboard cannot do this.
Note that innovations are continually being introduced. Very likely, at some point, positional tracking will be included with the Cardboard arsenal. For example, we know that Google's Project Tango implements visual-inertial odometry, or VIO, using sensors, gyroscopes, and awareness of the physical space to provide motion and positional tracking to mobile apps. Refer to https://developers.google.com/project-tango/overview/concepts. Mobile device companies, such as LG and Samsung, are working hard to figure out how to do mobile positional tracking, but (at the time of this writing) a universal, low-latency solution does not yet exist. Google's Project Tango shows some promise but cannot yet achieve the time-to-pixel latency required for a smooth, comfortable VR experience. Too much latency and you get sick!
At the