webgl hotsh t - packt publishing · a synopsis of the book’s content . ... such as bricks with...

35
WebGL HOTSH T Mitch Williams Chapter No. 1 "Building Great Web3D"

Upload: buique

Post on 22-Apr-2018

222 views

Category:

Documents


2 download

TRANSCRIPT

WebGL HOTSH T

Mitch Williams

Chapter No. 1 "Building Great Web3D"

In this package, you will find: A Biography of the author of the book

A preview chapter from the book, Chapter NO.1 "Building Great Web3D"

A synopsis of the book’s content

Information on where to buy this book

About the Author Mitch Williams has been involved with 3D graphics programming and Web3D development since its creation in the mid 1990s. He began his career writing software for digital imaging products before moving on as Manager of Software for Vivendi Universal Games. In the late 1990s, he started 3D-Online, his own company, where he created "Dynamic-3D", a Web3D graphics engine. He has worked on various projects ranging from interactive 3D medical procedures, online 3D training for the Department of Defense, creating one of the first 3D mobile games prior to the launch of the iPhone, and graphics card shader language programming. He has been teaching Interactive 3D Media at various universities including UC Berkeley, UC Irvine, and UCLA Extension.

Gratitude and thanks to my family, friends, dogs—past and present, artists, SIGGRAPH, wonderful students, and the great math and engineering teachers who helped me along the way.

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

WebGL HOTSH T Welcome to WebGL Hotshot. Web3D was first introduced about the same time as HTML and web browsers in the early 1990s. VRML 1.0, the Virtual Reality Modeling Language, made its L.A. debut by its co-inventors, Mark Pesce, Tony Parisi, and others, as part of the VR SIG (special interest group) organized by Dave Blackburn at Kit and Sherrie Galloway's Electronic Café (http://www.ecafe.com/), a part of Santa Monica's 18th Street Arts Center (http://18thstreet.org/). Meanwhile, 3D was an emerging entertainment medium as Toy Story was released in 1995 about the same time as Microsoft 's DirectX 3Dgame interface, and a few years after Doom launched, one of the first 3D games. VRML 2.0 adopted the tag style, < >, of HTML a few years later. VRML, however, required either a plugin for your web browser, common at the time with the emergence of real audio and flash, or a pure Java implementation such as Dynamic 3D.

For much of the first decade of this century, the commercial applications of 3D graphics were seen in animated movies, special effects, and video games. Web3D had little visibility and was mostly used in research centers such as the U.S. Naval Postgraduate School in Monterey, California, USC Behavioral Technology Labs, and the Fraunhofer Institute for Computer Graphics in Europe. However, two new technologies were about to bring Web3D into the foreground. XML (eXtensible Markup Language) emerged as the file format and validation system for passing data across the Internet, and shader languages provided the ability to program the GPU (Graphics Processing Unit), which was a significant boost in the performance of 3D graphics.

Behind every technology are innovative, imaginative people. Two organizations, Khronos and the Web3D Consortium, provided the implementation of Web3D to be robust and simple for both developers and artists. Khronos (https://www.khronos.org) is a group of major media-centric technology companies dedicated to creating open standards in computer graphics. Khronos defined WebGL and its adoption among web browser developers to enable interactive Web3D. The Web3D Consortium (http://www.web3d.org) defined X3D, the VRML 2.0-based file format using XML standards.

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

This book will introduce the two leading technologies for interactive Web3D: X3D and WebGL. Emphasis is placed on real-world applications while intertwining technical concepts. We begin with X3D and the fundamental concepts of creating 3D scenes. If you have never built anything in 3D, you'll be amazed at how quickly you can create colorful 3D environments. Then, we transition to WebGL, writing JavaScript to parse the 3D meshes, control the interactivity, and handle the interfacing to the GPU for rendering 3D meshes with texture maps. Then, GPU shader languages are applied to create various lights, free-flowing cloth, and animated waterfalls.

More advanced techniques are then demonstrated, such as integrating WebGL with content from Facebook, the social media site, and with live stock market data to show how 3D can be a more effective means of navigation and communication. We then deploy content from other 3D applications developed by architects and engineers to bring their content to the Web and as an engaging tool for education. Finally, we look at WebGL as art applied to the design of 3D websites to engage audiences like never before.

What This Book Covers Project 1, Building Great Web3D, introduces us to 3D graphics concepts—lights, cameras, 3D meshes, and their placement in 3D space, plus animation with X3D.

Project 2, WebGL for E-Commerce, describes how to build e-commerce sites in 3D using existing assets while introducing WebGL technology including shader programming inside the GPU. Then, we look at the issues and opportunities in building a WebGL 3D e-commerce site.

Project 3, User Experience, Story, Character, Visual Design, and Interactivity, applies shader languages to texture maps in order to create effects such as flags waving in the wind and waterfalls. Then, we will create engaging night scenes with lighting and fog when navigating 3D scenes.

Project 4, Mobile and Web3D Gaming, builds 2D user interfaces in a 3D environment, common in video games. We will then implement features of games such as misdirection to create challenges in games and implement gravity.

Project 5, Social Media Meets Its Destiny, interfaces WebGL with Facebook, the social media website, in order to build 3D interfaces to visit your Facebook friends. Also, we will learn about the Facebook programming interface to expand our applications.

Project 6, 3D Reveals More Information, demonstrates how to display data from a real-time Internet feed such as the stock market in 3D. We then demonstrate techniques to display large amounts of data and show how to navigate into the data so that we can analyze the data for a full year down to a day for a more refined display.

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Project 7, Adapting Architecture, Medical, and Mechanical Engineering to Web3D, discusses the issues and solutions to porting the work of architects and engineers to the Web, given their 3D drawings. We then add the features of 3D renderings, including reflection and refraction of light to simulate windows and transparencies, other materials such as bricks with depth, and multiple cameras in a scene.

Project 8, 3D Websites, revisits X3D to create and navigate 3D websites and create engaging scenes with lighting and normal maps so that surfaces look natural. We then add portals to transport within a 3D website for faster navigation.

Project 9, Education in the Third Dimension, demonstrates how to select a specific chemical element from the periodic chart and then select countries off a wall map, demonstrating how to pick irregular shapes. Finally, we show how 3D graphics can be an effective tool to show math algorithms.

Project 10, The New World of 3D Art, recreates the complex architecture of Chicago's Art Institute, and then invents a new interactive 3D art based on the work of the famous pop artist Roy Lichtenstein.

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Project 1Building Great Web3D

"If I have seen further it is by standing on the shoulders of giants."

– Sir Isaac Newton

Not long a er the introduc on of HTML, 3D for the web was launched. Web3D was a natural extension of exis ng technologies. Already, the fi rst 3D games such as Doom were being launched and computer-generated imagery was being used for special eff ects in movies. Microso 's DirectX game interface (originally known as Game Developers Kit) was launched and a number of 3D modeling programs such as Caligari trueSpace, 3D Studio, and Wavefront were made available to ar sts. In addi on, programming languages such as Java and JavaScript enable web programming and Internet applica ons. Exis ng tools were also being migrated to the Web such as Macromedia's Director through the Shockwave plugin. The Web quickly went beyond just text and sta c images as mul media streamed through RealAudio and RealVideo. The fi rst modems grew from 14.4 to 28.8 and then to 56.6 kb/s. Storage increased from 1 MB fl oppy discs to 700 MB CD-ROMs. Memory disk prices dropped signifi cantly, suppor ng the move from text to imagery. All this was driven by consumers.

A graphical revolu on was taking place. The command-line opera ng system was fi nally giving way to a graphical user interface. Toy Story, the fi rst animated feature fi lm premiered, showed that 3D was a story-telling medium with engaging characters. Moreover, there was a small group of commi ed, talented people with visions of an interac ve Web3D, combined with enthusiasm and dreams of virtual reality. So much was in place for Web3D's growth: fast technology, 3D modeling tools for crea on, and talented people with vision. The fi rst specifi ca on, Virtual Reality Modeling Language (VRML), was also born, although it served as a prototype to the soon-replaced update, VRML 2.0 . Web3D was a small representa ve of the dot-com boom. A mix of startups and technology giants entered the arena with varied engineering approaches. Some opted for their own technology such as Pulse 3D and Ac veworlds, which is s ll ac ve as its name says. Others relied on their own VRML browsers and plugins such as Sony, Microso , and Silicon Graphics.

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Building Great Web3D

10

With me, however, the Web could no longer just be about fun, irrelevant stuff such as live video cameras focused on fi sh tanks. It had to become economically viable, and thus, the more frivolous applica ons gave way to search engines, online banking, and e-commerce. Among them were Yahoo!, Amazon, and America Online. The early pioneers of Web3D and VRML were ahead of their me and deserve acknowledgement for their great work. Their eff orts were not fu le, but Web3D's day would come another me. The public needed the familiar medium of text, photos, and streaming audio and video. Interac ve 3D was fi nding its early adopters elsewhere—gamers—people who embraced new technology for fun.

A second coming3D was basically an entertainment medium used in movies such as Toy Story and Shrek or in video games such as Doom. Game development was rather tedious. Programmers had to create so ware known as drivers for every model of a graphics card, similar to how peripherals today, for instance a printer and a scanner, must have their own driver device. Each video game had its own unique graphic card drivers. The industry needed a be er solu on to interface between video games and graphic cards. Thus, an industry standard interface was born: a set of commands that said "you game developers, build your game using these commands" and "you graphics chip makers, make sure you accept these commands". The end result was that any game could run on any graphics card.

A graphic interface can be thought of as a gas sta on; any car can purchase their gas from any gas sta on. We need not worry about our car only accep ng gas from a par cular vendor. The two leading graphics interfaces at the end of the millennium were Open Graphics Library (OpenGL) (1992) and DirectX (1995). OpenGL was from Silicon Graphics Incorporated (SGI) and was designed for computer graphics in anima on or special eff ects, mostly in movies or commercials. Thus, OpenGL did not require interac vity from the mouse or keyboard to play video games. OpenGL also did not include sound; audio would just be combined with the computer-generated video in a fi lm-edi ng process.

The other graphics interface was DirectX , originally known as Game Developers Kit from Microso . Launched in the early 1990s, DirectX provided addi onal support for programming video games such as interfaces to the mouse, keyboard, and game controllers as well as support to control audio. Game developers could use DirectX to load their 3D models; move and rotate them; specify lights and proper es; and receive mouse, keyboard, and game controller commands.

OpenGL was picked up by Khronos (www.khronos.org), a consor um of graphics and computer companies that insured its growth. Khronos' mission is to create open standards for all compu ng media. It was a broad agenda that incorporated mobile graphics and the Web.

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Project 1

11

Meanwhile, fi le formats also needed an industry standard. It was clear that informa on was being shared among organiza ons, businesses, and over the Internet. There was a need for a worldwide standard for the World Wide Web. XML, eXtensible Markup Language, was launched in the late 1990s. It specifi ed a format to share data and ways to validate whether the format is correct. Each industry would come up with its own standards; the most prevalent was HTML, which adopted the XML standard to become XHTML, a more rigorous standard that enabled a more consistent fi le format.

VRML 2.0 gained stature as a 3D mesh fi le-sharing format and was exported from major 3D modeling programs. Now was the me to jump on the XML bandwagon, and thus, X3D was born. It had the features of VRML but was now in a standardized XML format. VRML and X3D were under the direc on of the Web3D Consor um (http://www.web3d.org/), a group of outstanding, intelligent, dedicated people with a vision and commitment for 3D on the Web. As an XML document, X3D could be extended for specifi c applica ons, such as medical applica ons, computer-aided design (CAD) for mechanical engineers, and avatars. Collada is another fi le format from Khronos with a broader scope for other 3D applica ons, but with X3D, the community is well served.

Comprehensive solutionsKhronos and the Web3D Consor um brought diff erent companies together to produce unifi ed standards and solu ons. An issue with the standards was that companies with vested fi nancial interests in their own technologies would have to compromise and perhaps lose a technical advantage. However, in the long run, we end up with a greater good that has standards, and some companies con nue to support their own features as an extension to these standards. O en, the right path cannot be discovered un l we have tried other unsuccessful paths. We learned a lot in the early days. Remarkably, the early inventors got much of it right, even for the products that had not yet been invented or conceived such as smartphones. Perhaps the only cri cism seemed to be redundancy; there were mul ple commands in OpenGL to accomplish the same func ons. A li le streamlining was in order, and thus, OpenGL ES (Embedded Systems, 2003) gave us a powerful 3D graphics interface for low ba ery power and low-level devices.

Khronos launched WebGL in March 2011, which was supported in Google Chrome, Safari, Firefox, and most recently, Microso 's Internet Explorer. The ongoing evolu on of HTML—the language read by web browsers to display web pages—was producing new standards for HTML5 with the goal of suppor ng mul media and interac vity. 3D and, by associa on, WebGL were a natural fi t to be embedded into HTML5. WebGL did not require a plugin to view 3D inside web pages, and by interfacing with the graphics card, WebGL could deliver high-performance graphics. Programming in JavaScript and Cascading Style Sheets (CSS) were languages familiar to web developers.

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Building Great Web3D

12

Technical breakthroughs are o en a synergy of near-simultaneous events. The Internet had been around for nearly a quarter of a century before 1970, but was not a commercial success. A convergence of hardware and so ware took place. Fax modems became commonplace on most PCs. Netscape, the fi rst web browser, was born. Consumers were introduced to the Internet via AOL (America Online), and while primi ve to today's standards, the graphical user interface was ubiquitous with Windows, introduced years earlier by Macintosh (and Xerox if we wish to be precise). Web3D was undergoing its own technical breakthrough with HTML5, OpenGL ES, X3D, and one more innova on —shader languages—also known as GPU (Graphics Processing Unit) programming.

The earlier versions of OpenGL and the streamlined OpenGL ES used the fi xed-func on pipeline method . A 3D mesh, which is simply a list of ver ces and how they are connected—think of a Rose Parade Float formed with chicken wire—would go through a series of steps known as the 3D graphics pipeline . The pipeline would perform the following tasks:

Transform the object so that it would move (translate), rotate, and scale the 3D object

Transform the object to the camera's point-of-view

Convert the scene into perspec ve view so that it appears on the screen in the same way as we would perceive it with our eye in the real world

Tradi onally, all the programming was done on the CPU, which passed the 3D meshes and object transforma ons to the GPU in order to draw or render the colored dots on the screen. The GPU is simply another computer chip specifi cally designed for this fi nal drawing. It is programmable and its mul processor capability means it can operate on mul ple ver ces simultaneously. Innovators began programming GPUs. Eventually, a formal programming language was designed to program the GPU / shader languages.

Shader languages enabled developers to have fi nite control and programming over each pixel, vertex, light, and text. With the earlier fi xed-func on pipeline, we only controlled the fi nal loca on of the ver ces and let the GPU interpolate between the ver ces to draw the polygons. Now, with shader languages, we can calculate ligh ng, shadows, rough surfaces, and blend texture maps on a pixel-by-pixel basis. A great advantage of GPU programming is that the OpenGL ES standard is shared across many products. So, the same shader language coded on an iPhone works for an Android phone. Finally, all was in place—WebGL overcame the plugin issues of the previous Web3D a empts, X3D would be the latest fi le format based on the XML community standard, and shader languages would give us improved performance and image quality on a pixel-by-pixel basis.

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Project 1

13

Mission briefi ngWe now venture into Web3D by building our fi rst X3D objects . This will also introduce you to the 3D scene graph of how objects are specifi ed; fi rst, they are specifi ed as primi ves, such as boxes and spheres, and then as more complex 3D models built by ar sts. We will also apply textures to these 3D meshes and include cameras, lights, anima on, and interac vity.

Why is it awesome?X3D is a great language to specify a 3D scene without doing any programming. It is also a great learning tool. Best of all, it provides instant gra fi ca on. If you have never created anything in 3D, you will now be able to create something in a few minutes.

Your Hotshot objectives Introduc on to 3D fundamentals

Transforma ons – transla on, rota on, and scaling

Lights, camera, ac on!

Naviga ng between mul ple viewports

Anima on with interpolators

Adding texture maps to 3D meshes

Ligh ng a scene and shading 3D objects with normals

Crea ng an animated Solar System with mul ple cameras for naviga on

Mission checklistMost X3D and WebGL developments require a li le more than what comes on a standard computer—be it a PC, Macintosh, or other device; I would not doubt that one can create and test Web3D on a smartphone or a tablet.

Firefox is the preferred browser for tes ng. Google Chrome will not allow you to read 3D objects off the hard drive due to security restric ons, which require you to upload your 3D objects, texture maps, and WebGL to your website before tes ng. Firefox relaxes these restric ons and will enable you to test your work on your hard drive.

As we dive deeper into Web3D crea on, you may need to confi gure your server to enable MIME types such as .obj for 3D models. You may want to consult your server administrator to check this.

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Building Great Web3D

14

Some websites that are worth bookmarking are as follows:

The Web3D Consor um: This website (http://www.web3d.org/) defi nes the X3D fi le format and has the latest news

X3Dom: This website (http://www.x3dom.org/) has the libraries that are used for our X3D demonstra ons

The Khronos Group: This website (http://www.khronos.org/) is the consor um that oversees the OpenGL specifi ca on and defi nes WebGL

3D-Online: This website (http://www.3D-Online.com) is for book demonstra ons and author contact informa on

Introduction to 3D fundamentalsA picture is worth a thousand words, and this is, a er all, a book on 3D graphics. So, let's get started with the fun stuff ! Two technologies will be demonstrated: WebGL and X3D. WebGL is related to X3D , but X3D is be er to demonstrate simple objects. Since we will be building the Solar System, X3D is be er in order to show the three rota ons of the Earth—the 24-hour day rota on, the seasonal lts, and the 365.25 annual rota on around the Sun. The Moon is a child of the Earth. Wherever the Earth goes, the Moon follows with its own independent rota on around the Earth. To assist the parsing of these X3D fi les, we shall use X3DOM (X3D with the Document Object Model (DOM))—a publicly available program. WebGL, by itself, is ideal to display the 3D mesh, whereas X3D be er represents the connec on between objects. For example, an X3D fi le can show the hierarchy of an animated hand rota ng at the wrist, which is connected to the lower arm that rotates at the elbow, and then the shoulder.

Programming tradi on states that the fi rst program shall be called "Hello World" and simply displays these words. 3D also has "Hello World"; however, it displays the simplest 3D object—a box.

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Project 1

15

A <Box> node is one of the several simple primi ves that are included in X3D; the other shape nodes are <Cone>, <Cylinder>, and <Sphere>. While WebGL is JavaScript programming, X3D looks like HTML tags. So, angular brackets, < and >, will o en be used to describe X3D.

Engage thrustersHowever, we will not cover basic HTML tags, CSS, or JavaScript. There is too much to cover in 3D, and these are be er addressed online. A good source for basic HTML and web programming can be found at http://www.w3schools.com/. Here is our fi rst <Box> shape node used in the following code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"> <head><meta http-equiv="X-UA-Compatible" content="chrome=1" /> <meta http-equiv="Content-Type"content="text/html;charset=utf-8" /> <title>WebGL Hotshots - chapter 01</title><link rel="stylesheet" type="text/css"href="x3dom.css"/> <script type="text/javascript" src="x3dom.js"></script> </head> <body> <X3Dxmlns=http://www.web3d.org/specifications/x3d-namespacewidth="400px" height="400px"><Scene> <Shape> <Appearance> <Material diffuseColor='0.9 0.6 0.3'/> </Appearance> <Box/> </Shape></Scene></X3D></body></html>

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Building Great Web3D

16

Downloading the example codeYou can download the example code fi les for all Packt books you have purchased 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 fi les e-mailed directly to you.

Objective complete – mini debriefi ngBetween the <head> and </head> tags are two references that link this xhtml fi le to the X3DOM JavaScript code, x3dom.js. This code parses the X3D fi le and loads the data onto the graphics card using the OpenGL commands. So, it takes care of a lot of low-level coding, which we will look at later using WebGL. Also, the x3dom.css fi le sets some parameters similar to any CSS fi le. Thus, a basic knowledge of HTML is helpful to develop WebGL. Some of the other tags in the preceding code relate to the valida on process of all XML documents such as the DOCTYPE informa on in the preceding code.

The heart of the ma er begins with the <X3D> tag being embedded into a standard XHTML document. It can also include X3D version informa on, width and height data, and other iden fi ca ons that will be used later. There are also a set of <Scene> and </Scene> tags within which all the 3D data will be contained.

The <Shape> tags contain a single 3D mesh and specify the geometry and appearance of the 3D mesh. Here, we have a single <Box/> tag and the <Appearance> tag, which specifi es either a texture map and/or a <Material> tag that includes several proper es, namely, the diff use color that will be blended with the color of our scene's lights, the emissive or glow simula on color, the object's specular highlights such as a bright spot refl ec ng the Sun on a car's hood, and any transparency. Colors in 3D are the same as those used on the Web—red, green, and blue. Though 3D colors span between 0 and 1, the Web o en uses a hexadecimal number from 0 x 00 through 0 x FF. In the preceding code, the diff use color used is 0.9 red, 0.6 green, and 0.3 blue for a light orange color.

The box also shows some shading with its brightest sides facing us. This is because there is a default headlight in the scene, which is posi oned in the direc on of the camera. This scene has no camera defi ned; in this case, a default camera will be inserted at the posi on (0, 0, 10), which is 10 units towards us along the z axis and points towards the origin (0, 0, 0). If you run this program (which you should), you will be able to rotate the viewpoint (camera) around the origin with the default headlight a ached to the viewpoint. We will address ligh ng later, as ligh ng is a very important and complex part of 3D graphics.

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Project 1

17

Transformations – translation, rotation, and scaling

We are off to a good start. Now, let's add two or more objects. If we don't want everything si ng in the same place, we need a way to posi on the objects in the vast universe of 3D space. The most common way is by using transforma on.

Engage thrustersWe don't alter the original 3D object, but just apply some math to each point in the 3D mesh to rotate, translate (move), and/or scale the object, as follows:

<Scene> <Transform translation="-2 -3 -3" rotation=".6 .8 0 .5"> <Shape> <Appearance> <Material diffuseColor='0.9 0.6 0.3' /> </Appearance> <Box/> </Shape> </Transform> <Transform translation="2 2.5 1" rotation="0 0 1 -.5"> <Shape> <Appearance> <Material diffuseColor='0.3 0.9 0.6' /> </Appearance>

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Building Great Web3D

18

<Cone/> </Shape> </Transform> <Transform translation="-1 0 0" scale=".5 .5 .5"> <Shape> <Appearance> <Material diffuseColor='0.6 0.3 0.9' /> </Appearance> <Cylinder/> </Shape> </Transform> <Transform translation="1 0 0"> <Shape> <Appearance> <Material diffuseColor='0.6 0.3 0.9' /> </Appearance> <Cylinder/> </Shape> </Transform></Scene>

Objective complete – mini debriefi ngEach <Shape> tag is now embedded into a <Transform> tag. The fi rst object, the box, has a transla on of (-2, -3, -3), which moves it two units to the le , three units downwards, and three units backward from the origin. It also has a rota on of (0.6, 0.8, 0, 0.5), which will be discussed in more detail later, but the fi rst three values represent the x, y, and z axes, respec vely, and the fourth value is the angle of rota on in radians (π radians = 180 degrees). Also, note that the sum of the squares of the x, y, and z values equals 1: x2 + y2 + z2 = 1.

The second object is a cone translated two units to the right, 2.5 units upwards, and one unit forward with a rota on of 0.5 radians around the z axis (like the hands of a clock). The third and fourth objects are both cylinders with a uniform 0.5 scale on the le cylinder, which means that it's half its default size. Note that the scale does not need to be the same value for all three axes.

Lights, camera, action!"Lights, camera, ac on!" is an old Hollywood phrase to start fi lming, but it is just as applicable to interac ve 3D graphics. So, let's add lights, cameras, and interac vity to our X3D scenes.

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Project 1

19

Engage thrustersThis scene retains the fi rst two objects created previously and adds a point light that can be thought of as a light bulb—a light from a single point emana ng in all direc ons. We turned off the headlight inside the <NavigationInfo> tag, and at the same me, restricted movement in the scene by se ng type to NONE, simply to introduce this as part of the demo. At the same me, the <Viewpoint> tag or camera is introduced with its default position value, orientation (rota on) value, and fieldOfView value that defaults to π/4, that is, 0.785 radians. The added code is as follows:

<Scene> <NavigationInfo headlight="FALSE" type='"NONE"'/> <PointLight location="0 3 2"/> <Viewpoint position="0 0 10" orientation="0 0 1 0" fieldOfView=".785"/> <Transform …>

The point light is 3 units up and 2 units in front, so it clearly shines on the top of the box and to the le -hand side of the cone but not on the le -hand side of the box or the bo om of the cylinder.

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Building Great Web3D

20

Navigating between multiple viewpoints

3D space is wonderful to travel freely, but we also want specifi c cameras for users and ways to navigate between them. The following fi gure depicts the same scene from three diff erent viewpoints with a single spotlight on the le -hand side of the image along the nega ve x axis poin ng towards the origin (0, 0, 0). The image on the le shows the ini al default camera, the image in the middle shows the view from the le along the x axis from the <Viewpoint> node named vp1, and the image on the right is from the <Viewpoint> node labeled vp2 at a 45-degree angle between the posi ve x axis and the posi ve z axis:

Engage thrustersIn the following code, we have three <Viewpoint> nodes. These cameras are in the id=origin default posi on, the le -hand side of the scene (id=vp1), and at a 45-degree angle on the right (id=vp2). All cameras are facing the origin. Clicking on the <Box> node directs us to go to the camera vp1. Clicking on the cone animates us to <Viewpoint> vp2, and clicking on the small blue <Box> sends us back to our original <Viewpoint>. Note that the order does ma er, although the scene begins with the fi rst <Viewpoint> listed:

<Scene><NavigationInfo headlight="FALSE" type='"NONE"'/><SpotLight location="-5 0 0" direction="0 0 0"/><Viewpoint id="origin" position="0 0 10" orientation="0 0 1 0" fieldOfView=".785"/><Viewpoint id="vp1" orientation="0 1 0 -1.57" position="-12 0 0"></Viewpoint><Viewpoint id="vp2" orientation="0 1 0 .785" position="10 0 10"></Viewpoint><Transform translation="-2 0 -2"> <Shape>

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Project 1

21

<Appearance> <Material diffuseColor='1 0.75 0.5'/> </Appearance> <Box onclick = "document.getElementById('vp1').setAttribute ('set_bind','true');"/> </Shape></Transform><Transform translation="2 2.5 1" rotation="0 0 1 -.5"> <Shape> <Appearance> <Material diffuseColor='0.5 1 0.75'/> </Appearance> <Cone onclick = "document.getElementById('vp2').setAttribute ('set_bind','true');"/> </Shape></Transform><Transform scale=".25 .25 .25"> <Shape> <Appearance> <Material diffuseColor='0 0 0' emissiveColor='0.75 0.5 1' /> </Appearance> <Box onclick = "document.getElementById('origin').setAttribute ('set_bind','true');"/> </Shape></Transform></Scene>

Objective complete – mini debriefi ngThe small <Box> node is placed at the origin for reference. Its diff use color is black and thus is unaff ected by any lights. Instead, its emissive color is light purple, though it does not actually emit light. For this, we would need some addi onal ligh ng objects to give the impression that it glows. The <Box> node also has some familiar JavaScript programming, onclick="document.getElementById('origin'), that HTML web developers have seen while programming interac ve websites. The rest of the line (setAttribute('set_bind','true');) is X3D's way of se ng the viewpoint named origin to be the current or bound camera. Note that the spotlight in the image in the middle does not have a rounded edge that a fl ashlight typically produces. Lights without GPU or shader languages are limited to calcula ng the light at each vertex and interpola ng the light across the polygon. By contrast, shader languages calculate these images on a pixel-by-pixel basis in the GPU's mul processor, so the process is quite fast. We will see more of this and shader languages' contribu on to 3D graphics imagery later.

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Building Great Web3D

22

Animation with interpolatorsAnima on comes in the following forms:

Procedural: This type of anima on is controlled by a program, such as the simula on of a bouncing ball impacted by real-world physics.

Event-driven: This type of anima on includes mo on based on events in the scene, such as a simula on of a dog that sees, smells, hears, and then reacts to it.

Key frame: This type of anima on is where the animated character's movement(s) and rota on(s) occur at specifi c mes. WebGL interpolates between these key frames.

The Moon orbi ng around the Earth, which in turn orbits around the Sun, has a lot of good 3D graphic concepts to review. Note that the Earth's transforma on is inside the Sun's transforma on, and the Moon's transform is contained inside the Earth's transform. Thus, wherever the Earth goes, rota ng around the Sun, the Moon will follow. Also, not only is the Earth 10 units away from the Sun, but it's center is -10 units, which means that the center of the Earth's rota on is the Sun. Now, the Earth also rotates around its own axis for a day; we will show this later. Have a look at the following screenshot:

Engage thrustersLayout the code with all the objects such as the Sun, Earth, and Moon along with all the <Transform> nodes, <TimeSensor> nodes, and interpolators before the ROUTE node. The order is important, just as we must have the <Transform> nodes embedded properly to represent the annual, seasonal, and daily rota ons of the Earth, as shown in the following code:

<Scene><Viewpoint orientation="1 0 0 -.3" position="0 8 30"/> <NavigationInfo headlight="false"/> <PointLight/>

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Project 1

23

<Transform DEF="Sun"> <Shape> <Sphere radius="2.5"/> <Appearance> <Material diffuseColor="1 1 0" emissiveColor="1 .5 0"/> </Appearance> </Shape> <Transform DEF="Earth" center="-10 0 0" translation="10 0 0"> <Shape> <Sphere radius="1.2"/> <Appearance> <Material diffuseColor=".2 .4 .8"/> </Appearance> </Shape> <Transform DEF="Moon" center="-3 0 0" translation="3 0 0"> <Shape> <Sphere radius=".6"/> <Appearance> <Material diffuseColor=".4 .4 .4"/> </Appearance> </Shape> </Transform> </Transform> </Transform> <TimeSensor DEF="yearTimer" cycleInterval="36.5" loop="true"/><OrientationInterpolator DEF="YRotation" key="0 .5 1"keyValue="0 1 0 0 0 1 0 3.14 0 1 0 6.28"/><ROUTE fromField="fraction_changed" fromNode="yearTimer"toField="set_fraction" toNode="YRotation"/><ROUTE fromField="value_changed" fromNode="YRotation"toField="rotation" toNode="Earth"/>

<TimeSensor DEF="moonTimer" cycleInterval="2.9" loop="true"/><OrientationInterpolator DEF="YRotMoon" key="0 .5 1"keyValue="0 1 0 0 0 1 0 3.14 0 1 0 6.28"/><ROUTE fromField="fraction_changed" fromNode="moonTimer"toField="set_fraction" toNode="YRotMoon"/><ROUTE fromField="value_changed" fromNode="YRotMoon"toField="rotation" toNode="Moon"/></Scene>

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Building Great Web3D

24

Objective complete – mini debriefi ngThe <TimeSensor> nodes, interpolators, and the ROUTE nodes create the key frame anima on. The <TimeSensor> node specifi es the dura on (cycleInterval) of the anima on, which is 36.5 seconds here, where each day represents one tenth of a second. Interpolators specify the key and keyValue func ons such that for each key func on, there must be a key value func on. Since this is a rota on or change in orienta on, we use <OrientationInterpolator>. Also, there are <PositionInterpolator> and <ColorInterpolator> nodes that move the 3D mesh and change its color, respec vely, over me. Unlike fi lms, where we have a fi xed 30 frames per second, in real- me anima ons we can have more or less frames per second depending on how complex the scene is and also on the performance of our CPU.

We will break down the interpolator at the three keys when the me equals 0, 0.5, and 1, as follows:

The <OrientationInterpolator> node says that at me = 0, the rota on will be (0, 1, 0, 0), meaning a rota on of 0 radians around the y axis.

At me = 0.5, which is 18.25 seconds (half of 36.5 seconds) here, the rota on will be (0 1 0 3.14) or 3.14 radians, which is 180 degrees around the y axis.

Finally, at me = 1, which is 36.5 seconds, the rota on will be 6.28 radians, which is a full 360-degree circle around the y axis.

So, why do we have to put a midpoint such as 180 degrees? The problem is that the <OrientationInterpolator> node op mizes the rota on distances to be the smallest. For example, a 120-degree rota on clockwise is the same as a 240-degree rota on counter-clockwise. However, the <OrientationInterpolator> node will take the shortest route and rotate 120 degrees clockwise. If you wanted to force a 240-degree counter-clockwise rota on, you'd need to add a midpoint.

Finally, we have to connect the mer to the interpolator with the 3D object that has to be rotated. The ROUTE node directs value(s) from a mer or sensor to another sensor or object. The fi rst ROUTE node takes the output from yearTimer.fraction_changed to YRotation.set_fraction. Note the passing of a frac on value within the ROUTE node. The mer will count from 0 to 36.5 seconds and divide this value by 36.5 so that it is a value between 0 and 1. The orienta on interpolator will receive this frac on value and interpolate between the two key values. For example, at 10 seconds, the frac on is 10/36.5 or 0.274, which is between 0 and 0.5 in the <OrientationInterpolator> node's key. This becomes a key value of (0 1 0 1.72), about 98.63 degrees (1.72 radians * 180 degrees/π).

The next ROUTE node sends the keyValue func on from the <OrientationInterpolator> node and sets the rota on values of the <Transform> node defi ned as Earth, using the DEF="Earth" statement inside the <Transform> node. And with this, we nearly have our Solar System. We just have to add more planets.

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Project 1

25

Adding texture maps to 3D meshesSo far, our objects have been pre y basic shapes and in a single color. That's why they are called primi ves. But of course, 3D objects are far more complex and require the talent of ar sts. Texture maps help us to understand how complex 3D objects are assembled based on simple ones. Have a look at the following fi gure:

Vertex 0(-2, 2, 0)

Vertex 2(2, -2, 0)

Vertex 1(-2, -2, 0)

Engage thrustersA solid colored triangle is the simplest object to draw. I o en suggest drawing objects on paper and labelling the ver ces depending on how they are connected because it can be very tedious to form shapes from memory:

<Shape><Appearance> <Material diffuseColor="1 1 0"/></Appearance> <IndexedFaceSet coordIndex="0 1 2 -1"> <Coordinate point="-2 2 0 -2 -2 0 2 -2 0"/> </IndexedFaceSet></Shape>

Instead of specifying a box or sphere, the shape in the preceding code consists of IndexedFaceSet with three points or ver ces connected in the order listed by coordIndex = "0 1 2 -1". Vertex 0 is connected to vertex 1, vertex 1 is connected to vertex 2, and vertex 2 is connected back to vertex 0. The side that should face us is determined by the right-hand rule. Using your right hand, curve your fi ngers in the order of the ver ces. The direc on of your thumb is the direc on that the polygon faces. So, as you curve your fi ngers counter-clockwise, if your thumb is poin ng towards you, the polygon will be visible to you. The ver ces are connected in a counter-clockwise order.

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Building Great Web3D

26

Let's add a texture map of a wonderful Basset Hound dog with a wet, pink tongue. The camera has been slightly rotated to dis nguish this 3D object from a fl at image. Have a look at the following screenshot:

Have a look at the following code:

<Shape><Appearance><ImageTexture url="./textureMaps/bassethound.jpg"/></Appearance><IndexedFaceSet coordIndex="0 1 2 -1 2 3 0 -1" texCoordIndex="0 1 2 -1 2 3 0 -1"> <Coordinate point="-2 2 0 -2 -2 0 2 -2 0 2 2 0"/> <TextureCoordinate point="0 1 0 0 1 0 1 1"/></IndexedFaceSet></Shape>

In the preceding code, a fourth coordinate point has been added to form two triangles. The IndexedFaceSet coordIndex node now specifi es two triangles. It is preferred to use triangles rather than polygons of four or more ver ces for the same reason that a three-legged chair won't wobble, but a four-legged chair may wobble because one leg may be longer than the others and not sit fl at on the ground. At least this is a nontechnical and noncomplex answer. Three vertex polygons will always be fl at or planer and four vertex polygons can be bent. Addi onally, it's o en just about selec ng a checkbox to export a 3D mesh using only triangles for ar sts.

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Project 1

27

The <Appearance> tag now has an <ImageTexture> node tag instead of a <Material> tag and specifi es an image similar to how HTML would embed an image into a web page. A texture map on a 3D mesh is like hanging wallpaper on a wall. We paste the wallpaper to the corners. We need to align the corners of the walls with the correct corners of the wallpaper; otherwise, the wallpaper gets hung sideways or upside down. The <TextureCoordinate> point specifi es which corner of the texture map is placed at each vertex of the 3D mesh. The lower-le corner of a texture map is (0, 0), and the upper-right corner is (1, 1). The fi rst value is along the x axis, and the second value is along the y axis.

The <TextureCoordinate> point gets aligned to the <Coordinate> point ver ces. For example, the fi rst <Coordinate> point is (-2, 2, 0), which is the upper-le vertex, and the fi rst <TextureCoordinate> point is (0, 1), which is the upper-le corner of the texture map.

The fi nal texture map shows the <TextureTransform> tag, which is o en used for ling (such as repea ng a brick wall pa ern), but it can also be used for shi ing and rota ng images. For example, texture maps can also be animated to create nice water eff ects.

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Building Great Web3D

28

The three images in the preceding screenshot show ling with a texture map of 3 x 2 in the upper-le 3D mesh, rota on of the texture map by 0.2 radians in the image on the right, and transla on of the texture map by -0.3 units to the le and 0.6 units upwards in the image in the lower-le -hand side corner. In the following code, within the <Scene> tags, there are three <Transform> tags, one tag for each <Shape> node, and the <TextureTransform> node:

<Scene><Transform translation="-3 2 -3"><Shape><Appearance><ImageTexture DEF="basset"url="./textureMaps/bassethound.jpg"/><TextureTransform scale="3 2"/></Appearance> <IndexedFaceSet DEF="bassetIFS" coordIndex="0 1 2 -1 2 3 0 -1" texCoordIndex="0 1 2 -1 2 3 0 -1"> <Coordinate point="-2 2 0 -2 -2 0 2 -2 0 2 2 0"/> <TextureCoordinate point="0 1 0 0 1 0 1 1"/> </IndexedFaceSet> </Shape> </Transform> <Transform translation="2 1 -2"> <Shape> <Appearance> <ImageTexture USE="basset"/> <TextureTransform rotation=".2"/> </Appearance> <IndexedFaceSet USE="bassetIFS"/> </Shape> </Transform> <Transform translation="-3 -3 -4"> <Shape> <Appearance> <ImageTexture USE="basset"/> <TextureTransform translation=".3 -.6"/> </Appearance> <IndexedFaceSet USE="bassetIFS"/> </Shape> </Transform></Scene>

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Project 1

29

Objective complete – mini debriefi ngSince each of the 3D meshes shares the same <ImageTexture> and <IndexedFaceSet> nodes, this applica on is a perfect opportunity to use the DEF and USE proper es. Through <DEF> and <USE>, we were able to focus on the capabili es of the <TextureTransform> node.

Lighting a scene and shading 3D objects with normals

One of the great eff ects in 3D graphics is to create surfaces such as a weathered brick wall, the bumpy skin of an orange, or ripples on the surface of water. O en, these surfaces are fl at, but we can blend images together or paint the texture with these bumps. They can even be animated so that water appears to be fl owing, such as in a waterfall. To create this realis c, weathered, and irregular look, we use vertex normals. A normal is simply a three-dimensional vector usually at a right angle to the polygon and o en generated by 3D modeling tools.

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Building Great Web3D

30

Engage thrustersEach of the images in the preceding screenshot of the dog uses the same ligh ng, texture maps, and polygons. They only diff er by their normals. In the upper-le image, the normals are all set to (0, 0, 1), which means that they point right back at the light and thus each corner is fully lit. However, the lower-le image has its normals randomly set and thus does not point back at the light source. The image on the upper-right-hand side has the normal in the top-right corner set 90 degrees away; therefore, this corner appears as a dark spot. Finally, the lower-right image has its normal poin ng at an angle to the light and thus the en re image is dark. The following code contains four <Transform> nodes with iden cal shapes and texture maps, and only diff ers by the vector values in the <Normal> nodes (thus, much of the repeated code has been le out):

<Transform translation="-2.25 2.25 -2"><Shape><Appearance DEF='bassetHoundImage' ><Material diffuseColor='1 1 1' /><ImageTexture url='textureMaps/bassethound.jpg' /></Appearance>

<IndexedFaceSet coordIndex='0 1 2 -1 3 2 1 -1' normalIndex='0 1 2 -1 3 2 1 -1' texCoordIndex='0 1 2 -1 3 2 1 -1' ><Coordinate DEF="coords" point='-2 -2 0, 2 -2 0, -2 2 0, 2 2 0'/> <Normal vector='0 0 1, 0 0 1, 0 0 1, 0 0 1'/> <TextureCoordinate DEF="textureCoord" point='0 0, 1 0, 0 1, 1 1' /> </IndexedFaceSet></Shape></Transform>

<Transform translation="-2.25 -2.25 -2"><Shape> <Appearance USE='bassetHoundImage' /> <IndexedFaceSet coordIndex='0 1 2 -1 3 2 1 -1' normalIndex='0 1 2 -1 3 2 1 -1' texCoordIndex='0 1 2 -1 3 2 1 -1' > <Coordinate USE="coords" /> <Normal vector='-.707 -.5 .5, 0 0 1, -.707 .707 0, 0 .8 .6'/> <TextureCoordinate USE="textureCoord" /> </IndexedFaceSet></Shape></Transform>

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Project 1

31

<Transform translation="-2.25 -2.25 -2">… <Normal vector='0 0 1, 0 0 1, 0 0 1, 1 0 0'/> …</Transform>

<Transform translation="2.25 -2.25 -2">… <Normal vector='.63 .63 .48, .63 .63 .48, .63 .63 .48, .63 .63 .48'/></Transform>

Objective complete – mini debriefi ngOnly the X3D code for the fi rst two images is shown. Using the DEF and USE proper es allows us to share the same <Appearance>, <Coordinate>, and <TextureCoordinate> nodes for each shape. Only the <Normal> node within each <Transform> node for the two textured 3D meshes on the right are shown. Note that the <Normal> vector is a unit value, which means that it has a length of 1; its three-dimensional (x, y, z) values have the property x2 + y2 + z2 = 1.

Normals play a major role in shader languages; they allow you to create a realis c look for complex ligh ng. We shall visit normals later, but let's see one small piece of math here. The amount of light on a polygon at each vertex is calculated by mul plying the (opposite direc on of the) light vector and the normal vector. Both values must be unit values, which means that they should have a length of 1 unit before you mul ply the two vectors. The light vector L can be mul plied with the normal vector N (known as the dot product) as (Lx, Ly, Lz) * (Nx, Ny, Nz) = Lx * Nx + Ly * Ny + Lz * Nz. The value will be between -1 and 1 (inclusive of both), but for any value less than zero, the light will come from behind the object, leaving the vertex in the dark. Incidentally, this amount of light at a vertex is equal to the cosine of the angle between the two vectors. For example, if the angle between the light vector and the normal vector is 30 degrees, then the dot product will equal cosine (30) = 0.866, or about 86.6 percent of the en re amount of light will reach this vertex.

Creating an animated Solar System with multiple cameras for navigation

We conclude this 3D graphics overview with our fi rst applica on, a Solar System with several cameras and planets undergoing mul ple anima ons. First, we will look at the organiza on of these objects in a condensed version of the X3D code (the <IndexedFaceSet> node in the Earth was removed from here since it consists of thousands of values).

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Building Great Web3D

32

Engage thrustersEarth comprises of three <Transform> nodes for its rota on around the Sun, the seasons, and the 24-hour day. Note that in the Earth's outermost transforma on, center (0, 0, 10) is at the same distance from the Sun as the Earth's transla on (0, 0, -10). This is because the center of the Earth's yearly rota on is the Sun. The rota on for the Earth's seasons is around the z axis, set to 0.4 radians or 23 degrees, the actual lt of the Earth. The fi nal inner <Transform> node controls the Earth's daily rota on.

The Moon <Transform> is a child of the Earth's annual rota on. The Moon's rota on is centered on the Earth. Thus, the Moon's transla on is 3 units (3, 0, 0) from the Earth, but its center is 3 units behind (-3, 0, 0). Of course, the Moon is unaff ected by the Earth's seasonal and daily rota on, and thus the Moon's <Transform> node is a child object of the Earth's outermost year <Transform> but not a child of the Earth's seasonal or daily transforma on.

<NavigationInfo headlight="FALSE"/><Viewpoint id="mainCamera" orientation="1 0 0 -.3"position="0 8 30"/><Viewpoint id="aboveCamera" orientation="1 0 0 -1.57"position="0 180 0"/><PointLight/> <Transform DEF="Sun"> <Shape> <Sphere radius="6" onclick = "document.getElementById('aboveCamera') .setAttribute('set_bind','true');"/> <Appearance> <Material diffuseColor="1 1 0" emissiveColor="1 .7 0"/> </Appearance> </Shape> </Transform>

<Viewpoint id="EarthCamera" position=" 0 2 0" orientation="0 1 0 0"/> <Transform DEF="Earth" center="0 0 10"translation="0 0 -10" scale="2 2 2"> <Transform DEF="Earth-Season" rotation="0 0 1 .4"> <Transform DEF="Earth-Day"> <Shape>….IndexedFaceSet and coordinates </Shape> </Transform></Transform>

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Project 1

33

<Transform DEF="Moon" center="-3 0 0"translation="3 0 0"><Shape> <Sphere radius=".6"/> <Appearance> <Material diffuseColor=".4 .4 .4"/> </Appearance></Shape> </Transform> </Transform>

Saturn also has a <Transform> node centered around the Sun and two child <Transform> nodes to control Saturn's day and rings that are constructed from a fl at plane and a texture map with a transparency.

<Viewpoint id="SaturnCamera" position=" 0 0 0"orientation="0 1 0 0" fieldOfView=".5"/> <Transform DEF="Saturn" center="0 0 20"translation="0 0 -20" scale="4 4 4"> <Transform DEF="SaturnDay"> <Shape> <Appearance> <Material diffuseColor='1 1 1' specularColor='.1 .1 .1' shininess='0.9' /> <ImageTextureurl="./textureMaps/saturn.jpg"/> </Appearance> <IndexedFaceSet USE='Sphere_GEOMETRY' /> </Shape> </Transform>

Saturn's rings are just a fl at plane consis ng of two polygons and a texture map. A .gif image is used to allow transparent areas in the corners and the center where Saturn sits. Saturn's rings are slightly lted towards the Sun during the phases of its rota on around the Sun, as shown in the fi gure that follows this code:

<Transform DEF="rings" rotation="1 0 0 .2"> <Shape> <Appearance> <Material diffuseColor='1 1 1' specularColor='.2 .2 .2' shininess='0.8' emissiveColor=".1 .1 .1"/> <ImageTexture

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Building Great Web3D

34

url="./textureMaps/SaturnRings.gif"/> </Appearance> <IndexedFaceSet coordIndex="0 1 2 -1 2 3 0 -1 2 1 0 -1 0 3 2 -1"texCoordIndex="0 1 2 -1 2 3 0 -1 2 1 0 -1 0 3 2 -1"> <Coordinate point="-4 0 4 4 0 4 4 0 -4 -4 0 -4"/> <TextureCoordinate point="0 0 1 0 1 1 0 1"/> </IndexedFaceSet> </Shape> </Transform> </Transform></Transform>

Anima on is a series of <TimeSensor>, <OrientationInterpolator>, and <ROUTE> func ons. The frac on of me is sent via the <ROUTE> node from <TimeSensor> to the interpolator, which uses another <ROUTE> node to update the rota on or posi on in the object's <Transform> node in order to allow rota on of the Earth around the Sun as the fi rst four statements show in the following code. The next set of three statements control the seasonal lt of the Earth using the same <TimeSensor> node with a rota on around the z axis of +/- 0.4 radians. The day rota on for the Earth has its own four statements to control the 24-hour day, animated as one second. The Moon has its own independent anima on and fi nally, the camera focused on the Earth uses the same <TimeSensor> node as the Earth's year and seasons. However, the cameras focused on the Earth, the Earth's annual rota on, and the Earth's seasons have their own <OrientationInterpolator> nodes. Saturn has its own interpolators to rotate around the Sun and for its own day, but this is not shown in the following code:

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Project 1

35

<TimeSensor DEF="yearTimer" cycleInterval="36.5" loop="true"/><OrientationInterpolator DEF="yearlyRotation" key="0 .5 1"keyValue="0 1 0 0 0 1 0 3.14 0 1 0 6.28"/><ROUTE fromField="fraction_changed" fromNode="yearTimer"toField="set_fraction" toNode="yearlyRotation"/><ROUTE fromField="value_changed" fromNode="yearlyRotation"toField="rotation" toNode="Earth"/>

Earth's seasonal rota on, which has a lt of 0.4 radians, is demonstrated in the following code:

<OrientationInterpolator DEF="seasonalRotation" key="0 .5 1"keyValue="0 0 1 .4 0 0 1 -.4 0 0 1 .4"/><ROUTE fromField="fraction_changed" fromNode="yearTimer"toField="set_fraction" toNode="seasonalRotation"/><ROUTE fromField="value_changed" fromNode="seasonalRotation"toField="rotation" toNode="Earth-Season"/>

Earth's day rota on, set to 1 second, is demonstrated in the following code:

<TimeSensor DEF="EarthDayTimer" cycleInterval="1" loop="true"/><OrientationInterpolator DEF="EarthDayRotation" key="0 .5 1"keyValue="0 1 0 0 0 1 0 3.14 0 1 0 6.28"/><ROUTE fromField="fraction_changed" fromNode="EarthDayTimer"toField="set_fraction" toNode="EarthDayRotation"/><ROUTE fromField="value_changed" fromNode="EarthDayRotation"toField="rotation" toNode="Earth-Day"/>

The Moon's rota on around the Earth is set to 5.8 seconds and is demonstrated in the following code:

<TimeSensor DEF="moonTimer" cycleInterval="5.8" loop="true"/><OrientationInterpolator DEF="YRotMoon" key="0 .5 1"keyValue="0 1 0 0 0 1 0 3.14 0 1 0 6.28"/><ROUTE fromField="fraction_changed" fromNode="moonTimer"toField="set_fraction" toNode="YRotMoon"/><ROUTE fromField="value_changed" fromNode="YRotMoon"toField="rotation" toNode="Moon"/>

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Building Great Web3D

36

To ensure that our camera stays focused on the Earth, the <Viewpoint> node is also animated using the same year mer as the Earth, as shown in the following code:

<OrientationInterpolator DEF="EarthCameraRotation" key="0 .5 1"keyValue="0 1 0 0 0 1 0 3.14 0 1 0 6.28"/><ROUTE fromField="fraction_changed" fromNode="yearTimer"toField="set_fraction" toNode="EarthCameraRotation"/><ROUTE fromField="value_changed" fromNode="EarthCameraRotation"toField="orientation" toNode="EarthCamera"/>

The images in the preceding fi gure show the views from Saturn's and Earth's cameras, two of the four cameras in the scene. To track planets, the user requires HTML bu ons to navigate from one planet to the next. Clicking on the Sun or Earth will also take the user to the respec ve cameras. Bu ons for X3D on a web page use the same bu ons as any HTML page. What is unique for X3D is that element ID's such as aboveCamera and mainCamera are the ID values for the <Viewpoint> nodes in X3D. The setAttribute('set_bind', 'true') method, also a part of X3D, sets this as the new camera posi on, as shown in the following code:

<input type="button" value="Solar System View"onclick="document.getElementById('aboveCamera').setAttribute('set_ bind','true');" /><input type="button" value="Sun"onclick="document.getElementById('mainCamera').setAttribute('set_b ind','true');" /><input type="button" value="Earth"onclick="document.getElementById('EarthCamera').setAttribute('set_ bind','true');" /><input type="button" value="Saturn"onclick="document.getElementById('SaturnCamera').setAttribute('set _bind','true');" />

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Project 1

37

Some of the images in the preceding fi gure look pixelated or led. This is partly due to the default shader language and will be addressed as we go further in WebGL.

Objective complete – mini debriefi ngIf you are new to the crea on of 3D, one of the most fun aspects is the instant gra fi ca on from crea ng 3D scenes. In the subsequent projects, we will apply 3D graphics to familiar applica ons and see the places where 3D can be a more eff ec ve communica on tool for users.

Mission accomplishedWe covered a great deal of ground in understanding the fundamentals of 3D graphics: basic objects such as boxes and spheres, the crea on of more complex objects using indexed face sets, texture maps, lights, viewpoints, anima on, and interac vity. From just what was introduced here plus a li le HTML and JavaScript, we can create vast worlds and applica ons. A er all, if we can create a Solar System in an introduc on, we can pre y much go anywhere.

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book

Where to buy this book You can buy WebGL HOTSH T from the Packt Publishing website: http://www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-devices-using-webgl-hotshot/book. Free shipping to the US, UK, Europe and selected Asian countries. For more information, please read our shipping policy.

Alternatively, you can buy the book from Amazon, BN.com, Computer Manuals and most internet book retailers.

www.PacktPub.com

For More Information: www.packtpub.com/create-interactive-3D-content-for-web-pages-and-mobile-

devices-using-webgl-hotshot/book