100% found this document useful (6 votes)
70 views

Complete Download AR and VR Using The WebXR API: Learn To Create Immersive Content With WebGL, Three - JS, and A-Frame Rakesh Baruah PDF All Chapters

Rakesh

Uploaded by

elabsymaman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (6 votes)
70 views

Complete Download AR and VR Using The WebXR API: Learn To Create Immersive Content With WebGL, Three - JS, and A-Frame Rakesh Baruah PDF All Chapters

Rakesh

Uploaded by

elabsymaman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Download the full version of the textbook now at textbookfull.

com

AR and VR Using the WebXR API: Learn to


Create Immersive Content with WebGL,
Three.js, and A-Frame Rakesh Baruah

https://textbookfull.com/product/ar-and-vr-using-
the-webxr-api-learn-to-create-immersive-content-
with-webgl-three-js-and-a-frame-rakesh-baruah/

Explore and download more textbook at https://textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

AR and VR Using the WebXR API Learn to Create Immersive


Content with WebGL Three js and A Frame 1st Edition Rakesh
Baruah
https://textbookfull.com/product/ar-and-vr-using-the-webxr-api-learn-
to-create-immersive-content-with-webgl-three-js-and-a-frame-1st-
edition-rakesh-baruah/
textbookfull.com

Biota Grow 2C gather 2C cook Loucas

https://textbookfull.com/product/biota-grow-2c-gather-2c-cook-loucas/

textbookfull.com

Learning Three.js: The JavaScript 3D Library for WebGL -


Second Edition Jos Dirksen

https://textbookfull.com/product/learning-three-js-the-
javascript-3d-library-for-webgl-second-edition-jos-dirksen/

textbookfull.com

How to Integrate It A Practical Guide to Finding


Elementary Integrals 1st Edition Seã¡N M. Stewart

https://textbookfull.com/product/how-to-integrate-it-a-practical-
guide-to-finding-elementary-integrals-1st-edition-sean-m-stewart/

textbookfull.com
Captured by her Alien Mate A science fiction romance
Warriors of the D tali Book 4 1st Edition Ava York &
Starr Huntress [York
https://textbookfull.com/product/captured-by-her-alien-mate-a-science-
fiction-romance-warriors-of-the-d-tali-book-4-1st-edition-ava-york-
starr-huntress-york/
textbookfull.com

SQL Easy SQL Programming Database Management for Beginners


Your Step By Step Guide to Learning the SQL Database Felix
Alvaro
https://textbookfull.com/product/sql-easy-sql-programming-database-
management-for-beginners-your-step-by-step-guide-to-learning-the-sql-
database-felix-alvaro/
textbookfull.com

The Men on Magic Carpets Searching for the Superhuman


Sports Star 1st Edition Ed Hawkins

https://textbookfull.com/product/the-men-on-magic-carpets-searching-
for-the-superhuman-sports-star-1st-edition-ed-hawkins/

textbookfull.com

Preparing the Public Health Workforce Educational Pathways


for the Field and the Classroom 1st Edition Rosemary M.
Caron (Auth.)
https://textbookfull.com/product/preparing-the-public-health-
workforce-educational-pathways-for-the-field-and-the-classroom-1st-
edition-rosemary-m-caron-auth/
textbookfull.com

Flexible Working in Organisations A Research Overview


Lilian M De Menezes

https://textbookfull.com/product/flexible-working-in-organisations-a-
research-overview-lilian-m-de-menezes/

textbookfull.com
EASA Module 11A B1 Turbine Aeroplane Aerodynamics
Structures and Systems 4th Edition Aircraft Technical Book
Company Llc
https://textbookfull.com/product/easa-module-11a-b1-turbine-aeroplane-
aerodynamics-structures-and-systems-4th-edition-aircraft-technical-
book-company-llc/
textbookfull.com
AR and VR
Using the
WebXR API
Learn to Create Immersive Content
with WebGL, Three.js, and A-Frame

Rakesh Baruah
AR and VR Using the
WebXR API
Learn to Create Immersive
Content with WebGL, Three.js,
and A-Frame

Rakesh Baruah
AR and VR Using the WebXR API
Rakesh Baruah
Brookfield, WI, USA

ISBN-13 (pbk): 978-1-4842-6317-4    ISBN-13 (electronic): 978-1-4842-6318-1 


https://doi.org/10.1007/978-1-4842-6318-1

Copyright © 2021 by Rakesh Baruah


This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or
part of the material is concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way,
and transmission or information storage and retrieval, electronic adaptation, computer software,
or by similar or dissimilar methodology now known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark
symbol with every occurrence of a trademarked name, logo, or image we use the names, logos,
and images only in an editorial fashion and to the benefit of the trademark owner, with no
intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if
they are not identified as such, is not to be taken as an expression of opinion as to whether or not
they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of
publication, neither the authors nor the editors nor the publisher can accept any legal
responsibility for any errors or omissions that may be made. The publisher makes no warranty,
express or implied, with respect to the material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Spandana Chatterjee
Development Editor: James Markham
Coordinating Editor: Divya Modi
Cover designed by eStudioCalamar
Cover image designed by Pixabay
Distributed to the book trade worldwide by Springer Science+Business Media New York, 1
New York Plaza, Suite 4600, New York, NY 10004-1562, USA. Phone 1-800-SPRINGER, fax (201)
348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media,
LLC is a California LLC and the sole member (owner) is Springer Science + Business Media
Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail booktranslations@springernature.com; for
reprint, paperback, or audio rights, please e-mail bookpermissions@springernature.com.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook
versions and licenses are also available for most titles. For more information, reference our Print
and eBook Bulk Sales web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is
available to readers on GitHub via the book’s product page, located at www.apress.com/
978-1-4842-6317-4. For more detailed information, please visit www.apress.com/source-code.
Printed on acid-free paper
To Mom & Dad for boundless patience, love, and support
Table of Contents
About the Author��������������������������������������������������������������������������������xv

About the Technical Reviewer����������������������������������������������������������xvii


Acknowledgments�����������������������������������������������������������������������������xix
Introduction���������������������������������������������������������������������������������������xxi

Chapter 1: Getting Started��������������������������������������������������������������������1


WebGL�������������������������������������������������������������������������������������������������������������������2
The Browser����������������������������������������������������������������������������������������������������3
The Render Engine������������������������������������������������������������������������������������������5
Buffers������������������������������������������������������������������������������������������������������������������6
The Graphics Processing Unit�������������������������������������������������������������������������������6
The Present Future������������������������������������������������������������������������������������������������8
Tooling Up�������������������������������������������������������������������������������������������������������������8
A Code Editor��������������������������������������������������������������������������������������������������������8
Hardware���������������������������������������������������������������������������������������������������������9
Platforms���������������������������������������������������������������������������������������������������������9
Local Web Server for Development���������������������������������������������������������������������10
Live Server VS Extension by Ritwick Dey������������������������������������������������������10
NodeJS http-server Package from NPM��������������������������������������������������������11
Python HTTP server module��������������������������������������������������������������������������11
Servez— A Simple Web Server for Local Web Development������������������������11

v
Table of Contents

A Web Browser Compatible with the WebXR API������������������������������������������������12


XR Device������������������������������������������������������������������������������������������������������13
WebXR Emulator��������������������������������������������������������������������������������������������13
Summary������������������������������������������������������������������������������������������������������������14

Chapter 2: Up and Running with WebGL���������������������������������������������17


The Form and Function of HTML�������������������������������������������������������������������������18
The Canvas����������������������������������������������������������������������������������������������������������20
Exercise 1: Your First WebGL Application������������������������������������������������������������20
A Reference to a Canvas�������������������������������������������������������������������������������������21
The WebGL Context���������������������������������������������������������������������������������������������24
Drawing on the WebGL Context���������������������������������������������������������������������25
Resizing the Canvas��������������������������������������������������������������������������������������26
Shaders���������������������������������������������������������������������������������������������������������������28
Source�����������������������������������������������������������������������������������������������������������28
Compiling������������������������������������������������������������������������������������������������������30
Linking�����������������������������������������������������������������������������������������������������������31
Buffers����������������������������������������������������������������������������������������������������������������32
Setting Vertex Positions���������������������������������������������������������������������������������32
Connecting Shaders with Buffers������������������������������������������������������������������34
Drawing���������������������������������������������������������������������������������������������������������������36
Resolution������������������������������������������������������������������������������������������������������38
Modes of Drawing�����������������������������������������������������������������������������������������39
Summary������������������������������������������������������������������������������������������������������������42

Chapter 3: Toward the Third Dimension in WebGL������������������������������43


The ABCs of XYZ��������������������������������������������������������������������������������������������������44
Exercise 2, Part 1: Painting in the Third Dimension��������������������������������������������45
The WebGL Pipeline���������������������������������������������������������������������������������������46

vi
Table of Contents

Setup�������������������������������������������������������������������������������������������������������������48
A Separation of Concerns������������������������������������������������������������������������������50
An Array of Possibilities���������������������������������������������������������������������������������51
Literally Speaking������������������������������������������������������������������������������������������53
Move the Pointer�������������������������������������������������������������������������������������������54
Calling the Drawing Mode�����������������������������������������������������������������������������55
Exercise 2, Part 2: Squares Squared�������������������������������������������������������������������58
Z-Town�����������������������������������������������������������������������������������������������������������59
A Second Color����������������������������������������������������������������������������������������������62
Exercise 2, Part 3: Three Sides for Three Dimensions�����������������������������������������69
More Shapes, More Vertices, More Coordinates��������������������������������������������70
Math Magic����������������������������������������������������������������������������������������������������72
Summary������������������������������������������������������������������������������������������������������������72

Chapter 4: Matrices, Transformations, and Perspective in WebGL�����75


A Box of Maps�����������������������������������������������������������������������������������������������������76
What You May Have Missed in Algebra 2������������������������������������������������������������80
Translation�����������������������������������������������������������������������������������������������������80
Scaling�����������������������������������������������������������������������������������������������������������82
Rotation���������������������������������������������������������������������������������������������������������84
From Many into One��������������������������������������������������������������������������������������������91
GPUs and Matrices Sitting In a Tree . . .��������������������������������������������������������������92
Exercise 3, Part 1: Matrix Revolution������������������������������������������������������������������93
Import GLMatrix.js�����������������������������������������������������������������������������������������94
Uniforms in Shaders��������������������������������������������������������������������������������������96
The Order of Floperations������������������������������������������������������������������������������97
Making Memories of Matrices�����������������������������������������������������������������������99
Order in the Import��������������������������������������������������������������������������������������101

vii
Table of Contents

Who Am I?���������������������������������������������������������������������������������������������������101
Making Moves with Matrices����������������������������������������������������������������������102
Animation����������������������������������������������������������������������������������������������������103
Animation Loop��������������������������������������������������������������������������������������������108
Part 1 Recap������������������������������������������������������������������������������������������������111
Orthographic and Perspective Matrix Projections���������������������������������������������112
The View Frustum����������������������������������������������������������������������������������������113
Exercise 3, Part 2: A Change in Perspective������������������������������������������������114
Part 2 Recap������������������������������������������������������������������������������������������������119
Summary����������������������������������������������������������������������������������������������������������120

Chapter 5: Diving into Three.js���������������������������������������������������������123


What Is Three.js?�����������������������������������������������������������������������������������������������124
A Synthesizer for Shapes����������������������������������������������������������������������������124
WebGL but Simpler��������������������������������������������������������������������������������������125
Exercise 4, Part 1: Remix the Matrix�����������������������������������������������������������������125
Download the Three.js Source Code������������������������������������������������������������126
A Detour into ES Modules����������������������������������������������������������������������������126
Making a Context�����������������������������������������������������������������������������������������129
Making a Camera����������������������������������������������������������������������������������������129
Making a Scene�������������������������������������������������������������������������������������������131
Geometry�����������������������������������������������������������������������������������������������������131
Material�������������������������������������������������������������������������������������������������������132
Meshes��������������������������������������������������������������������������������������������������������133
Rendering Animation�����������������������������������������������������������������������������������134
Painted Black�����������������������������������������������������������������������������������������������135
Let Var Be Light�������������������������������������������������������������������������������������������135
Pixel Perfect������������������������������������������������������������������������������������������������136
Part 1 Recap������������������������������������������������������������������������������������������������138

viii
Table of Contents

Exercise 4, Part 2: Materials, Textures��������������������������������������������������������������139


Sphere Geometry�����������������������������������������������������������������������������������������139
Lambert Material�����������������������������������������������������������������������������������������140
Textures�������������������������������������������������������������������������������������������������������142
Three.js TextureLoader��������������������������������������������������������������������������������144
The Lighting Model��������������������������������������������������������������������������������������146
Part 2 Recap������������������������������������������������������������������������������������������������153
Exercise 4, Part 3: Fog, Backgrounds, Ambient Lights, and Normal Maps��������153
Scene Background��������������������������������������������������������������������������������������154
Fog���������������������������������������������������������������������������������������������������������������154
Applying a Normal Map�������������������������������������������������������������������������������156
Mipmapping�������������������������������������������������������������������������������������������������160
Anisotropy���������������������������������������������������������������������������������������������������161
Normal Mapping the Plane��������������������������������������������������������������������������163
Ambient Light����������������������������������������������������������������������������������������������165
Animation with Parametric Equations���������������������������������������������������������166
Part 3 Recap������������������������������������������������������������������������������������������������168
Summary����������������������������������������������������������������������������������������������������������168

Chapter 6: Entering VR Through WebXR�������������������������������������������171


Setting Up the Debug Environment�������������������������������������������������������������������172
Debugging WebXR on an Oculus Quest�������������������������������������������������������172
Running a Demo from the Immersive Web�������������������������������������������������������176
Preparing Our Scene for Immersive VR�������������������������������������������������������������178
Life Cycle of a WebXR Application���������������������������������������������������������������178
Exercise 5, Part 1: Creating an XR Session Through the WebXR API�����������������180
Stage 1: Is WebXR Supported?��������������������������������������������������������������������180
Stage 2: Advertise XR Functionality to the User������������������������������������������185

ix
Table of Contents

Stage 3: Enable a User Activation Event������������������������������������������������������186


Stage 4: Request an XR Session������������������������������������������������������������������187
Part 1 Recap������������������������������������������������������������������������������������������������191
Exercise 5, Part 2: Scope, Closure, a Module, and a Singleton��������������������192
WebXRManager in Three.js��������������������������������������������������������������������������192
Scope�����������������������������������������������������������������������������������������������������������193
Closure��������������������������������������������������������������������������������������������������������201
Part 2 Recap������������������������������������������������������������������������������������������������208
Exercise 5, Part 3: The Homestretch�����������������������������������������������������������������208
Enable Port Forwarding from a Local Development Server
to a VR Device����������������������������������������������������������������������������������������������211
Part 3 Recap������������������������������������������������������������������������������������������������213
Summary����������������������������������������������������������������������������������������������������������214

Chapter 7: Creating an Augmented Reality Website with


Three.js and the WebXR API�������������������������������������������������������������217
Exercise 6, Part 1: The Floating Cube����������������������������������������������������������������218
Spatial Tracking in WebXR���������������������������������������������������������������������������219
Install Three.js Through Node and the Node Package Manager������������������220
Outline the Life Cycle of the Application������������������������������������������������������222
Load the Scene Components�����������������������������������������������������������������������224
Write the Body of the Initialize Function������������������������������������������������������226
Write the Body of the Button’s Event Listener���������������������������������������������228
Start the AR Session������������������������������������������������������������������������������������230
Change the Button Element’s State�������������������������������������������������������������231
Save a Reference to the XR Session�����������������������������������������������������������232
Set the XR Session’s XR WebGL Layer Property to Three.js Rendering
Context��������������������������������������������������������������������������������������������������������232
Set the XR Session’s Reference Space for AR���������������������������������������������234

x
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
Table of Contents

Set the Three.js XR Manager’s XR Session Property


to the Current XR Session����������������������������������������������������������������������������235
Call the animate( ) Function�������������������������������������������������������������������������235
Call Three.js’ SetAnimationLoop( ) with the render( ) Function Set
as Its Callback���������������������������������������������������������������������������������������������236
Create an Event Handling Function for the End of a Session����������������������237
Create a Function to Reset the State of the Application������������������������������237
Part 1 Recap������������������������������������������������������������������������������������������������238
Exercise 6, Part 2: The Hit Test��������������������������������������������������������������������������239
Controllers and Events��������������������������������������������������������������������������������240
Create the Reticle����������������������������������������������������������������������������������������243
Move XR Query Function�����������������������������������������������������������������������������244
WebXR Spatial Anchors Module������������������������������������������������������������������247
Running the Scene��������������������������������������������������������������������������������������249
Part 2 Recap������������������������������������������������������������������������������������������������250
Summary����������������������������������������������������������������������������������������������������������251

Chapter 8: Building VR for the Web with A-Frame����������������������������253


A Review So Far������������������������������������������������������������������������������������������������253
What Is A-Frame?���������������������������������������������������������������������������������������������255
Exercise 7, Part 1: The Bare Bones of A-Frame�������������������������������������������������255
Installation���������������������������������������������������������������������������������������������������256
Abstraction FTW!�����������������������������������������������������������������������������������������256
Abstraction Takes Some L’s�������������������������������������������������������������������������257
The Entity Component System��������������������������������������������������������������������257
A-Frame: An Entity Component System-Based Framework for Three.js�����259
The Entity�����������������������������������������������������������������������������������������������������260
The Component�������������������������������������������������������������������������������������������261
Primitives�����������������������������������������������������������������������������������������������������262

xi
Table of Contents

Systems�������������������������������������������������������������������������������������������������������263
Part 1 Recap������������������������������������������������������������������������������������������������264
Using Three.js in A-Frame���������������������������������������������������������������������������������265
Exercise 7, Part 2: Three.js and A-Frame Entities���������������������������������������������265
Through the Window������������������������������������������������������������������������������������266
Three.js Properties in A-Frame��������������������������������������������������������������������266
Access the DOM API������������������������������������������������������������������������������������267
Three.js Groups and getObject3D( )�������������������������������������������������������������268
Run the Scene���������������������������������������������������������������������������������������������269
Part 2 Recap������������������������������������������������������������������������������������������������269
Custom Components in A-Frame����������������������������������������������������������������������270
Exercise 7, Part 3: Build a Custom A-Frame Component����������������������������������270
Setup�����������������������������������������������������������������������������������������������������������271
registerComponent( )�����������������������������������������������������������������������������������271
Referencing Component Data From Inside the Component������������������������273
Add Custom Component to Entity����������������������������������������������������������������274
Three.js Properties Through Custom Components��������������������������������������275
‘this.el’���������������������������������������������������������������������������������������������������������276
Run the Scene���������������������������������������������������������������������������������������������277
Part 3 Recap������������������������������������������������������������������������������������������������278
Two Birds, One Component�������������������������������������������������������������������������������278
Exercise 7, Part 4: Greener Pastures�����������������������������������������������������������������279
Add the Custom Component to a Plane Entity���������������������������������������������280
Add a Custom Component Attribute������������������������������������������������������������280
Component Diversity Through Logic������������������������������������������������������������281
The Lighting Model Persists������������������������������������������������������������������������284

xii
Table of Contents

Fog as Component���������������������������������������������������������������������������������������284
Part 4 Recap������������������������������������������������������������������������������������������������285
Summary����������������������������������������������������������������������������������������������������������286

Chapter 9: Physics and User Interaction in A-Frame�����������������������289


Where’s the Game Engine?�������������������������������������������������������������������������������290
Exercise 8, Part 1: Importing a Ready-Made Physics System into A-Frame�����291
Install A-Frame and Systems�����������������������������������������������������������������������291
A-Frame Developer Ecosystem�������������������������������������������������������������������292
A-Frame Physics System�����������������������������������������������������������������������������292
Load a System to a Scene Entity�����������������������������������������������������������������292
Add Physics Properties to Entities���������������������������������������������������������������293
HTTP vs. HTTPS�������������������������������������������������������������������������������������������294
Part 1 Recap������������������������������������������������������������������������������������������������295
Exercise 8, Part 2: Hands On�����������������������������������������������������������������������������296
Super Hands������������������������������������������������������������������������������������������������296
Touch-Controller Components���������������������������������������������������������������������297
A-Frame Physics Extra System�������������������������������������������������������������������298
Run the Scene���������������������������������������������������������������������������������������������300
Part 2 Recap������������������������������������������������������������������������������������������������301
Summary����������������������������������������������������������������������������������������������������������301

Chapter 10: Deploying 3D Animated Models in AR with


A-Frame and GitHub Pages���������������������������������������������������������������303
HTTPS and XR Testing���������������������������������������������������������������������������������������304
GitHub����������������������������������������������������������������������������������������������������������305
Exercise 9, Part 1: Upload a GLTF Model to A-Frame and
Publish to GitHub Pages������������������������������������������������������������������������������������306
Set Up GitHub����������������������������������������������������������������������������������������������306
GLTF Assets�������������������������������������������������������������������������������������������������308

xiii
Table of Contents

GLTF-Model Entity Component��������������������������������������������������������������������309


Run the Scene���������������������������������������������������������������������������������������������310
Part 1 Recap������������������������������������������������������������������������������������������������311
Exercise 9, Part 2: Animating GLTF Models in A-Frame�������������������������������������311
A-Frame Extras��������������������������������������������������������������������������������������������312
Animation-Mixer Component�����������������������������������������������������������������������313
Relative Transforms�������������������������������������������������������������������������������������313
Run the Scene���������������������������������������������������������������������������������������������314
Part 2 Recap������������������������������������������������������������������������������������������������314
Chapter Summary���������������������������������������������������������������������������������������������315
Conclusion��������������������������������������������������������������������������������������������������������317

Index�������������������������������������������������������������������������������������������������319

xiv
About the Author
Rakesh Baruah is a writer and creator with 15
years of experience in new media, film, and
television in New York City. After completing
an MFA in screenwriting and directing for film
from Columbia University, Rakesh joined the
writers’ room of a hit, primetime, network
drama as an assistant. The experience opened
his eyes to the limits of television and the
opportunities promised by 3D, immersive
content. In 2016 he began a self-guided
journey toward mixed reality design that has
taken him through startups, boot camps, the Microsoft offices, and many,
many hours in front of a computer. He is the author of one previous book
on virtual reality and the Unity Game Engine and has received an Nvidia-
certified nanodegree in Computer Vision. He currently teaches high school
computer science in Milwaukee, WI. He shares what he’s learned with
you in a style and format designed specifically for the person who, in high
school, preferred English class to Trigonometry.

xv
About the Technical Reviewer
Yogendra Sharma is a developer with
experience in architecture, design, and
development of scalable and distributed
applications, with a core interest in
Microservices and DevOps. He is currently
working as an IoT and Cloud Architect at
Intelizign Engineering Services Pvt Pune. He
also has hands-on experience in technologies
such as AR/VR, CAD CAM, Simulation,
AWS, IoT, Python, J2SE, J2EE, NodeJS, VueJs,
Angular, MongoDB, and Docker. He constantly
explores technical novelties, and he is open-
minded and eager to learn about new technologies and frameworks. He
has reviewed several books and video courses published by Packt and
Apress.

xvii
Acknowledgments
Deep thanks to the members of the Immersive Web Working Group for
their support of the WebXR API. To Brandon Jones, Nell, Manish, and
others whom I only know through Twitter, thank you for the attention you
put into the documentation for the WebXR API and all of its features. Mr.
Doob, thanks go to you and your compatriots for creating and maintaining
Three.js. To the team at Google Chrome Labs, thank you for evangelizing
the promise of augmented reality on the Web. To Mozilla and all who have
called it an employer, thank you for everything you have done to help
make the Web a more inclusive, democratic space. Thank you to the team
members at Mozilla Mixed Reality, Mozilla Hubs, MDN, and A-Frame for
creating, supporting, and maintaining the tools to make mobile mixed
reality an opportunity for everyone in the world. An incredibly special
thank you to my team at Apress for their tireless devotion to my project.
Spandana Chatterjee, thank you for your support and concern for all
things book related and not. James Markham, thank you for the guidance
you have provided for each chapter. To Yogendra Sharma, my technical
editor, thank you for keen eyes and a sharp mind that kept me honest. And
finally, thank you to my primary editor, Divya Modi, for whom this is my
second book. Divya, thank you for the prompt responses, clarifications,
follow-ups, and forwards that made collaborating remotely a smooth,
fruitful experience.

xix
Introduction
This book is a resource to help you become familiar with the tools to create
mobile mixed reality for the Web. On July 24, 2020 the World Wide Web
Consortium, the international standards organization for the World Wide
Web, published its most recent version, as of this writing, of the WebXR
API specification. The specification describes how Web browsers can
implement support for virtual and augmented reality devices, including
headsets and sensors, on the Web. The first iteration of the specification
appeared in 2017 as the WebVR API. However, in 2018 the expansion of use
cases for VR and AR on the Web prompted the Immersive Web Working
Group—made up of contributors from Google, Microsoft, Mozilla, and
elsewhere—to overhaul WebVR in favor of an API designed to embrace
what the future of mixed reality may offer. By June of 2020, at least four
of the leading Web browsers, including Google Chrome, Microsoft Edge,
Mozilla Firefox, and Oculus Browser, provided support for the WebXR API.
As WebXR is a new, evolving specification, resources for its
development are sparse. In this book I have created a pathway to help you
prepare for the future of mobile, mixed reality development. By the book’s
end you will be familiar with the most common tools used for WebXR
development today. These tools include Visual Studio Code, WebGL,
Three.js, and A-Frame. Familiarity with HTML, CSS, and JavaScript is not
required to benefit from the lessons in this book.
What follows is a road map for the rest of the course. Chapter 1
introduces the concepts behind the WebXR API as well as the tools you
may need to begin developing mobile, immersive applications. Chapter 2
places us at the point of origin for 3D graphics on the Web, WebGL. By
creating simple projects with WebGL, HTML, and JavaScript, you will

xxi
Introduction

quickly learn the fundamentals of how the WebXR API works inside a
browser. In Chapter 3 we remain with WebGL, as its bare-bones syntax
makes clear the ins and outs of the graphics rendering pipeline that
connects server, client, and GPU. Chapter 4 builds on the preceding two
chapters, culminating with an explanation of linear algebra through
WebGL. The simple, yet important, principles of linear algebra covered
in Chapter 4 provide the suggested groundwork for a deep dive into
immersive Web development with the 3D JavaScript library, Three.js, in
Chapter 5. With a thorough understanding of the WebGL pipeline and
the convenience created by the Three.js library, you will create a virtual
reality project on your local machine and load it into a VR-capable device
through the Internet via the WebXR API in Chapter 6. Chapter 7 moves the
focus from virtual reality to augmented reality programming with Three.
js. Using the features of the WebXR API’s Augmented Reality module,
Chapter 7 provides steps toward creating mobile AR experiences that
include animation and user interaction. Chapter 8 returns to the topic of
virtual reality to introduce the use of A-Frame, a framework for creating
mobile XR experiences using Three.js. Both Chapters 9 and 10 remain with
A-Frame, as Chapter 9 explains how to implement real-world physics and
user interaction in a VR scene through the WebXR API’s implementation
of the Gamepad API, also built into many browsers. Finally, Chapter 10
provides instruction on how to import 3D models into A-Frame, animate
them, and view them in augmented reality through GitHub Pages.
The WebXR API is poised to become a useful tool for XR and Web
developers alike. As the lines between mobile and native, augmented
and virtual blur, applications that make use of both 2D and immersive
technologies will become more common. I have created the lessons
inside this book with the intent to help you join the growing community
of developers designing experiences for the immersive Web. No prior
experience with Web development or 3D programming is assumed. As
the WebXR API is such a new technology, more seasoned developers
may also benefit from the instruction contained within. As the future of

xxii
Introduction

Web development moves into a third dimension and the principles of


game development move on to the Web, more opportunities will open up
for creative minds to forge the language of the new Internet. I hope you,
empowered with the lessons in this course, will be among those leading
the charge.

xxiii
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
CHAPTER 1

Getting Started
WebXR is not a programming language; it’s not even a library of code we
can access to create our apps. WebXR is a specification developed by the
World Wide Web Consortium, W3C, a nonprofit group of industry experts
who collaborate to create standard protocols across the Web. The W3C
has left the implementation of the WebXR guidelines to the developers
of browsers. WebXR, therefore, is nothing more than a set of rules agreed
upon by industry.
Not to be confused with the WebXR specification, the WebXR API is
an implementation of the WebXR feature set. The WebXR API serves as
an interface between XR Web content and the devices on which they run.
For example, the WebXR API collects data regarding the orientation of a
headset and a user’s pose. The WebXR API provides developers access to
user data through its library of commands.
Yet, the WebXR Device API does have important limitations: it can’t
manage 3D data or draw anything to a screen. The WebXR API is not a
rendering engine. It cannot load models, wrap them in textures, and paint
them to pixels—a process known as rasterization. To rasterize 3D content
in a browser, the WebXR API extends another API called WebGL.
Following an introduction to the components integral to the use of the
WebXR API, we will discuss the tools we need to create XR applications of
our own. The tools required for creating WebXR applications are a code
editor, a local development server, a Web browser, and an XR device.
Developers without access to an XR device may use the WebXR Emulator
provided by browser creators like Mozilla. All of these are discussed in a
later section of this chapter.
© Rakesh Baruah 2021 1
R. Baruah, AR and VR Using the WebXR API,
https://doi.org/10.1007/978-1-4842-6318-1_1
Chapter 1 Getting Started

A thorough understanding of how the WebXR API builds upon the


fundamental features of the Web browser will make understanding the
tools we will use later in the course, such as the Three.js JavaScript library
and the A-Frame framework, an easier process. By preparing ourselves
with an understanding of the WebXR API from the ground up and a
knowledge of how the tools we will use will impact the development of our
WebXR apps, we will guarantee that we are best prepared to meet whatever
advancements the WebXR API may release in the future.
In this chapter you will:

• Learn the origin and purpose of WebGL

• Briefly cover the role of JavaScript in the history of the


Web browser

• Learn the purpose of the browser’s rendering engine

• Learn the role played by buffers in XR applications

• Learn the value that graphics processing units (GPUs)


offer to creating and running XR apps

• Survey the tools needed to create WebXR applications

• Cover the system requirements for the use of these tools


• Come to understand the suite of technologies used
throughout this course

WebGL
WebGL is a Web graphics library available through a JavaScript API in all
contemporary Web browsers. Like the WebXR API, the WebGL API also
conforms to a specification. The specification for WebGL, however, is
not maintained by the W3C, but by a different consortium known as the
Kronos Group. Comprising over 150 leading technology companies, the

2
Chapter 1 Getting Started

Kronos group promotes advanced Web standards for graphics, mixed


reality, and machine learning applications. One among their many visual
computing APIs is the OpenGL graphics standard.
The OpenGL graphics standard specifies a protocol for communication
between an application and the drivers of a GPU, such as those made by
Nvidia and AMD. While OpenGL is compatible across machines, platform-
specific APIs like Microsoft’s DirectX and Apple’s Metal also exist. However,
OpenGL’s cross-platform applicability has made its younger cousin, OpenGL
ES, a popular graphics API to implement on mobile devices. The ES in
OpenGL ES stands for “embedded systems,” which means the API targets
small, low-power devices. As these devices cannot avail themselves of the
big GPUs you can find in a desktop gaming computer, for example, they
require a graphics API dedicated to their specific needs.
OpenGL ES’ ability to operate on mobile devices allows WebGL to
create 2D and 3D graphics in Web browsers running on stand-alone
headsets and smartphones. It is the Kronos Group’s specification for
OpenGL ES that informs the implementation of the WebGL API. While the
communication between applications and GPUs still requires the use of
GLSL, the language of OpenGL’s rendering and drawing commands, the
WebGL API enables Web developers to blend GLSL with a language they
are much more comfortable with, JavaScript. After all, JavaScript is the
language of the Web, and the Web is the domain of the browser.

The Browser
The Web browser as we know it today really came of age in 1995 with the
release of Netscape Navigator. Though Netscape eventually succumbed to
the industry leviathan of Microsoft’s Internet Explorer, its legacy continues
to inform the nature of the Web. But Netscape wasn’t even the first publicly
used Web browser. That distinction belongs to an earlier iteration of
Navigator called Mosaic. In fact, Navigator and its predecessor had been
around since 1993. What, then, happened in 1995 to mark the year as a
watershed moment in the browser wars?
3
Chapter 1 Getting Started

JavaScript happened. While developing Navigator, Netscape sought


a scripting language to use inside its browser. Originally, developers at
Netscape wanted a programming language that embraced the object-­
oriented paradigm (OOP) of Java. However, the OOP nature of Java proved
ill-fitting for the needs of the browser. Looking for outside help, Netscape
recruited software engineer Brendan Eich to implement a version of the
Scheme programming language for the browser. For better or worse, the
minimalist dialect of Scheme didn’t appeal to the larger community of
developers who preferred Java’s OOP approach to software design. Looking
for a compromise, Netscape brass asked Eich to strike a balance between
the structure of Java and the flexibility of Scheme. As the apocryphal story
goes, Eich developed what came to be known as JavaScript over the course
of just 10 days.
Eich’s intent with JavaScript was to “touch the page.” By any measure
Eich succeeded, as JavaScript is one of the most popular programming
languages used worldwide. Web developers have used JavaScript and
members of its family like AJAX and JQuery for decades to create Web
applications increasingly more responsive to user feedback. With the
arrival of Node.js, JavaScript leapt from the front end to the server-side back
end of Web development, an arena once exclusively dominated by more
established languages like C and C++. JavaScript’s flexibility has made it a
go-to language for many developers interested in designing for the full stack.
But its efficacy may not be more apparent than in the Web browser, where its
extensibility allows for the creation of streaming XR content.
The browser is literally our window into the World Wide Web. One
need not do more than execute the function window.onLoad() in a
JavaScript file to understand what I mean. Really, though, the Web browser
is less a window than a wall. It doesn’t allow us to peer into the Web.
Rather, it brings the Web into our homes, onto our tablets and our phones,
by painting the contents of the Web onto the screens of our devices. About
60 times a second a Web browser repaints itself to create the illusion of a
world that we surf with keyboard strokes and mouse clicks. The core of a

4
Chapter 1 Getting Started

Web browser’s functionality is its ability to render remote content to our


screens. The source of this power is the product of one of its two main
engines.

The Render Engine


Two engines make up the modern Web browser application. One is
the JavaScript engine, such as Chrome’s V8 engine, which manages
the compilation of JavaScript code. The other is the engine of primary
importance to us, at this point in our journey. That engine is the one
responsible for rendering content delivered from a server to our screens.
When information arrives at our Internet-connected devices, it passes
through the many protocol layers of the network specification before
appearing inside our browsing window. Data leaves a server wrapped in
layers of instructions that communicate to each node on the network how
to route data to its target. Layer by layer is stripped away by network nodes
until the data packet reaches the machine of the client who requested it.
If the header of the data packet matches what the browser expects,
then the browser gets to work refitting the data to appear on our screen as
it began at its source. Employing its ability to parse the packet’s content,
the browser builds a page from the syntax of its HTML document. While
the JavaScript engine attends to the demands of the website’s JavaScript
modules, the browser’s rendering engine digs into the layout and
compositing instructions described through HTML and CSS. When the
rendering engine is through laying out the elements of a page and painting
them in the order they appear on the screen, we, the user of the client
browser, will have barely noticed that any time has passed at all.
But how exactly does a browser understand where on our screens it
should draw certain shapes or tint certain pixels? Sure, a designer has
included the instruction set for a page’s appearance in HTML and CSS,
but what if a user scrolls? Enters a character into a form? Or presses play
on a video? A browser requires a place to store in memory the content it

5
Random documents with unrelated
content Scribd suggests to you:
the pool. The “herring” had been in, for there was a dead one lying
on the bottom of weed, a golden fish silted over with fine mud.
Suddenly, on chancing to look bay-ward, I saw a small school of
“herring” just off the mouth of the brook and scarce more than fifteen
feet from the motionless rim of the tide. There were, perhaps, fifty or
a hundred fish in the school. Occasional fins chopped the quiet
water. “Herrings” of Eastham brook unable to enter the pond in which
they were born, barred from it by a dam of Nature’s making. As I
stood looking off to the baffled creatures, now huddled and
seemingly still in deeper water, now huddled and all astir in the
shallowest fringes of the tide, I began to reflect on Nature’s
eagerness to sow life everywhere, to fill the planet with it, to crowd
with it the earth, the air, and the seas. Into every empty corner, into
all forgotten things and nooks, Nature struggles to pour life, pouring
life into the dead, life into life itself. That immense, overwhelming,
relentless, burning ardency of Nature for the stir of life! And all these
her creatures, even as these thwarted lives, what travail, what
hunger and cold, what bruising and slow-killing struggle will they not
endure to accomplish the earth’s purpose? and what conscious
resolution of men can equal their impersonal, their congregate will to
yield self life to the will of life universal?
The tide ebbed, swiftly shallowing over the flats, the “herring”
vanished from sight like a reflection from a glass; I could not tell
when they were gone or the manner of their going.
Returning to the outer beach late in the afternoon, I found the
ocean all a cold jade-green sown with whitecaps, the wind rising,
and great broken clouds flowing over from the east. And in this
northern current was a new warmth.
Chapter VIII
NIGHT ON THE GREAT BEACH

I
Our fantastic civilization has fallen out of touch with many aspects
of nature, and with none more completely than with night. Primitive
folk, gathered at a cave mouth round a fire, do not fear night; they
fear, rather, the energies and creatures to whom night gives power;
we of the age of the machines, having delivered ourselves of
nocturnal enemies, now have a dislike of night itself. With lights and
ever more lights, we drive the holiness and beauty of night back to
the forests and the sea; the little villages, the crossroads even, will
have none of it. Are modern folk, perhaps, afraid of night? Do they
fear that vast serenity, the mystery of infinite space, the austerity of
stars? Having made themselves at home in a civilization obsessed
with power, which explains its whole world in terms of energy, do
they fear at night for their dull acquiescence and the pattern of their
beliefs? Be the answer what it will, to-day’s civilization is full of
people who have not the slightest notion of the character or the
poetry of night, who have never even seen night. Yet to live thus, to
know only artificial night, is as absurd and evil as to know only
artificial day.
Night is very beautiful on this great beach. It is the true other half
of the day’s tremendous wheel; no lights without meaning stab or
trouble it; it is beauty, it is fulfilment, it is rest. Thin clouds float in
these heavens, islands of obscurity in a splendour of space and
stars: the Milky Way bridges earth and ocean; the beach resolves
itself into a unity of form, its summer lagoons, its slopes and uplands
merging; against the western sky and the falling bow of sun rise the
silent and superb undulations of the dunes.
My nights are at their darkest when a dense fog streams in from
the sea under a black, unbroken floor of cloud. Such nights are rare,
but are most to be expected when fog gathers off the coast in early
summer; this last Wednesday night was the darkest I have known.
Between ten o’clock and two in the morning three vessels stranded
on the outer beach—a fisherman, a four-masted schooner, and a
beam trawler. The fisherman and the schooner have been towed off,
but the trawler, they say, is still ashore.
I went down to the beach that night just after ten o’clock. So utterly
black, pitch dark it was, and so thick with moisture and trailing
showers, that there was no sign whatever of the beam of Nauset; the
sea was only a sound, and when I reached the edge of the surf the
dunes themselves had disappeared behind. I stood as isolate in that
immensity of rain and night as I might have stood in interplanetary
space. The sea was troubled and noisy, and when I opened the
darkness with an outlined cone of light from my electric torch I saw
that the waves were washing up green coils of sea grass, all coldly
wet and bright in the motionless and unnatural radiance. Far off a
single ship was groaning its way along the shoals. The fog was
compact of the finest moisture; passing by, it spun itself into my lens
of light like a kind of strange, aërial, and liquid silk. Effin Chalke, the
new coast guard, passed me going north, and told me that he had
had news at the halfway house of the schooner at Cahoon’s.
It was dark, pitch dark to my eye, yet complete darkness, I
imagine, is exceedingly rare, perhaps unknown in outer nature. The
nearest natural approximation to it is probably the gloom of forest
country buried in night and cloud. Dark as the night was here, there
was still light on the surface of the planet. Standing on the shelving
beach, with the surf breaking at my feet, I could see the endless wild
uprush, slide, and withdrawal of the sea’s white rim of foam. The
men at Nauset tell me that on such nights they follow along this
vague crawl of whiteness, trusting to habit and a sixth sense to warn
them of their approach to the halfway house.
Animals descend by starlight to the beach. North, beyond the
dunes, muskrats forsake the cliff and nose about in the driftwood and
weed, leaving intricate trails and figure eights to be obliterated by the
day; the lesser folk—the mice, the occasional small sand-coloured
toads, the burrowing moles—keep to the upper beach and leave
their tiny footprints under the overhanging wall. In autumn skunks,
beset by a shrinking larder, go beach combing early in the night. The
animal is by preference a clean feeder and turns up his nose at
rankness. I almost stepped on a big fellow one night as I was
walking north to meet the first man south from Nauset. There was a
scamper, and the creature ran up the beach from under my feet;
alarmed he certainly was, yet was he contained and continent. Deer
are frequently seen, especially north of the light. I find their tracks
upon the summer dunes.
Years ago, while camping on this beach north of Nauset, I went for
a stroll along the top of the cliff at break of dawn. Though the path
followed close enough along the edge, the beach below was often
hidden, and I looked directly from the height to the flush of sunrise at
sea. Presently the path, turning, approached the brink of the earth
precipice, and on the beach below, in the cool, wet rosiness of dawn,
I saw three deer playing. They frolicked, rose on their hind legs,
scampered off, and returned again, and were merry. Just before
sunrise they trotted off north together down the beach toward a
hollow in the cliff and the path that climbs it.
Occasionally a sea creature visits the shore at night. Lone coast
guardsmen, trudging the sand at some deserted hour, have been
startled by seals. One man fell flat on a creature’s back, and it drew
away from under him, flippering toward the sea, with a sound
“halfway between a squeal and a bark.” I myself once had rather a
start. It was long after sundown, the light dying and uncertain, and I
was walking home on the top level of the beach and close along the
slope descending to the ebbing tide. A little more than halfway to the
Fo’castle a huge unexpected something suddenly writhed horribly in
the darkness under my bare foot. I had stepped on a skate left
stranded by some recent crest of surf, and my weight had
momentarily annoyed it back to life.
The Highland Light
Facing north, the beam of Nauset becomes part of the dune night.
As I walk toward it, I see the lantern, now as a star of light which
waxes and wanes three mathematic times, now as a lovely pale flare
of light behind the rounded summits of the dunes. The changes in
the atmosphere change the colour of the beam; it is now whitish,
now flame golden, now golden red; it changes its form as well, from
a star to a blare of light, from a blare of light to a cone of radiance
sweeping a circumference of fog. To the west of Nauset I often see
the apocalyptic flash of the great light at the Highland reflected on
the clouds or even on the moisture in the starlit air, and, seeing it, I
often think of the pleasant hours I have spent there when George
and Mary Smith were at the light and I had the good fortune to visit
as their guest. Instead of going to sleep in the room under the eaves,
I would lie awake, looking out of a window to the great spokes of
light revolving as solemnly as a part of the universe.
All night long the lights of coastwise vessels pass at sea, green
lights going south, red lights moving north. Fishing schooners and
flounder draggers anchor two or three miles out, and keep a bright
riding light burning on the mast. I see them come to anchor at
sundown, but I rarely see them go, for they are off at dawn. When
busy at night, these fishermen illumine their decks with a scatter of
oil flares. From shore, the ships might be thought afire. I have
watched the scene through a night glass. I could see no smoke, only
the waving flares, the reddish radiance on sail and rigging, an edge
of reflection overside, and the enormous night and sea beyond.
One July night, as I returned at three o’clock from an expedition
north, the whole night, in one strange, burning instant, turned into a
phantom day. I stopped and, questioning, stared about. An
enormous meteor, the largest I have ever seen, was consuming itself
in an effulgence of light west of the zenith. Beach and dune and
ocean appeared out of nothing, shadowless and motionless, a
landscape whose every tremor and vibration were stilled, a
landscape in a dream.
The beach at night has a voice all its own, a sound in fullest
harmony with its spirit and mood—with its little, dry noise of sand
forever moving, with its solemn, overspilling, rhythmic seas, with its
eternity of stars that sometimes seem to hang down like lamps from
the high heavens—and that sound the piping of a bird. As I walk the
beach in early summer my solitary coming disturbs it on its nest, and
it flies away, troubled, invisible, piping its sweet, plaintive cry. The
bird I write of is the piping plover, Charadrius melodus, sometimes
called the beach plover or the mourning bird. Its note is a whistled
syllable, the loveliest musical note, I think, sounded by any North
Atlantic bird.
Now that summer is here I often cook myself a camp supper on
the beach. Beyond the crackling, salt-yellow driftwood flame, over
the pyramid of barrel staves, broken boards, and old sticks all atwist
with climbing fire, the unseen ocean thunders and booms, the
breaker sounding hollow as it falls. The wall of the sand cliff behind,
with its rim of grass and withering roots, its sandy crumblings and
erosions, stands gilded with flame; wind cries over it; a covey of
sandpipers pass between the ocean and the fire. There are stars,
and to the south Scorpio hangs curving down the sky with ringed
Saturn shining in his claw.
Learn to reverence night and to put away the vulgar fear of it, for,
with the banishment of night from the experience of man, there
vanishes as well a religious emotion, a poetic mood, which gives
depth to the adventure of humanity. By day, space is one with the
earth and with man—it is his sun that is shining, his clouds that are
floating past; at night, space is his no more. When the great earth,
abandoning day, rolls up the deeps of the heavens and the universe,
a new door opens for the human spirit, and there are few so
clownish that some awareness of the mystery of being does not
touch them as they gaze. For a moment of night we have a glimpse
of ourselves and of our world islanded in its stream of stars—pilgrims
of mortality, voyaging between horizons across eternal seas of space
and time. Fugitive though the instant be, the spirit of man is, during
it, ennobled by a genuine moment of emotional dignity, and poetry
makes its own both the human spirit and experience.

II
At intervals during the summer, often enough when the tides are
high and the moon is near the full, the surf along the beach turns
from a churn of empty moonlit water to a mass of panic life. Driven in
by schools of larger fish, swarms of little fish enter the tumble of the
surf, the eaters follow them, the surf catches them both up and
throws them, mauled and confused, ashore.
Under a sailing moon, the whole churn of sea close off the beach
vibrates with a primeval ferocity and intensity of life; yet is this war of
rushing mouth and living food without a sound save for the breaking
of the seas. But let me tell of such a night.
I had spent an afternoon ashore with friends, and they had driven
me to Nauset Station just after nine o’clock. The moon, two days
from the full, was very lovely on the moors and on the channels and
flat, moon-green isles of the lagoon; the wind was southerly and
light. Moved by its own enormous rhythms, the surf that night was a
stately incoming of high, serried waves, the last wave alone
breaking. This inmost wave broke heavily in a smother and rebound
of sandy foam, and thin sheets of seethe, racing before it up the
beach, vanished endlessly into the endless thirst of the sands. As I
neared the surf rim to begin my walk to the southward, I saw that the
beach close along the breakers, as far as the eye would reach, was
curiously atwinkle in the moonlight with the convulsive dance of
myriads of tiny fish. The breakers were spilling them on the sands;
the surf was aswarm with the creatures; it was indeed, for the time
being, a surf of life. And this surf of life was breaking for miles along
the Cape.
Little herring or mackerel? Sand eels? I picked a dancer out of the
slide and held him up to the moon. It was the familiar sand eel or
sand launce, Ammodytes americanus, of the waters between
Hatteras and Labrador. This is no kin of the true eels, though he
rather resembles one in general appearance, for his body is slender,
eel-like, and round. Instead of ending bluntly, however, this “eel” has
a large, well-forked tail. The fish in the surf were two and three
inches long.
Homeward that night I walked barefooted in the surf, watching the
convulsive, twinkling dance, now and then feeling the squirm of a
fish across my toes. Presently something occurred which made me
keep to the thinnest edge of the foam. Some ten feet ahead, an
enormous dogfish was suddenly borne up the beach on the rim of a
slide of foam; he moved with it unresisting while it carried him; the
slide withdrawing and drying up, it rolled him twice over seaward; he
then twisted heavily, and another minor slide carried him back again
to shore. The fish was about three feet long, a real junior shark,
purplish black in the increasing light—for the moon was moving west
across the long axis of the breakers—and his dark, important bulk
seemed strange in the bright dance of the smaller fish about him.
It was then that I began to look carefully at the width of gathering
seas. Here were the greater fish, the mouths, the eaters who had
driven the “eels” ashore to the edge of their world and into ours. The
surf was alive with dogfish, aswarm with them, with the rush, the cold
bellies, the twist and tear of their wolfish violence of life. Yet there
was but little sign of it in the waters—a rare fin slicing past, and once
the odd and instant glimpse of a fish embedded like a fly in amber in
the bright, overturning volute of a wave.
Too far in, the dogfish were now in the grip of the surf, and
presently began to come ashore. As I walked the next half mile every
other breaker seemed to leave behind its ebb a mauled and
stranded sharklet feebly sculling with his tail. I kicked many back into
the seas, risking a toe, perhaps; some I caught by the tails and flung,
for I did not want them corrupting on the beach. The next morning, in
the mile and three quarters between the Fo’castle and the station, I
counted seventy-one dogfish lying dead on the upper beach. There
were also a dozen or two skates—the skate is really a kind of shark
—which had stranded the same night. Skates follow in many things,
and are forever being flung upon these sands.
I sat up late that night at the Fo’castle, often putting down the book
I read to return to the beach.
A little after eleven came Bill Eldredge to the door, with a grin on
his face and one hand held behind his back. “Have you ordered to-
morrow’s dinner yet?” said he. “No.” “Well, here it is,” and Bill
produced a fine cod from behind his back. “Just found him right in
front of your door, alive and flopping. Yes, yes, haddock and cod
often chase those sand eels in with the bigger fish; often find them
on the beach about this time of the year. Got any place to keep him?
Let me have a piece of string and I’ll hang him on your clothesline.
He’ll keep all right.” With a deft unforking of two fingers, Bill drew the
line through the gills, and as he did so the heavy fish flopped noisily.
No fear about him being dead. Make a nice chowder. Bill stepped
outside; I heard him at the clothesline. Afterward we talked till it was
time for him to shoulder his clock and Coston case again, pick up his
watch cap, whistle in his little black dog, and go down over the dune
to the beach and Nauset Station.
The Sequel of Fog on a Summer Night
There were nights in June when there was phosphorescence in
the surf and on the beach, and one such night I think I shall
remember as the most strange and beautiful of all the year.
Early this summer the middle beach moulded itself into a bar, and
between it and the dunes are long, shallow runnels into which the
ocean spills over at high tide. On the night I write of, the first quarter
of the moon hung in the west, and its light on the sheets of incoming
tide coursing thin across the bar was very beautiful to see. Just after
sundown I walked to Nauset with friends who had been with me
during the afternoon; the tide was still rising, and a current running in
the pools. I lingered at the station with my friends till the last of
sunset had died, and the light upon the planet, which had been
moonlight mingled with sunset pink, had cleared to pure cold moon.
Southward, then, I turned, and because the flooded runnels were
deep close by the station, I could not cross them and had to walk
their inner shores. The tide had fallen half a foot, perhaps, but the
breakers were still leaping up against the bar as against a wall, the
greater ones still spilling over sheets of vanishing foam.
It grew darker with the westing of the moon. There was light on the
western tops of the dunes, a fainter light on the lower beach and the
breakers; the face of the dunes was a unity of dusk.
The tide had ebbed in the pools, and their edges were wet and
dark. There was a strange contrast between the still levels of the
pool and the seethe of the sea. I kept close to the land edge of the
lagoons, and as I advanced my boots kicked wet spatters of sand
ahead as they might have kicked particles of snow. Every spatter
was a crumb of phosphorescence; I walked in a dust of stars. Behind
me, in my footprints, luminous patches burned. With the double-ebb
moonlight and tide, the deepening brims of the pools took shape in
smouldering, wet fire. So strangely did the luminous speckles
smoulder and die and glow that it seemed as if some wind were
passing, by whose breath they were kindled and extinguished.
Occasional whole breakers of phosphorescence rolled in out of the
vague sea—the whole wave one ghostly motion, one creamy light—
and, breaking against the bar, flung up pale sprays of fire.
A strange thing happens here during these luminous tides. The
phosphorescence is itself a mass of life, sometimes protozoan its
origin, sometimes bacterial, the phosphorescence I write of being
probably the latter. Once this living light has seeped into the beach,
colonies of it speedily invade the tissues of the ten thousand
thousand sand fleas which are forever hopping on this edge of
ocean. Within an hour the grey bodies of these swarming
amphipods, these useful, ever hungry sea scavengers (Orchestia
agilis; Talorchestia megalophthalma), show phosphorescent
pinpoints, and these points grow and unite till the whole creature is
luminous. The attack is really a disease, an infection of light. The
process had already begun when I arrived on the beach on the night
of which I am writing, and the luminous fleas hopping off before my
boots were an extraordinary sight. It was curious to see them hop
from the pool rims to the upper beach, paling as they reached the
width of peaceful moonlight lying landward of the strange, crawling
beauty of the pools. This infection kills them, I think; at least, I have
often found the larger creature lying dead on the fringe of the beach,
his huge porcelain eyes and water-grey body one core of living fire.
Round and about him, disregarding, ten thousand kinsmen, carrying
on life and the plan of life, ate of the bounty of the tide.
III
All winter long I slept on a couch in my larger room, but with the
coming of warm weather I have put my bedroom in order—I used it
as a kind of storage space during the cold season—and returned to
my old and rather rusty iron cot. Every once in a while, however,
moved by some obscure mood, I lift off the bedclothing and make up
the couch again for a few nights. I like the seven windows of the
larger room, and the sense one may have there of being almost out-
of-doors. My couch stands alongside the two front windows, and
from my pillow I can look out to sea and watch the passing lights, the
stars rising over ocean, the swaying lanterns of the anchored
fishermen, and the white spill of the surf whose long sound fills the
quiet of the dunes.
Ever since my coming I have wanted to see a thunderstorm bear
down upon this elemental coast. A thunderstorm is a “tempest” on
the Cape. The quoted word, as Shakespeare used it, means
lightning and thunder, and it is in this old and beautiful Elizabethan
sense that the word is used in Eastham. When a schoolboy in the
Orleans or the Wellfleet High reads the Shakespearean play, its title
means to him exactly what it meant to the man from Stratford;
elsewhere in America, the terms seems to mean anything from a
tornado to a blizzard. I imagine that this old significance of the word
is now to be found only in certain parts of England and Cape Cod.
On the night of the June tempest, I was sleeping in my larger
room, the windows were open, and the first low roll of thunder
opened my eyes. It had been very still when I went to bed, but now a
wind from the west-nor’west was blowing through the windows in a
strong and steady current, and as I closed them there was lightning
to the west and far away. I looked at my watch; it was just after one
o’clock. Then came a time of waiting in the darkness, long minutes
broken by more thunder, and intervals of quiet in which I heard a
faintest sound of light surf upon the beach. Suddenly the heavens
cracked open in an immense instant of pinkish-violet lightning. My
seven windows filled with the violent, inhuman light, and I had a
glimpse of the great, solitary dunes staringly empty of familiar
shadows; a tremendous crash then mingled with the withdrawal of
the light, and echoes of thunder rumbled away and grew faint in a
returning rush of darkness. A moment after, rain began to fall gently
as if someone had just released its flow, a blessed sound on a roof
of wooden shingles, and one I have loved ever since I was a child.
From a gentle patter the sound of the rain grew swiftly to a drumming
roar, and with the rain came the chuckling of water from the eaves.
The tempest was crossing the Cape, striking at the ancient land on
its way to the heavens above the sea.
Now came flash after stabbing flash amid a roaring of rain, and
heavy thunder that rolled on till its last echoes were swallowed up in
vast detonations which jarred the walls. Houses were struck that
night in Eastham village. My lonely world, full of lightning and rain,
was strange to look upon. I do not share the usual fear of lightning,
but that night there came over me, for the first and last time of all my
solitary year, a sense of isolation and remoteness from my kind. I
remember that I stood up, watching, in the middle of the room. On
the great marshes the lightning surfaced the winding channels with a
metallic splendour and arrest of motion, all very strange through
windows blurred by rain. Under the violences of light the great dunes
took on a kind of elemental passivity, the quiet of earth enchanted
into stone, and as I watched them appear and plunge back into a
darkness that had an intensity of its own I felt, as never before, a
sense of the vast time, of the thousands of cyclic and uncounted
years which had passed since these giants had risen from the dark
ocean at their feet and given themselves to the wind and the bright
day.
Fantastic things were visible at sea. Beaten down by the rain, and
sheltered by the Cape itself from the river of west wind, the offshore
brim of ocean remained unusually calm. The tide was about halfway
up the beach, and rising, and long parallels of low waves, forming
close inshore, were curling over and breaking placidly along the
lonely, rain-drenched miles. The intense crackling flares and
quiverings of the storm, moving out to sea, illumined every inch of
the beach and the plain of the Atlantic, all save the hollow bellies of
the little breakers, which were shielded from the light by their
overcurling crests. The effect was dramatic and strangely beautiful,
for what one saw was a bright ocean rimmed with parallel bands of
blackest advancing darkness, each one melting back to light as the
wave toppled down upon the beach in foam.
Stars came out after the storm, and when I woke again before
sunrise I found the heavens and the earth rainwashed, cool, and
clear. Saturn and the Scorpion were setting, but Jupiter was riding
the zenith and paling on his throne. The tide was low in the marsh
channels; the gulls had scarcely stirred upon their gravel banks and
bars. Suddenly, thus wandering about, I disturbed a song sparrow on
her nest. She flew to the roof of my house, grasped the ridgepole,
and turned about, apprehensive, inquiring ... ’tsiped her
monosyllable of alarm. Then back toward her nest she flew, alighted
in a plum bush, and, reassured at last, trilled out a morning song.

Piping Plover at Nest


Chapter IX
THE YEAR AT HIGH TIDE

I
Had I room in this book, I should like to write a whole chapter on
the sense of smell, for all my life long I have had of that sense an
individual enjoyment. To my mind, we live too completely by the eye.
I like a good smell—the smell of a freshly ploughed field on a warm
morning after a night of April rain, the clovelike aroma of our wild
Cape Cod pinks, the morning perfume of lilacs showery with dew,
the good reek of hot salt grass and low tide blowing from these
meadows late on summer afternoons.
What a stench modern civilization breathes, and how have we
ever learned to endure that foul blue air? In the Seventeenth
Century, the air about a city must have been much the same air as
overhung a large village; to-day the town atmosphere is to be
endured only by the new synthetic man.
Our whole English tradition neglects smell. In English, the nose is
still something of an indelicate organ, and I am not so sure that its
use is not regarded as somewhat sensual. Our literary pictures, our
poetic landscapes are things to hang on the mind’s wall, things for
the eye. French letters are more indulgent to the nose; one can
scarcely read ten lines of any French verse without encountering the
omnipresent, the inevitable parfum. And here the French are right,
for though the eye is the human master sense and chief æsthetic
gate, the creation of a mood or of a moment of earth poetry is a rite
for which other senses may be properly invoked. Of all such appeals
to sensory recollection, none are more powerful, none open a wider
door in the brain than an appeal to the nose. It is a sense that every
lover of the elemental world ought to use, and, using, enjoy. We
ought to keep all senses vibrant and alive. Had we done so, we
should never have built a civilization which outrages them, which so
outrages them, indeed, that a vicious circle has been established
and the dull sense grown duller.
One reason for my love of this great beach is that, living here, I
dwell in a world that has a good natural smell, that is full of keen,
vivid, and interesting savours and fragrances. I have them at their
best, perhaps, when hot days are dulled with a warm rain. So well do
I know them, indeed, that were I blindfolded and led about the
summer beach, I think I could tell on what part of it I was at any
moment standing. At the ocean’s very edge the air is almost always
cool—cold even—and delicately moist with surf spray and the
endless dissolution of the innumerable bubbles of the foam slides;
the wet sand slope beneath exhales a cool savour of mingling beach
and sea, and the innermost breakers push ahead of them puffs of
this fragrant air. It is a singular experience to walk this brim of ocean
when the wind is blowing almost directly down the beach, but now
veering a point toward the dunes, now a point toward the sea. For
twenty feet a humid and tropical exhalation of hot, wet sand encircles
one, and from this one steps, as through a door, into as many yards
of mid-September. In a point of time, one goes from Central America
to Maine.
Atop the broad eight-foot back of the summer bar, inland forty feet
or so from the edge of low tide, other odours wait. Here have the
tides strewn a moist tableland with lumpy tangles, wisps, and matted
festoons of ocean vegetation—with common sea grass, with
rockweed olive-green and rockweed olive-brown, with the crushed
and wrinkled green leaves of sea lettuce, with edible, purple-red
dulse and bleached sea moss, with slimy and gelatinous cords
seven and eight feet long. In the hot noontide they lie, slowly, slowly
withering—for their very substance is water—and sending an odour
of ocean and vegetation into the burning air. I like this good natural
savour. Sometimes a dead, surf-trapped fish, perhaps a dead skate
curling up in the heat, adds to this odour of vegetation a faint fishy
rankness, but the smell is not earth corruption, and the scavengers
of the beach soon enough remove the cause.
Beyond the bar and the tidal runnel farther in, the flat region I call
the upper beach runs back to the shadeless bastion of the dunes. In
summer this beach is rarely covered by the tides. Here lies a hot and
pleasant odour of sand. I find myself an angle of shade slanting off
from a mass of wreckage still embedded in a dune, take up a handful
of the dry, bright sand, sift it slowly through my fingers, and note how
the heat brings out the fine, sharp, stony smell of it. There is weed
here, too, well buried in the dry sand—flotsam of last month’s high,
full-moon tides. In the shadowless glare, the topmost fronds and
heart-shaped air sacs have ripened to an odd iodine orange and a
blackish iodine brown. Overwhelmed thus by sand and heat, the
aroma of this foliage has dissolved; only a shower will summon it
again from these crisping, strangely coloured leaves.

Nesting Tern
Cool breath of eastern ocean, the aroma of beach vegetation in
the sun, the hot, pungent exhalation of fine sand—these mingled are
the midsummer savour of the beach.

II
In my open, treeless world, the year is at flood tide. All day long
and all night long, for four days and five days, the southwest wind
blows across the Cape with the tireless constancy of a planetary
river. The sun, descending the altar of the year, pauses ritually on
the steps of the summer months, the disk of flame overflowing. On
hot days the beach is tremulous with rising, visible heat bent
seaward by the wind; a blue haze hangs inland over the moors and
the great marsh blotting out pictorial individualities and reducing the
landscape to a mass. Dune days are sometimes hotter than village
days, for the naked glare of sand reflects the heat; dune nights are
always cooler. On its sun-trodden sand, between the marsh wind
and the coolness of ocean, the Fo’castle has been as comfortable as
a ship at sea.
The duneland air burns with the smell of sand, ocean, and sun. On
the tops of the hills, the grass stands at its tallest and greenest, its
new straw-green seed plumes rising through a dead crop of last
year’s withered spears. On some leaves there is already a tiny spot
of orange wither at the very tip, and thin lines of wither descending
on either edge. Grasses in the salt meadows are fruiting; there are
brownish and greenish-yellow patches on the levels of summer
green. On the dunes, the sand lies quiescent in a tangle of grass; in
naked places, it lies as if it were held down by the sun. When there
has been no rain for a week or more, and the slanting flame has
been heavy on the beach, the sand in my path down Fo’castle dune
becomes so dry, so loose and deep, that I trudge through it as
through snow.
The winter sea was a mirror in a cold, half-lighted room, the
summer sea is a mirror in a room burning with light. So abundant is
the light and so huge the mirror that the whole of a summer day
floats reflected on the glass. Colours gather there, sunrise and
twilight, cloud shadows and cloud reflections, the pewter dullness of
gathering rain, the blue, burning splendour of space swept free of
every cloud. Light transfixes ocean, and some warmth steals in with
the light, but the waves that glint in the sun are still a tingling cold.
Now do insects inherit the warm earth. When a sluggish wind
blows from the marsh on a hot day, the dunes can be tropical. The
sand quivers with insect lives. On such days, “greenheads,” Tabanus
costalis, stab and buzz, sand gnats or “no-see-ums” gather in
myriads on the sun-drenched south wall of the house, “flatiron flies”
and minor unknowns swarm to the attack. One must remain indoors
or take a precarious refuge at the ocean’s very edge. Thanks to the
wind, the coolness, and the spray, the lower beach is usually free of
insect bloodletters, though the bullying, poisonous Tabanid, in the
mid-August height of his season, can be a hateful nuisance. So far,
however, I have had but two of these tropical visitations. Barring an
extra allowance of greenheads, the dunes are probably quite as
habitable as any stretch of outermost beach. The wind, moreover,
saves me from mosquitoes.
Ants have appeared, and the upper beach is pitted with their hills; I
watch the tiny, red-brown creatures running in and out of buried
weed. Just outside each hole, the fine sand is all delicately ascrawl
with the small, endless comings and goings. The whole upper beach,
indeed, has become a plain of intense and minute life; there are
tunnels and doors and pitways everywhere. The dune locusts that
were so small in June have grown large and learned to make a
sound. All up and down the dunes, sometimes swept seaward out of
their course by the west wind, go various butterflies. When I turn up
driftwood in the dunes, or walk the wheel ruts in the meadows,
crickets race off into the grass.
On the dunes, in open places near thin grass, I find the deep,
finger-round mine shafts of the dune spider. A foot below, in the
cooler sand, lives the black female; dig her up, and you will find a
hairy, spidery ball. During the summer months the lady does not
leave her cave, but in early autumn she revisits the world and
scuttles through the dune grass, black, fast, and formidable. The
smaller, sand-coloured male runs about everywhere. I saw one on
the beach the other night, running along in cloudy moonlight, and
mistook him at first for a small crab. Later the same night, I found a
tiny, sand-coloured dune toad at the very brim of the surf, and
wondered if an appetite for beach fleas had led him there.
“June bugs,” Lachnosterna arcuata, strike my screens with a
formidable boom and linger there formidably buzzing; let me but
open the door, and half a dozen are tilting at my table lamp and
falling stunned upon the cloth. On mounded slopes of sand, solitary
black wasps scratch themselves out a cave; across my paths move
the shadows of giant dragon flies.
The straggling beach peas of the region are in bloom; the west
wind blows the grass and rushes out to the rippled levels of a level
sea; heat clouds hang motionless on the land horizon, their lower
rims lost in the general haze; the great sun overflows; the year burns
on.

III
I have spoken in another chapter of the melting away of bird life
from this region during April and May. There was a time when the all-
the-year-round herring gulls seemed the only birds left to me, and
many of these were immature birds or birds whose plumage was
then changing from immature brown to adult white and grey. One
cold, foggy morning late in May, I woke to find the beach in front of
the Fo’castle crowded with these gulls, for a number of hake had
stranded during the night, and the birds had discovered them and
come to feed. Some fed on the fresh fish, findings being keepings—I
saw various birds defend their individual repasts from late arrivals
and would-be sharers with a show of wings and a hostile cry—others
stood on the top of the beach in a long, senatorial row facing the
sea. The maturing birds were of all tones of white and brown; some
were chalky and brown, some were speckled like hens, others were
a curious brown-mottled chalky grey. The moults of herring gulls are
complicated affairs. There are spring moults and autumn moults,
partial moults and second nuptial plumages. Not until the third year
or later does the bird seem to assume its full nuptial and adult
coloration.
When I first open my eyes on a bright midsummer morning, the
first sound that becomes part of my waking consciousness is the
recurrent rush and spill of the summer sea; then do I hear a patter of
tiny feet on the roof over my head and the cheerful notes of a song
sparrow’s home-spun tune. These sparrows are the songbirds of the
dunes. I hear them all day long, for I have a pair nesting on the
seaward slope of this dune in a clump of dusty miller. My building of

You might also like