WebGL hotshot

306 154 0
WebGL hotshot

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

www.it-ebooks.info WebGL HOTSH T Create interactive 3D content for web pages and mobile devices Mitch Williams BIRMINGHAM - MUMBAI www.it-ebooks.info WebGL HOTSH T Copyright © 2014 Packt Publishing All rights reserved No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews Every effort has been made in the preparation of this book to ensure the accuracy of the information presented However, the information contained in this book is sold without warranty, either express or implied Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals However, Packt Publishing cannot guarantee the accuracy of this information First published: May 2014 Production Reference: 1200514 Published by Packt Publishing Ltd Livery Place 35 Livery Street Birmingham B3 2PB, UK ISBN 978-1-78328-091-9 www.packtpub.com Cover Image by Michael Harms (kunstraum@googlemail.com) www.it-ebooks.info Credits Author Mitch Williams Project Coordinator Wendell Palmer Reviewers Andrea Barisone Proofreaders Simran Bhogal Dario Calonaci Maria Gould Jing Jin Paul Hindle Vincent Lark Indexer Mehreen Deshmukh Todd J Seiler Commissioning Editor Joanne Fitzpatrick Graphics Ronak Dhruv Valentina Dsilva Acquisition Editor Joanne Fitzpatrick Disha Haria Content Development Editor Neeshma Ramakrishnan Production Coordinator Shantanu Zagade Technical Editors Shruti Rawool Cover Work Shantanu Zagade Aman Preet Singh Copy Editors Tanvi Gaitonde Dipti Kapadia Aditya Nair www.it-ebooks.info 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 www.it-ebooks.info About the Reviewers Andrea Barisone works for a leading Italian IT company and has over 13 years of experience in Information Technology, working on corporate projects as a developer using different technologies He also has a strong experience in ECM Systems and has several J2EE certifications He has the ability to acquire new technologies and to exploit the knowledge acquired by working with different environments and technologies He was the technical reviewer for the following books: ff Agile Web Development with Rails 4, David Heinemeier Hansson, Sam Ruby, and Dave Thomas, Pragmatic Bookshelf ff BPEL and Java Cookbook, Jurij Laznik, Packt Publishing ff Learning Three.js: The JavaScript 3D Library for WebGL, Jos Dirksen, Packt Publishing ff Building Applications with ExtJS, Simon Elliston Ball, Packt Publishing (yet to be published) I would like to thank my parents, Renzo and Maria Carla; my beloved wife, Barbara; and my two wonderful little children, Gabriele and Aurora, for making every day of my life wonderful www.it-ebooks.info Dario Calonaci is a graphic designer specializing in typography and logo design He has worked for the United Nations conference RIO+20, and has worked with Node.js, which was selected for Obama for America His name and work has appeared in a book presentation in the Senate's library in Rome He has been teaching Web Design since he was 23 years old He is a member of FacultyRow, a New York-based association, as a valuable teacher and academic figure He has been invited to deliver talks as well as to conduct a workshop His works have been exposed in New York, internationally published and featured, and studied in a couple of theses You can learn more about him and see his works at http://dariocalonaci.com Jing Jin works at a game company as a technical artist She loves delving into new technologies that render game graphics better and more efficiently She's also interested in innovations that enable a variety of gaming experiences and bring novelty to traditional gaming Vincent Lark (@allyouneedisgnu) is a French developer in Luxembourg with six years of experience He worked as a full-stack developer in some large audience companies such as EuroDNS, Jamendo, and more recently, for a local news website for cross-border workers Interested in game development and 3D modeling since his school years, he's practicing these subjects in Global Game Jams and other hackathons with friends An open source fanatic, he shares every prototype on his GitHub account and tries to follow state-of-the-art web development Todd J Seiler works in the CAD/CAM dental industry as a graphics software engineer at E4D Technologies in Dallas, Texas He has worked as a software development engineer in Test on Games for Windows LIVE at Microsoft, and he has also worked in the mobile game development industry He has a B.S degree in Computer Graphics and Interactive Media from the University of Dubuque, Dubuque, Iowa with minors in Computer Information Systems He also has a B.S degree in Real-time Interactive Simulations from DigiPen Institute of Technology, Redmond, Washington, with minors in mathematics and physics In his spare time, he plays video games, studies Catholic apologetics and theology, writes books and articles, and toys with new tech when he can He periodically blogs about random things at http://www.toddseiler.com www.it-ebooks.info www.PacktPub.com Support files, eBooks, discount offers, and more You might want to visit www.PacktPub.com for support files and downloads related to your book Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy Get in touch with us at service@packtpub.com for more details At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks TM http://PacktLib.PacktPub.com Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library Here, you can access, read and search across Packt's entire library of books Why Subscribe? ff Fully searchable across every book published by Packt ff Copy and paste, print and bookmark content ff On demand and accessible via web browser Free Access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books Simply use your login credentials for immediate access www.it-ebooks.info www.it-ebooks.info Table of Contents Preface 1 Project 1: Building Great Web3D A second coming Comprehensive solutions Mission briefing Introduction to 3D fundamentals Transformations – translation, rotation, and scaling Lights, camera, action! Navigating between multiple viewpoints Animation with interpolators Adding texture maps to 3D meshes Lighting a scene and shading 3D objects with normals Creating an animated Solar System with multiple cameras for navigation Mission accomplished Project 2: WebGL for E-Commerce Mission briefing Introduction to WebGL WebGL 3D with Perspective View WebGL texture mapping and animation Loading a 3D modeled object, normals, and lighting Using the mouse for interactivity E-commerce using existing assets E-commerce with 3D modeling Mission accomplished www.it-ebooks.info 10 11 13 14 17 18 20 22 25 29 31 37 39 40 42 47 49 53 57 63 66 70 Project 10 To create transparencies, texture maps have a second texture known as the mask Pixels from the mask that are pure green (0, 255, 0) will be discarded, creating the transparency, as shown in the following screenshot: A red wagon with the mask I preferred having the second image as the mask If I had only one image with the wagon surrounded in green, the green would blend in with the red wagon due to the mipmap process Unfortunately, we were still left with some dotted white areas around each image One way to remove this is to have a white background, but a better solution would be to add additional black pixels to outline the object Since this scene is intended to be interactive, lighting was added that can be turned on by a checkbox Inside the fragment shader, we first add some ambient light If the pixel is close to pure green, we discard that pixel If the pixel is close to black, we retain it Otherwise, set the pixel to white and calculate its color based on the three color lights, as shown in the following code: void main(void) { vec3 lightWeighting = vec3(uAmbientLight, uAmbientLight, uAmbientLight); vec4 fragmentColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)); vec4 textureMaskColor = texture2D(uSamplerMask, vec2(vTextureCoord.s, vTextureCoord.t)); // if mask is green, discard the pixel making it transparent if ( (textureMaskColor.r < 05) && (textureMaskColor.g > 95) && (textureMaskColor.b < 05) ) { discard; } else { // if pixel is NOT black, make it pure white if ( (fragmentColor.r > 01) || (fragmentColor.g > 01) || (fragmentColor.b > 01) ) { fragmentColor.r = 1.0; 279 www.it-ebooks.info The New World of 3D Art fragmentColor.g = 1.0; fragmentColor.b = 1.0; } } // A red light at (-10, 0, -50), the green light // at (0, 10, -40) and the blue light at (10, 0, lightWeighting += vec3(1.0, 0.0, 0.0) * calculateLightContribution( vec3(-10.0, 0.0, vTransformedNormal); lightWeighting += vec3(0.0, 1.0, 0.0) * calculateLightContribution( vec3( 0.0, 10.0, vTransformedNormal); lightWeighting += vec3(0.0, 0.0, 1.0) * calculateLightContribution( vec3( 10.0, 0.0, vTransformedNormal); // any colors above if ( lightWeighting.r > if ( lightWeighting.g > if ( lightWeighting.b > -30) -50.0), -40.0), -30.0), must be capped at 1.0 ) lightWeighting.r = 1.0; 1.0 ) lightWeighting.g = 1.0; 1.0 ) lightWeighting.b = 1.0; gl_FragColor = vec4(fragmentColor.rgb * lightWeighting, 1.0); } Much of the calculateLightContribution() function is simplified from the previous museum example; however, we don't have to calculate bump and normal maps nor spot lights This is shown in the following code: float calculateLightContribution(vec3 lightLoc, vec3 pixelNormal) { vec3 distanceLightToPixel = vec3(vPosition.xyz - lightLoc); vec3 vectorLightPosToPixel = normalize(distanceLightToPixel); float angleBetweenLightAndNormal = dot( -vectorLightPosToPixel, pixelNormal ); // if the angle is > 90 degrees (where cos(angle) < 0), // then no light hits this pixel if (angleBetweenLightAndNormal < 0.0) angleBetweenLightAndNormal = 0.0; // calculate attenuation (fall off of light over distance) float maxDist = 40.0; float attenuation = 0.0; if ( uUseAttenuation ) { if ( length(distanceLightToPixel) < maxDist ) { attenuation = (maxDist - length(distanceLightToPixel))/maxDist; } } 280 www.it-ebooks.info Project 10 float lightAmt = angleBetweenLightAndNormal * attenuation; return lightAmt; } In the renderer() function, we have to attach the correct mask with the object, so there are a series of if statements for each 3D mesh object This sends the mask to the GPU that is used inside the fragment shader, as seen in the following code: else if (meshObjectArray[i] == poster1Object) { if ( poster1Mask != null ) { gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, poster1Mask); gl.uniform1i(shaderProgram.samplerMaskUniform, 1); } } The results certainly create an interesting effect It also eliminates the white pixels that were seen to surround some of the items in the previous screenshot Red, green, and blue colored lights were placed in the foreground Using attenuation, objects in the distant background were slightly darker, which helped with our depth perception, as shown in the following screenshot: Removing the texture map colors and using red, green, and blue lights instead 281 www.it-ebooks.info The New World of 3D Art Cel shading is a popular technique for games and art to show depth Often, comic book characters have two tones—brighter colors for sunlight and slightly darker colors for shadows However, we aren't limited to two tones Previously, we checked to make sure no colors exceed 1.0 Now, we check if the red, green, or blue is 0.8 or greater, in which case we set these colors to 1.0 Any red, green, or blue amount from 0.6 to 0.8 will be set to 0.6, and so forth, as shown in the following code: // Only the red is shown Repeat for the green and blue if ( lightWeighting.r >= ) lightWeighting.r = 1.0; else if ( lightWeighting.r >= 0.6 ) lightWeighting.r = 0.6; else if ( lightWeighting.r >= 0.4 ) lightWeighting.r = 0.4; else if ( lightWeighting.r >= 0.2 ) lightWeighting.r = 0.2; else lightWeighting.r = 0.0; This is a great place to experiment with different values In addition, the background was changed to white to have the colors stand out better, as seen in the following screenshot: Cel shading effect inside the fragment shader 282 www.it-ebooks.info Project 10 One final addition to this 3D diorama is to get back to our original room For this, we deploy the same portal's previous demonstrations that we have been using; however, now the portal's camera is pointing to the original opening location Inside the handleKeys() function, we check if the camera's z value, eye[2], has reached a certain depth, and if so, we reset the camera's location based on the portal's point-of-view value, portal2eye, as presented in the code that follows the screenshot: A closer view of the portal that sends us back to our original location function handleKeys() { if (currentlyPressedKeys[38]){//up arrow, camera moves forward eye[0] += Math.sin( cameraRotation ) * 4; eye[2] -= Math.cos( cameraRotation ) * 4; // check if we transport back to the original location if ( eye[2]

Ngày đăng: 27/03/2019, 14:56

Từ khóa liên quan

Mục lục

  • Cover

  • Copyright

  • Credits

  • About the Author

  • About the Reviewers

  • www.PacktPub.com

  • Table of Contents

  • Preface

  • Project 1: Building Great Web3D

    • A second coming

    • Comprehensive solutions

    • Mission briefing

    • Introduction to 3D fundamentals

    • Transformations – translation, rotation, and scaling

    • Lights, camera, action!

    • Navigating between multiple viewpoints

    • Animation with interpolators

    • Adding texture maps to 3D meshes

    • Lighting a scene and shading 3D objects with normals

    • Creating an animated Solar System with multiple cameras for navigation

    • Mission accomplished

Tài liệu cùng người dùng

Tài liệu liên quan